* Added templatelinks table. The table currently represents a literal list of templat...
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 /**
3 * File for articles
4 * @package MediaWiki
5 */
6
7 /**
8 * Need the CacheManager to be loaded
9 */
10 require_once( 'CacheManager.php' );
11 require_once( 'Revision.php' );
12
13 $wgArticleCurContentFields = false;
14 $wgArticleOldContentFields = false;
15
16 /**
17 * Class representing a MediaWiki article and history.
18 *
19 * See design.txt for an overview.
20 * Note: edit user interface and cache support functions have been
21 * moved to separate EditPage and CacheManager classes.
22 *
23 * @package MediaWiki
24 */
25 class Article {
26 /**#@+
27 * @access private
28 */
29 var $mContent, $mContentLoaded;
30 var $mUser, $mTimestamp, $mUserText;
31 var $mCounter, $mComment, $mGoodAdjustment, $mTotalAdjustment;
32 var $mMinorEdit, $mRedirectedFrom;
33 var $mTouched, $mFileCache, $mTitle;
34 var $mId, $mTable;
35 var $mForUpdate;
36 var $mOldId;
37 var $mRevIdFetched;
38 var $mRevision;
39 var $mRedirectUrl;
40 /**#@-*/
41
42 /**
43 * Constructor and clear the article
44 * @param Title &$title
45 * @param integer $oldId Revision ID, null to fetch from request, zero for current
46 */
47 function Article( &$title, $oldId = null ) {
48 $this->mTitle =& $title;
49 $this->mOldId = $oldId;
50 $this->clear();
51 }
52
53 /**
54 * get the title object of the article
55 * @public
56 */
57 function getTitle() {
58 return $this->mTitle;
59 }
60
61 /**
62 * Clear the object
63 * @private
64 */
65 function clear() {
66 $this->mDataLoaded = false;
67 $this->mContentLoaded = false;
68
69 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
70 $this->mRedirectedFrom = $this->mUserText =
71 $this->mTimestamp = $this->mComment = $this->mFileCache = '';
72 $this->mGoodAdjustment = $this->mTotalAdjustment = 0;
73 $this->mTouched = '19700101000000';
74 $this->mForUpdate = false;
75 $this->mIsRedirect = false;
76 $this->mRevIdFetched = 0;
77 $this->mRedirectUrl = false;
78 }
79
80 /**
81 * Note that getContent/loadContent may follow redirects if
82 * not told otherwise, and so may cause a change to mTitle.
83 *
84 * @param $noredir
85 * @return Return the text of this revision
86 */
87 function getContent( $noredir ) {
88 global $wgRequest, $wgUser, $wgOut;
89
90 # Get variables from query string :P
91 $action = $wgRequest->getText( 'action', 'view' );
92 $section = $wgRequest->getText( 'section' );
93 $preload = $wgRequest->getText( 'preload' );
94
95 $fname = 'Article::getContent';
96 wfProfileIn( $fname );
97
98 if ( 0 == $this->getID() ) {
99 if ( 'edit' == $action ) {
100 wfProfileOut( $fname );
101
102 # If requested, preload some text.
103 $text=$this->getPreloadedText($preload);
104
105 # We used to put MediaWiki:Newarticletext here if
106 # $text was empty at this point.
107 # This is now shown above the edit box instead.
108 return $text;
109 }
110 wfProfileOut( $fname );
111 $wgOut->setRobotpolicy( 'noindex,nofollow' );
112
113 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
114 $ret = wfMsgWeirdKey ( $this->mTitle->getText() ) ;
115 } else {
116 $ret = wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' );
117 }
118
119 return "<div class='noarticletext'>$ret</div>";
120 } else {
121 $this->loadContent( $noredir );
122 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
123 if ( $this->mTitle->getNamespace() == NS_USER_TALK &&
124 $wgUser->isIP($this->mTitle->getText()) &&
125 $action=='view'
126 ) {
127 wfProfileOut( $fname );
128 return $this->mContent . "\n" .wfMsg('anontalkpagetext');
129 } else {
130 if($action=='edit') {
131 if($section!='') {
132 if($section=='new') {
133 wfProfileOut( $fname );
134 $text=$this->getPreloadedText($preload);
135 return $text;
136 }
137
138 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
139 # comments to be stripped as well)
140 $rv=$this->getSection($this->mContent,$section);
141 wfProfileOut( $fname );
142 return $rv;
143 }
144 }
145 wfProfileOut( $fname );
146 return $this->mContent;
147 }
148 }
149 }
150
151 /**
152 This function accepts a title string as parameter
153 ($preload). If this string is non-empty, it attempts
154 to fetch the current revision text. It respects
155 <includeonly>.
156 */
157 function getPreloadedText($preload) {
158 if($preload) {
159 $preloadTitle=Title::newFromText($preload);
160 if(isset($preloadTitle) && $preloadTitle->userCanRead()) {
161 $rev=Revision::newFromTitle($preloadTitle);
162 if($rev) {
163 $text=$rev->getText();
164 $text=preg_replace('/<\/?includeonly>/i','',$text);
165 return $text;
166 }
167 }
168 }
169 return '';
170 }
171
172 /**
173 * This function returns the text of a section, specified by a number ($section).
174 * A section is text under a heading like == Heading == or <h1>Heading</h1>, or
175 * the first section before any such heading (section 0).
176 *
177 * If a section contains subsections, these are also returned.
178 *
179 * @param string $text text to look in
180 * @param integer $section section number
181 * @return string text of the requested section
182 */
183 function getSection($text,$section) {
184
185 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
186 # comments to be stripped as well)
187 $striparray=array();
188 $parser=new Parser();
189 $parser->mOutputType=OT_WIKI;
190 $parser->mOptions = new ParserOptions();
191 $striptext=$parser->strip($text, $striparray, true);
192
193 # now that we can be sure that no pseudo-sections are in the source,
194 # split it up by section
195 $secs =
196 preg_split(
197 '/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
198 $striptext, -1,
199 PREG_SPLIT_DELIM_CAPTURE);
200 if($section==0) {
201 $rv=$secs[0];
202 } else {
203 $headline=$secs[$section*2-1];
204 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
205 $hlevel=$matches[1];
206
207 # translate wiki heading into level
208 if(strpos($hlevel,'=')!==false) {
209 $hlevel=strlen($hlevel);
210 }
211
212 $rv=$headline. $secs[$section*2];
213 $count=$section+1;
214
215 $break=false;
216 while(!empty($secs[$count*2-1]) && !$break) {
217
218 $subheadline=$secs[$count*2-1];
219 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
220 $subhlevel=$matches[1];
221 if(strpos($subhlevel,'=')!==false) {
222 $subhlevel=strlen($subhlevel);
223 }
224 if($subhlevel > $hlevel) {
225 $rv.=$subheadline.$secs[$count*2];
226 }
227 if($subhlevel <= $hlevel) {
228 $break=true;
229 }
230 $count++;
231
232 }
233 }
234 # reinsert stripped tags
235 $rv=$parser->unstrip($rv,$striparray);
236 $rv=$parser->unstripNoWiki($rv,$striparray);
237 $rv=trim($rv);
238 return $rv;
239
240 }
241
242 /**
243 * Return the oldid of the article that is to be shown, 0 for the current revision
244 */
245 function getOldID() {
246 if ( is_null( $this->mOldId ) ) {
247 $this->mOldId = $this->getOldIDFromRequest();
248 }
249 return $this->mOldId;
250 }
251
252 /**
253 * Get the old ID from the request, return it.
254 * Sets $this->mRedirectUrl to a correct URL if the query parameters are incorrect
255 */
256 function getOldIDFromRequest() {
257 global $wgRequest;
258 $this->mRedirectUrl = false;
259 $oldid = $wgRequest->getVal( 'oldid' );
260 if ( isset( $oldid ) ) {
261 $oldid = intval( $oldid );
262 if ( $wgRequest->getVal( 'direction' ) == 'next' ) {
263 $nextid = $this->mTitle->getNextRevisionID( $oldid );
264 if ( $nextid ) {
265 $oldid = $nextid;
266 } else {
267 $this->mRedirectUrl = $this->mTitle->getFullURL( 'redirect=no' );
268 }
269 } elseif ( $wgRequest->getVal( 'direction' ) == 'prev' ) {
270 $previd = $this->mTitle->getPreviousRevisionID( $oldid );
271 if ( $previd ) {
272 $oldid = $previd;
273 } else {
274 # TODO
275 }
276 }
277 $lastid = $oldid;
278 }
279 if ( !$oldid ) {
280 $oldid = 0;
281 }
282 return $oldid;
283 }
284
285 /**
286 * Load the revision (including text) into this object
287 */
288 function loadContent( $noredir = false ) {
289 global $wgOut, $wgRequest;
290
291 if ( $this->mContentLoaded ) return;
292
293 # Query variables :P
294 $oldid = $this->getOldID();
295 $redirect = $wgRequest->getVal( 'redirect' );
296
297 $fname = 'Article::loadContent';
298
299 # Pre-fill content with error message so that if something
300 # fails we'll have something telling us what we intended.
301
302 $t = $this->mTitle->getPrefixedText();
303
304 $noredir = $noredir || ($wgRequest->getVal( 'redirect' ) == 'no')
305 || $wgRequest->getCheck( 'rdfrom' );
306 $this->mOldId = $oldid;
307 $this->fetchContent( $oldid, $noredir, true );
308 }
309
310
311 /**
312 * Fetch a page record with the given conditions
313 * @param Database $dbr
314 * @param array $conditions
315 * @access private
316 */
317 function pageData( &$dbr, $conditions ) {
318 $fields = array(
319 'page_id',
320 'page_namespace',
321 'page_title',
322 'page_restrictions',
323 'page_counter',
324 'page_is_redirect',
325 'page_is_new',
326 'page_random',
327 'page_touched',
328 'page_latest',
329 'page_len' ) ;
330 wfRunHooks( 'ArticlePageDataBefore', array( &$this , &$fields ) ) ;
331 $row = $dbr->selectRow( 'page',
332 $fields,
333 $conditions,
334 'Article::pageData' );
335 wfRunHooks( 'ArticlePageDataAfter', array( &$this , &$row ) ) ;
336 return $row ;
337 }
338
339 function pageDataFromTitle( &$dbr, $title ) {
340 return $this->pageData( $dbr, array(
341 'page_namespace' => $title->getNamespace(),
342 'page_title' => $title->getDBkey() ) );
343 }
344
345 function pageDataFromId( &$dbr, $id ) {
346 return $this->pageData( $dbr, array(
347 'page_id' => intval( $id ) ) );
348 }
349
350 /**
351 * Set the general counter, title etc data loaded from
352 * some source.
353 *
354 * @param object $data
355 * @access private
356 */
357 function loadPageData( $data ) {
358 $this->mTitle->loadRestrictions( $data->page_restrictions );
359 $this->mTitle->mRestrictionsLoaded = true;
360
361 $this->mCounter = $data->page_counter;
362 $this->mTouched = wfTimestamp( TS_MW, $data->page_touched );
363 $this->mIsRedirect = $data->page_is_redirect;
364 $this->mLatest = $data->page_latest;
365
366 $this->mDataLoaded = true;
367 }
368
369 /**
370 * Get text of an article from database
371 * @param int $oldid 0 for whatever the latest revision is
372 * @param bool $noredir Set to false to follow redirects
373 * @param bool $globalTitle Set to true to change the global $wgTitle object when following redirects or other unexpected title changes
374 * @return string
375 */
376 function fetchContent( $oldid = 0, $noredir = true, $globalTitle = false ) {
377 if ( $this->mContentLoaded ) {
378 return $this->mContent;
379 }
380
381 $dbr =& $this->getDB();
382 $fname = 'Article::fetchContent';
383
384 # Pre-fill content with error message so that if something
385 # fails we'll have something telling us what we intended.
386 $t = $this->mTitle->getPrefixedText();
387 if( $oldid ) {
388 $t .= ',oldid='.$oldid;
389 }
390 if( isset( $redirect ) ) {
391 $redirect = ($redirect == 'no') ? 'no' : 'yes';
392 $t .= ',redirect='.$redirect;
393 }
394 $this->mContent = wfMsg( 'missingarticle', $t ) ;
395
396 if( $oldid ) {
397 $revision = Revision::newFromId( $oldid );
398 if( is_null( $revision ) ) {
399 wfDebug( "$fname failed to retrieve specified revision, id $oldid\n" );
400 return false;
401 }
402 $data = $this->pageDataFromId( $dbr, $revision->getPage() );
403 if( !$data ) {
404 wfDebug( "$fname failed to get page data linked to revision id $oldid\n" );
405 return false;
406 }
407 $this->mTitle = Title::makeTitle( $data->page_namespace, $data->page_title );
408 $this->loadPageData( $data );
409 } else {
410 if( !$this->mDataLoaded ) {
411 $data = $this->pageDataFromTitle( $dbr, $this->mTitle );
412 if( !$data ) {
413 wfDebug( "$fname failed to find page data for title " . $this->mTitle->getPrefixedText() . "\n" );
414 return false;
415 }
416 $this->loadPageData( $data );
417 }
418 $revision = Revision::newFromId( $this->mLatest );
419 if( is_null( $revision ) ) {
420 wfDebug( "$fname failed to retrieve current page, rev_id $data->page_latest\n" );
421 return false;
422 }
423 }
424
425 # If we got a redirect, follow it (unless we've been told
426 # not to by either the function parameter or the query
427 if ( !$oldid && !$noredir ) {
428 $rt = Title::newFromRedirect( $revision->getText() );
429 # process if title object is valid and not special:userlogout
430 if ( $rt && ! ( $rt->getNamespace() == NS_SPECIAL && $rt->getText() == 'Userlogout' ) ) {
431 # Gotta hand redirects to special pages differently:
432 # Fill the HTTP response "Location" header and ignore
433 # the rest of the page we're on.
434 global $wgDisableHardRedirects;
435 if( $globalTitle && !$wgDisableHardRedirects ) {
436 global $wgOut;
437 if ( $rt->getInterwiki() != '' && $rt->isLocal() ) {
438 $source = $this->mTitle->getFullURL( 'redirect=no' );
439 $wgOut->redirect( $rt->getFullURL( 'rdfrom=' . urlencode( $source ) ) ) ;
440 return false;
441 }
442 if ( $rt->getNamespace() == NS_SPECIAL ) {
443 $wgOut->redirect( $rt->getFullURL() );
444 return false;
445 }
446 }
447 if( $rt->getInterwiki() == '' ) {
448 $redirData = $this->pageDataFromTitle( $dbr, $rt );
449 if( $redirData ) {
450 $redirRev = Revision::newFromId( $redirData->page_latest );
451 if( !is_null( $redirRev ) ) {
452 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
453 $this->mTitle = $rt;
454 $data = $redirData;
455 $this->loadPageData( $data );
456 $revision = $redirRev;
457 }
458 }
459 }
460 }
461 }
462
463 # if the title's different from expected, update...
464 if( $globalTitle ) {
465 global $wgTitle;
466 if( !$this->mTitle->equals( $wgTitle ) ) {
467 $wgTitle = $this->mTitle;
468 }
469 }
470
471 # Back to the business at hand...
472 $this->mContent = $revision->getText();
473
474 $this->mUser = $revision->getUser();
475 $this->mUserText = $revision->getUserText();
476 $this->mComment = $revision->getComment();
477 $this->mTimestamp = wfTimestamp( TS_MW, $revision->getTimestamp() );
478
479 $this->mRevIdFetched = $revision->getID();
480 $this->mContentLoaded = true;
481 $this->mRevision =& $revision;
482
483 wfRunHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) ) ;
484
485 return $this->mContent;
486 }
487
488 /**
489 * Gets the article text without using so many damn globals
490 * Returns false on error
491 *
492 * @param integer $oldid
493 */
494 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
495 return $this->fetchContent( $oldid, $noredir, false );
496 }
497
498 /**
499 * Read/write accessor to select FOR UPDATE
500 */
501 function forUpdate( $x = NULL ) {
502 return wfSetVar( $this->mForUpdate, $x );
503 }
504
505 /**
506 * Get the database which should be used for reads
507 */
508 function &getDB() {
509 $ret =& wfGetDB( DB_MASTER );
510 return $ret;
511 #if ( $this->mForUpdate ) {
512 $ret =& wfGetDB( DB_MASTER );
513 #} else {
514 # $ret =& wfGetDB( DB_SLAVE );
515 #}
516 return $ret;
517 }
518
519 /**
520 * Get options for all SELECT statements
521 * Can pass an option array, to which the class-wide options will be appended
522 */
523 function getSelectOptions( $options = '' ) {
524 if ( $this->mForUpdate ) {
525 if ( is_array( $options ) ) {
526 $options[] = 'FOR UPDATE';
527 } else {
528 $options = 'FOR UPDATE';
529 }
530 }
531 return $options;
532 }
533
534 /**
535 * Return the Article ID
536 */
537 function getID() {
538 if( $this->mTitle ) {
539 return $this->mTitle->getArticleID();
540 } else {
541 return 0;
542 }
543 }
544
545 /**
546 * Returns true if this article exists in the database.
547 * @return bool
548 */
549 function exists() {
550 return $this->getId() != 0;
551 }
552
553 /**
554 * Get the view count for this article
555 */
556 function getCount() {
557 if ( -1 == $this->mCounter ) {
558 $id = $this->getID();
559 $dbr =& $this->getDB();
560 $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
561 'Article::getCount', $this->getSelectOptions() );
562 }
563 return $this->mCounter;
564 }
565
566 /**
567 * Would the given text make this article a "good" article (i.e.,
568 * suitable for including in the article count)?
569 * @param string $text Text to analyze
570 * @return integer 1 if it can be counted else 0
571 */
572 function isCountable( $text ) {
573 global $wgUseCommaCount;
574
575 if ( NS_MAIN != $this->mTitle->getNamespace() ) { return 0; }
576 if ( $this->isRedirect( $text ) ) { return 0; }
577 $token = ($wgUseCommaCount ? ',' : '[[' );
578 if ( false === strstr( $text, $token ) ) { return 0; }
579 return 1;
580 }
581
582 /**
583 * Tests if the article text represents a redirect
584 */
585 function isRedirect( $text = false ) {
586 if ( $text === false ) {
587 $this->loadContent();
588 $titleObj = Title::newFromRedirect( $this->fetchContent() );
589 } else {
590 $titleObj = Title::newFromRedirect( $text );
591 }
592 return $titleObj !== NULL;
593 }
594
595 /**
596 * Returns true if the currently-referenced revision is the current edit
597 * to this page (and it exists).
598 * @return bool
599 */
600 function isCurrent() {
601 return $this->exists() &&
602 isset( $this->mRevision ) &&
603 $this->mRevision->isCurrent();
604 }
605
606 /**
607 * Loads everything except the text
608 * This isn't necessary for all uses, so it's only done if needed.
609 * @private
610 */
611 function loadLastEdit() {
612 global $wgOut;
613
614 if ( -1 != $this->mUser )
615 return;
616
617 # New or non-existent articles have no user information
618 $id = $this->getID();
619 if ( 0 == $id ) return;
620
621 $this->mLastRevision = Revision::loadFromPageId( $this->getDB(), $id );
622 if( !is_null( $this->mLastRevision ) ) {
623 $this->mUser = $this->mLastRevision->getUser();
624 $this->mUserText = $this->mLastRevision->getUserText();
625 $this->mTimestamp = $this->mLastRevision->getTimestamp();
626 $this->mComment = $this->mLastRevision->getComment();
627 $this->mMinorEdit = $this->mLastRevision->isMinor();
628 $this->mRevIdFetched = $this->mLastRevision->getID();
629 }
630 }
631
632 function getTimestamp() {
633 $this->loadLastEdit();
634 return wfTimestamp(TS_MW, $this->mTimestamp);
635 }
636
637 function getUser() {
638 $this->loadLastEdit();
639 return $this->mUser;
640 }
641
642 function getUserText() {
643 $this->loadLastEdit();
644 return $this->mUserText;
645 }
646
647 function getComment() {
648 $this->loadLastEdit();
649 return $this->mComment;
650 }
651
652 function getMinorEdit() {
653 $this->loadLastEdit();
654 return $this->mMinorEdit;
655 }
656
657 function getRevIdFetched() {
658 $this->loadLastEdit();
659 return $this->mRevIdFetched;
660 }
661
662 function getContributors($limit = 0, $offset = 0) {
663 $fname = 'Article::getContributors';
664
665 # XXX: this is expensive; cache this info somewhere.
666
667 $title = $this->mTitle;
668 $contribs = array();
669 $dbr =& $this->getDB();
670 $revTable = $dbr->tableName( 'revision' );
671 $userTable = $dbr->tableName( 'user' );
672 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
673 $ns = $title->getNamespace();
674 $user = $this->getUser();
675 $pageId = $this->getId();
676
677 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
678 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
679 WHERE rev_page = $pageId
680 AND rev_user != $user
681 GROUP BY rev_user, rev_user_text, user_real_name
682 ORDER BY timestamp DESC";
683
684 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
685 $sql .= ' '. $this->getSelectOptions();
686
687 $res = $dbr->query($sql, $fname);
688
689 while ( $line = $dbr->fetchObject( $res ) ) {
690 $contribs[] = array($line->rev_user, $line->rev_user_text, $line->user_real_name);
691 }
692
693 $dbr->freeResult($res);
694 return $contribs;
695 }
696
697 /**
698 * This is the default action of the script: just view the page of
699 * the given title.
700 */
701 function view() {
702 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgContLang;
703 global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
704 global $wgParserCache, $wgUseTrackbacks;
705 $sk = $wgUser->getSkin();
706
707 $fname = 'Article::view';
708 wfProfileIn( $fname );
709 # Get variables from query string
710 $oldid = $this->getOldID();
711
712 # getOldID may want us to redirect somewhere else
713 if ( $this->mRedirectUrl ) {
714 $wgOut->redirect( $this->mRedirectUrl );
715 wfProfileOut( $fname );
716 return;
717 }
718
719 $diff = $wgRequest->getVal( 'diff' );
720 $rcid = $wgRequest->getVal( 'rcid' );
721 $rdfrom = $wgRequest->getVal( 'rdfrom' );
722
723 $wgOut->setArticleFlag( true );
724 $wgOut->setRobotpolicy( 'index,follow' );
725 # If we got diff and oldid in the query, we want to see a
726 # diff page instead of the article.
727
728 if ( !is_null( $diff ) ) {
729 require_once( 'DifferenceEngine.php' );
730 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
731
732 $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid );
733 // DifferenceEngine directly fetched the revision:
734 $this->mRevIdFetched = $de->mNewid;
735 $de->showDiffPage();
736
737 if( $diff == 0 ) {
738 # Run view updates for current revision only
739 $this->viewUpdates();
740 }
741 wfProfileOut( $fname );
742 return;
743 }
744
745 if ( empty( $oldid ) && $this->checkTouched() ) {
746 $wgOut->setETag($wgParserCache->getETag($this, $wgUser));
747
748 if( $wgOut->checkLastModified( $this->mTouched ) ){
749 wfProfileOut( $fname );
750 return;
751 } else if ( $this->tryFileCache() ) {
752 # tell wgOut that output is taken care of
753 $wgOut->disable();
754 $this->viewUpdates();
755 wfProfileOut( $fname );
756 return;
757 }
758 }
759 # Should the parser cache be used?
760 $pcache = $wgEnableParserCache &&
761 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
762 $this->exists() &&
763 empty( $oldid );
764 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
765 if ( $wgUser->getOption( 'stubthreshold' ) ) {
766 wfIncrStats( 'pcache_miss_stub' );
767 }
768
769 $outputDone = false;
770 if ( $pcache ) {
771 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
772 $outputDone = true;
773 }
774 }
775 if ( !$outputDone ) {
776 $text = $this->getContent( false ); # May change mTitle by following a redirect
777 if ( $text === false ) {
778 # Failed to load, replace text with error message
779 $t = $this->mTitle->getPrefixedText();
780 if( $oldid ) {
781 $t .= ',oldid='.$oldid;
782 }
783 if( isset( $redirect ) ) {
784 $redirect = ($redirect == 'no') ? 'no' : 'yes';
785 $t .= ',redirect='.$redirect;
786 }
787 $text = wfMsg( 'missingarticle', $t );
788 }
789
790 # Another whitelist check in case oldid or redirects are altering the title
791 if ( !$this->mTitle->userCanRead() ) {
792 $wgOut->loginToUse();
793 $wgOut->output();
794 exit;
795 }
796
797 # We're looking at an old revision
798
799 if ( !empty( $oldid ) ) {
800 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
801 $wgOut->setRobotpolicy( 'noindex,follow' );
802 }
803 $wasRedirected = false;
804 if ( '' != $this->mRedirectedFrom ) {
805 if ( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
806 $sk = $wgUser->getSkin();
807 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, '', 'redirect=no' );
808 $s = wfMsg( 'redirectedfrom', $redir );
809 $wgOut->setSubtitle( $s );
810
811 // Check the parser cache again, for the target page
812 if( $pcache ) {
813 if( $wgOut->tryParserCache( $this, $wgUser ) ) {
814 $outputDone = true;
815 }
816 }
817 $wasRedirected = true;
818 }
819 } elseif ( !empty( $rdfrom ) ) {
820 global $wgRedirectSources;
821 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
822 $sk = $wgUser->getSkin();
823 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
824 $s = wfMsg( 'redirectedfrom', $redir );
825 $wgOut->setSubtitle( $s );
826 $wasRedirected = true;
827 }
828 }
829 }
830 if( !$outputDone ) {
831 /**
832 * @fixme: this hook doesn't work most of the time, as it doesn't
833 * trigger when the parser cache is used.
834 */
835 wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
836 # wrap user css and user js in pre and don't parse
837 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
838 if (
839 $this->mTitle->getNamespace() == NS_USER &&
840 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
841 ) {
842 $wgOut->setRevisionId( $this->getRevIdFetched() );
843 $wgOut->addWikiText( wfMsg('clearyourcache'));
844 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
845 } else if ( $rt = Title::newFromRedirect( $text ) ) {
846 # Display redirect
847 $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
848 $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
849 if( !$wasRedirected ) {
850 $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
851 }
852 $targetUrl = $rt->escapeLocalURL();
853 $titleText = htmlspecialchars( $rt->getPrefixedText() );
854 $link = $sk->makeLinkObj( $rt );
855
856 $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
857 '<span class="redirectText">'.$link.'</span>' );
858
859 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
860 $catlinks = $parseout->getCategoryLinks();
861 $wgOut->addCategoryLinks($catlinks);
862 $skin = $wgUser->getSkin();
863 } else if ( $pcache ) {
864 # Display content and save to parser cache
865 $wgOut->setRevisionId( $this->getRevIdFetched() );
866 $wgOut->addPrimaryWikiText( $text, $this );
867 } else {
868 # Display content, don't attempt to save to parser cache
869
870 # Don't show section-edit links on old revisions... this way lies madness.
871 if( !$this->isCurrent() ) {
872 $oldEditSectionSetting = $wgOut->mParserOptions->setEditSection( false );
873 }
874 $wgOut->setRevisionId( $this->getRevIdFetched() );
875 $wgOut->addWikiText( $text );
876
877 if( !$this->isCurrent() ) {
878 $wgOut->mParserOptions->setEditSection( $oldEditSectionSetting );
879 }
880 }
881 }
882 /* title may have been set from the cache */
883 $t = $wgOut->getPageTitle();
884 if( empty( $t ) ) {
885 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
886 }
887
888 # If we have been passed an &rcid= parameter, we want to give the user a
889 # chance to mark this new article as patrolled.
890 if ( $wgUseRCPatrol
891 && !is_null($rcid)
892 && $rcid != 0
893 && $wgUser->isLoggedIn()
894 && ( $wgUser->isAllowed('patrol') || !$wgOnlySysopsCanPatrol ) )
895 {
896 $wgOut->addHTML(
897 "<div class='patrollink'>" .
898 wfMsg ( 'markaspatrolledlink',
899 $sk->makeKnownLinkObj( $this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
900 ) .
901 '</div>'
902 );
903 }
904
905 # Trackbacks
906 if ($wgUseTrackbacks)
907 $this->addTrackbacks();
908
909 $this->viewUpdates();
910 wfProfileOut( $fname );
911 }
912
913 function addTrackbacks() {
914 global $wgOut, $wgUser;
915
916 $dbr =& wfGetDB(DB_SLAVE);
917 $tbs = $dbr->select(
918 /* FROM */ 'trackbacks',
919 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
920 /* WHERE */ array('tb_page' => $this->getID())
921 );
922
923 if (!$dbr->numrows($tbs))
924 return;
925
926 $tbtext = "";
927 while ($o = $dbr->fetchObject($tbs)) {
928 $rmvtxt = "";
929 if ($wgUser->isSysop()) {
930 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
931 . $o->tb_id . "&token=" . $wgUser->editToken());
932 $rmvtxt = wfMsg('trackbackremove', $delurl);
933 }
934 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
935 $o->tb_title,
936 $o->tb_url,
937 $o->tb_ex,
938 $o->tb_name,
939 $rmvtxt);
940 }
941 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
942 }
943
944 function deletetrackback() {
945 global $wgUser, $wgRequest, $wgOut, $wgTitle;
946
947 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
948 $wgOut->addWikitext(wfMsg('sessionfailure'));
949 return;
950 }
951
952 if ((!$wgUser->isAllowed('delete'))) {
953 $wgOut->sysopRequired();
954 return;
955 }
956
957 if (wfReadOnly()) {
958 $wgOut->readOnlyPage();
959 return;
960 }
961
962 $db =& wfGetDB(DB_MASTER);
963 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
964 $wgTitle->invalidateCache();
965 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
966 }
967
968 function render() {
969 global $wgOut;
970
971 $wgOut->setArticleBodyOnly(true);
972 $this->view();
973 }
974
975 function purge() {
976 global $wgUser, $wgRequest, $wgOut, $wgUseSquid;
977
978 if ( $wgUser->isLoggedIn() || $wgRequest->wasPosted() ) {
979 // Invalidate the cache
980 $this->mTitle->invalidateCache();
981
982 if ( $wgUseSquid ) {
983 // Commit the transaction before the purge is sent
984 $dbw = wfGetDB( DB_MASTER );
985 $dbw->immediateCommit();
986
987 // Send purge
988 $update = SquidUpdate::newSimplePurge( $this->mTitle );
989 $update->doUpdate();
990 }
991 $this->view();
992 } else {
993 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
994 $action = $this->mTitle->escapeLocalURL( 'action=purge' );
995 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
996 $msg = str_replace( '$1',
997 "<form method=\"post\" action=\"$action\">\n" .
998 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
999 "</form>\n", $msg );
1000
1001 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
1002 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1003 $wgOut->addHTML( $msg );
1004 }
1005 }
1006
1007 /**
1008 * Insert a new empty page record for this article.
1009 * This *must* be followed up by creating a revision
1010 * and running $this->updateToLatest( $rev_id );
1011 * or else the record will be left in a funky state.
1012 * Best if all done inside a transaction.
1013 *
1014 * @param Database $dbw
1015 * @param string $restrictions
1016 * @return int The newly created page_id key
1017 * @access private
1018 */
1019 function insertOn( &$dbw, $restrictions = '' ) {
1020 $fname = 'Article::insertOn';
1021 wfProfileIn( $fname );
1022
1023 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
1024 $dbw->insert( 'page', array(
1025 'page_id' => $page_id,
1026 'page_namespace' => $this->mTitle->getNamespace(),
1027 'page_title' => $this->mTitle->getDBkey(),
1028 'page_counter' => 0,
1029 'page_restrictions' => $restrictions,
1030 'page_is_redirect' => 0, # Will set this shortly...
1031 'page_is_new' => 1,
1032 'page_random' => wfRandom(),
1033 'page_touched' => $dbw->timestamp(),
1034 'page_latest' => 0, # Fill this in shortly...
1035 'page_len' => 0, # Fill this in shortly...
1036 ), $fname );
1037 $newid = $dbw->insertId();
1038
1039 $this->mTitle->resetArticleId( $newid );
1040
1041 wfProfileOut( $fname );
1042 return $newid;
1043 }
1044
1045 /**
1046 * Update the page record to point to a newly saved revision.
1047 *
1048 * @param Database $dbw
1049 * @param Revision $revision -- for ID number, and text used to set
1050 length and redirect status fields
1051 * @param int $lastRevision -- if given, will not overwrite the page field
1052 * when different from the currently set value.
1053 * Giving 0 indicates the new page flag should
1054 * be set on.
1055 * @return bool true on success, false on failure
1056 * @access private
1057 */
1058 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1059 $fname = 'Article::updateToRevision';
1060 wfProfileIn( $fname );
1061
1062 $conditions = array( 'page_id' => $this->getId() );
1063 if( !is_null( $lastRevision ) ) {
1064 # An extra check against threads stepping on each other
1065 $conditions['page_latest'] = $lastRevision;
1066 }
1067
1068 $text = $revision->getText();
1069 $dbw->update( 'page',
1070 array( /* SET */
1071 'page_latest' => $revision->getId(),
1072 'page_touched' => $dbw->timestamp(),
1073 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1074 'page_is_redirect' => Article::isRedirect( $text ) ? 1 : 0,
1075 'page_len' => strlen( $text ),
1076 ),
1077 $conditions,
1078 $fname );
1079
1080 wfProfileOut( $fname );
1081 return ( $dbw->affectedRows() != 0 );
1082 }
1083
1084 /**
1085 * If the given revision is newer than the currently set page_latest,
1086 * update the page record. Otherwise, do nothing.
1087 *
1088 * @param Database $dbw
1089 * @param Revision $revision
1090 */
1091 function updateIfNewerOn( &$dbw, $revision ) {
1092 $fname = 'Article::updateIfNewerOn';
1093 wfProfileIn( $fname );
1094
1095 $row = $dbw->selectRow(
1096 array( 'revision', 'page' ),
1097 array( 'rev_id', 'rev_timestamp' ),
1098 array(
1099 'page_id' => $this->getId(),
1100 'page_latest=rev_id' ),
1101 $fname );
1102 if( $row ) {
1103 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1104 wfProfileOut( $fname );
1105 return false;
1106 }
1107 $prev = $row->rev_id;
1108 } else {
1109 # No or missing previous revision; mark the page as new
1110 $prev = 0;
1111 }
1112
1113 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1114 wfProfileOut( $fname );
1115 return $ret;
1116 }
1117
1118 /**
1119 * Theoretically we could defer these whole insert and update
1120 * functions for after display, but that's taking a big leap
1121 * of faith, and we want to be able to report database
1122 * errors at some point.
1123 * @private
1124 */
1125 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1126 global $wgOut, $wgUser, $wgUseSquid;
1127
1128 $fname = 'Article::insertNewArticle';
1129 wfProfileIn( $fname );
1130
1131 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1132 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1133 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1134 wfProfileOut( $fname );
1135 return false;
1136 }
1137
1138 $this->mGoodAdjustment = $this->isCountable( $text );
1139 $this->mTotalAdjustment = 1;
1140
1141 $ns = $this->mTitle->getNamespace();
1142 $ttl = $this->mTitle->getDBkey();
1143
1144 # If this is a comment, add the summary as headline
1145 if($comment && $summary!="") {
1146 $text="== {$summary} ==\n\n".$text;
1147 }
1148 $text = $this->preSaveTransform( $text );
1149 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ? 1 : 0;
1150 $now = wfTimestampNow();
1151
1152 $dbw =& wfGetDB( DB_MASTER );
1153
1154 # Add the page record; stake our claim on this title!
1155 $newid = $this->insertOn( $dbw );
1156
1157 # Save the revision text...
1158 $revision = new Revision( array(
1159 'page' => $newid,
1160 'comment' => $summary,
1161 'minor_edit' => $isminor,
1162 'text' => $text
1163 ) );
1164 $revisionId = $revision->insertOn( $dbw );
1165
1166 $this->mTitle->resetArticleID( $newid );
1167
1168 # Update the page record with revision data
1169 $this->updateRevisionOn( $dbw, $revision, 0 );
1170
1171 Article::onArticleCreate( $this->mTitle );
1172 if(!$suppressRC) {
1173 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, 'default',
1174 '', strlen( $text ), $revisionId );
1175 }
1176
1177 if ($watchthis) {
1178 if(!$this->mTitle->userIsWatching()) $this->watch();
1179 } else {
1180 if ( $this->mTitle->userIsWatching() ) {
1181 $this->unwatch();
1182 }
1183 }
1184
1185 # The talk page isn't in the regular link tables, so we need to update manually:
1186 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
1187 $dbw->update( 'page',
1188 array( 'page_touched' => $dbw->timestamp($now) ),
1189 array( 'page_namespace' => $talkns,
1190 'page_title' => $ttl ),
1191 $fname );
1192
1193 # standard deferred updates
1194 $this->editUpdates( $text, $summary, $isminor, $now, $revisionId );
1195
1196 $oldid = 0; # new article
1197 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1198
1199 wfRunHooks( 'ArticleInsertComplete', array( &$this, &$wgUser, $text,
1200 $summary, $isminor,
1201 $watchthis, NULL ) );
1202 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1203 $summary, $isminor,
1204 $watchthis, NULL ) );
1205 wfProfileOut( $fname );
1206 }
1207
1208 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
1209 $this->replaceSection( $section, $text, $summary, $edittime );
1210 }
1211
1212 /**
1213 * @return string Complete article text, or null if error
1214 */
1215 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1216 $fname = 'Article::replaceSection';
1217 wfProfileIn( $fname );
1218
1219 if ($section != '') {
1220 if( is_null( $edittime ) ) {
1221 $rev = Revision::newFromTitle( $this->mTitle );
1222 } else {
1223 $dbw =& wfGetDB( DB_MASTER );
1224 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1225 }
1226 if( is_null( $rev ) ) {
1227 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1228 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1229 return null;
1230 }
1231 $oldtext = $rev->getText();
1232
1233 if($section=='new') {
1234 if($summary) $subject="== {$summary} ==\n\n";
1235 $text=$oldtext."\n\n".$subject.$text;
1236 } else {
1237
1238 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1239 # comments to be stripped as well)
1240 $striparray=array();
1241 $parser=new Parser();
1242 $parser->mOutputType=OT_WIKI;
1243 $parser->mOptions = new ParserOptions();
1244 $oldtext=$parser->strip($oldtext, $striparray, true);
1245
1246 # now that we can be sure that no pseudo-sections are in the source,
1247 # split it up
1248 # Unfortunately we can't simply do a preg_replace because that might
1249 # replace the wrong section, so we have to use the section counter instead
1250 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
1251 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
1252 $secs[$section*2]=$text."\n\n"; // replace with edited
1253
1254 # section 0 is top (intro) section
1255 if($section!=0) {
1256
1257 # headline of old section - we need to go through this section
1258 # to determine if there are any subsections that now need to
1259 # be erased, as the mother section has been replaced with
1260 # the text of all subsections.
1261 $headline=$secs[$section*2-1];
1262 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
1263 $hlevel=$matches[1];
1264
1265 # determine headline level for wikimarkup headings
1266 if(strpos($hlevel,'=')!==false) {
1267 $hlevel=strlen($hlevel);
1268 }
1269
1270 $secs[$section*2-1]=''; // erase old headline
1271 $count=$section+1;
1272 $break=false;
1273 while(!empty($secs[$count*2-1]) && !$break) {
1274
1275 $subheadline=$secs[$count*2-1];
1276 preg_match(
1277 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1278 $subhlevel=$matches[1];
1279 if(strpos($subhlevel,'=')!==false) {
1280 $subhlevel=strlen($subhlevel);
1281 }
1282 if($subhlevel > $hlevel) {
1283 // erase old subsections
1284 $secs[$count*2-1]='';
1285 $secs[$count*2]='';
1286 }
1287 if($subhlevel <= $hlevel) {
1288 $break=true;
1289 }
1290 $count++;
1291
1292 }
1293
1294 }
1295 $text=join('',$secs);
1296 # reinsert the stuff that we stripped out earlier
1297 $text=$parser->unstrip($text,$striparray);
1298 $text=$parser->unstripNoWiki($text,$striparray);
1299 }
1300
1301 }
1302 wfProfileOut( $fname );
1303 return $text;
1304 }
1305
1306 /**
1307 * Change an existing article. Puts the previous version back into the old table, updates RC
1308 * and all necessary caches, mostly via the deferred update array.
1309 *
1310 * It is possible to call this function from a command-line script, but note that you should
1311 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1312 */
1313 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1314 global $wgOut, $wgUser, $wgDBtransactions, $wgMwRedir, $wgUseSquid;
1315 global $wgPostCommitUpdateList, $wgUseFileCache;
1316
1317 $fname = 'Article::updateArticle';
1318 wfProfileIn( $fname );
1319 $good = true;
1320
1321 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1322 &$summary, &$minor,
1323 &$watchthis, &$sectionanchor ) ) ) {
1324 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1325 wfProfileOut( $fname );
1326 return false;
1327 }
1328
1329 $isminor = ( $minor && $wgUser->isLoggedIn() );
1330 if ( $this->isRedirect( $text ) ) {
1331 # Remove all content but redirect
1332 # This could be done by reconstructing the redirect from a title given by
1333 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1334 # wants to see
1335 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1336 $redir = 1;
1337 $text = $m[1] . "\n";
1338 }
1339 }
1340 else { $redir = 0; }
1341
1342 $text = $this->preSaveTransform( $text );
1343 $dbw =& wfGetDB( DB_MASTER );
1344 $now = wfTimestampNow();
1345
1346 # Update article, but only if changed.
1347
1348 # It's important that we either rollback or complete, otherwise an attacker could
1349 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1350 # could conceivably have the same effect, especially if cur is locked for long periods.
1351 if( !$wgDBtransactions ) {
1352 $userAbort = ignore_user_abort( true );
1353 }
1354
1355 $oldtext = $this->getContent( true );
1356 $oldsize = strlen( $oldtext );
1357 $newsize = strlen( $text );
1358 $lastRevision = 0;
1359 $revisionId = 0;
1360
1361 if ( 0 != strcmp( $text, $oldtext ) ) {
1362 $this->mGoodAdjustment = $this->isCountable( $text )
1363 - $this->isCountable( $oldtext );
1364 $this->mTotalAdjustment = 0;
1365 $now = wfTimestampNow();
1366
1367 $lastRevision = $dbw->selectField(
1368 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1369
1370 $revision = new Revision( array(
1371 'page' => $this->getId(),
1372 'comment' => $summary,
1373 'minor_edit' => $isminor,
1374 'text' => $text
1375 ) );
1376
1377 $dbw->immediateCommit();
1378 $dbw->begin();
1379 $revisionId = $revision->insertOn( $dbw );
1380
1381 # Update page
1382 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1383
1384 if( !$ok ) {
1385 /* Belated edit conflict! Run away!! */
1386 $good = false;
1387 $dbw->rollback();
1388 } else {
1389 # Update recentchanges and purge cache and whatnot
1390 $bot = (int)($wgUser->isBot() || $forceBot);
1391 RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1392 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1393 $revisionId );
1394 $dbw->commit();
1395
1396 // Update caches outside the main transaction
1397 Article::onArticleEdit( $this->mTitle );
1398 }
1399 } else {
1400 // Keep the same revision ID, but do some updates on it
1401 $revisionId = $this->getRevIdFetched();
1402 }
1403
1404 if( !$wgDBtransactions ) {
1405 ignore_user_abort( $userAbort );
1406 }
1407
1408 if ( $good ) {
1409 if ($watchthis) {
1410 if (!$this->mTitle->userIsWatching()) {
1411 $dbw->immediateCommit();
1412 $dbw->begin();
1413 $this->watch();
1414 $dbw->commit();
1415 }
1416 } else {
1417 if ( $this->mTitle->userIsWatching() ) {
1418 $dbw->immediateCommit();
1419 $dbw->begin();
1420 $this->unwatch();
1421 $dbw->commit();
1422 }
1423 }
1424 # standard deferred updates
1425 $this->editUpdates( $text, $summary, $minor, $now, $revisionId );
1426
1427
1428 $urls = array();
1429 # Invalidate caches of all articles using this article as a template
1430
1431 # Template namespace
1432 # Purge all articles linking here
1433 $titles = $this->mTitle->getTemplateLinksTo();
1434 Title::touchArray( $titles );
1435 if ( $wgUseSquid ) {
1436 foreach ( $titles as $title ) {
1437 $urls[] = $title->getInternalURL();
1438 }
1439 }
1440
1441 # Squid updates
1442 if ( $wgUseSquid ) {
1443 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
1444 $u = new SquidUpdate( $urls );
1445 array_push( $wgPostCommitUpdateList, $u );
1446 }
1447
1448 # File cache
1449 if ( $wgUseFileCache ) {
1450 $cm = new CacheManager($this->mTitle);
1451 @unlink($cm->fileCacheName());
1452 }
1453
1454 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1455 }
1456 wfRunHooks( 'ArticleSaveComplete',
1457 array( &$this, &$wgUser, $text,
1458 $summary, $minor,
1459 $watchthis, $sectionanchor ) );
1460 wfProfileOut( $fname );
1461 return $good;
1462 }
1463
1464 /**
1465 * After we've either updated or inserted the article, update
1466 * the link tables and redirect to the new page.
1467 */
1468 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1469 global $wgOut, $wgUser;
1470 global $wgUseEnotif;
1471
1472 $fname = 'Article::showArticle';
1473 wfProfileIn( $fname );
1474
1475 # Output the redirect
1476 if( $this->isRedirect( $text ) )
1477 $r = 'redirect=no';
1478 else
1479 $r = '';
1480 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1481
1482 wfProfileOut( $fname );
1483 }
1484
1485 /**
1486 * Mark this particular edit as patrolled
1487 */
1488 function markpatrolled() {
1489 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1490 $wgOut->setRobotpolicy( 'noindex,follow' );
1491
1492 if ( !$wgUseRCPatrol )
1493 {
1494 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1495 return;
1496 }
1497 if ( $wgUser->isAnon() )
1498 {
1499 $wgOut->loginToUse();
1500 return;
1501 }
1502 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1503 {
1504 $wgOut->sysopRequired();
1505 return;
1506 }
1507 $rcid = $wgRequest->getVal( 'rcid' );
1508 if ( !is_null ( $rcid ) )
1509 {
1510 RecentChange::markPatrolled( $rcid );
1511 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1512 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1513
1514 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1515 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1516 }
1517 else
1518 {
1519 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1520 }
1521 }
1522
1523 /**
1524 * Add this page to $wgUser's watchlist
1525 */
1526
1527 function watch() {
1528
1529 global $wgUser, $wgOut;
1530
1531 if ( $wgUser->isAnon() ) {
1532 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1533 return;
1534 }
1535 if ( wfReadOnly() ) {
1536 $wgOut->readOnlyPage();
1537 return;
1538 }
1539
1540 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1541
1542 $wgUser->addWatch( $this->mTitle );
1543 $wgUser->saveSettings();
1544
1545 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1546
1547 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1548 $wgOut->setRobotpolicy( 'noindex,follow' );
1549
1550 $link = $this->mTitle->getPrefixedText();
1551 $text = wfMsg( 'addedwatchtext', $link );
1552 $wgOut->addWikiText( $text );
1553 }
1554
1555 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1556 }
1557
1558 /**
1559 * Stop watching a page
1560 */
1561
1562 function unwatch() {
1563
1564 global $wgUser, $wgOut;
1565
1566 if ( $wgUser->isAnon() ) {
1567 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1568 return;
1569 }
1570 if ( wfReadOnly() ) {
1571 $wgOut->readOnlyPage();
1572 return;
1573 }
1574
1575 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1576
1577 $wgUser->removeWatch( $this->mTitle );
1578 $wgUser->saveSettings();
1579
1580 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1581
1582 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1583 $wgOut->setRobotpolicy( 'noindex,follow' );
1584
1585 $link = $this->mTitle->getPrefixedText();
1586 $text = wfMsg( 'removedwatchtext', $link );
1587 $wgOut->addWikiText( $text );
1588 }
1589
1590 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1591 }
1592
1593 /**
1594 * action=protect handler
1595 */
1596 function protect() {
1597 require_once 'ProtectionForm.php';
1598 $form = new ProtectionForm( $this );
1599 $form->show();
1600 }
1601
1602 /**
1603 * action=unprotect handler (alias)
1604 */
1605 function unprotect() {
1606 $this->protect();
1607 }
1608
1609 /**
1610 * Update the article's restriction field, and leave a log entry.
1611 *
1612 * @param array $limit set of restriction keys
1613 * @param string $reason
1614 * @return bool true on success
1615 */
1616 function updateRestrictions( $limit = array(), $reason = '' ) {
1617 global $wgUser, $wgOut, $wgRequest;
1618
1619 if ( !$wgUser->isAllowed( 'protect' ) ) {
1620 return false;
1621 }
1622
1623 if( wfReadOnly() ) {
1624 return false;
1625 }
1626
1627 $id = $this->mTitle->getArticleID();
1628 if ( 0 == $id ) {
1629 return false;
1630 }
1631
1632 $flat = Article::flattenRestrictions( $limit );
1633 $protecting = ($flat != '');
1634
1635 if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser,
1636 $limit, $reason ) ) ) {
1637
1638 $dbw =& wfGetDB( DB_MASTER );
1639 $dbw->update( 'page',
1640 array( /* SET */
1641 'page_touched' => $dbw->timestamp(),
1642 'page_restrictions' => $flat
1643 ), array( /* WHERE */
1644 'page_id' => $id
1645 ), 'Article::protect'
1646 );
1647
1648 wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser,
1649 $limit, $reason ) );
1650
1651 $log = new LogPage( 'protect' );
1652 if( $protecting ) {
1653 $log->addEntry( 'protect', $this->mTitle, trim( $reason . " [$flat]" ) );
1654 } else {
1655 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1656 }
1657 }
1658 return true;
1659 }
1660
1661 /**
1662 * Take an array of page restrictions and flatten it to a string
1663 * suitable for insertion into the page_restrictions field.
1664 * @param array $limit
1665 * @return string
1666 * @access private
1667 */
1668 function flattenRestrictions( $limit ) {
1669 if( !is_array( $limit ) ) {
1670 wfDebugDieBacktrace( 'Article::flattenRestrictions given non-array restriction set' );
1671 }
1672 $bits = array();
1673 foreach( $limit as $action => $restrictions ) {
1674 if( $restrictions != '' ) {
1675 $bits[] = "$action=$restrictions";
1676 }
1677 }
1678 return implode( ':', $bits );
1679 }
1680
1681 /*
1682 * UI entry point for page deletion
1683 */
1684 function delete() {
1685 global $wgUser, $wgOut, $wgRequest;
1686 $fname = 'Article::delete';
1687 $confirm = $wgRequest->wasPosted() &&
1688 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1689 $reason = $wgRequest->getText( 'wpReason' );
1690
1691 # This code desperately needs to be totally rewritten
1692
1693 # Check permissions
1694 if( ( !$wgUser->isAllowed( 'delete' ) ) ) {
1695 $wgOut->sysopRequired();
1696 return;
1697 }
1698 if( wfReadOnly() ) {
1699 $wgOut->readOnlyPage();
1700 return;
1701 }
1702
1703 # Better double-check that it hasn't been deleted yet!
1704 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1705 if( !$this->mTitle->exists() ) {
1706 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1707 return;
1708 }
1709
1710 if( $confirm ) {
1711 $this->doDelete( $reason );
1712 return;
1713 }
1714
1715 # determine whether this page has earlier revisions
1716 # and insert a warning if it does
1717 # we select the text because it might be useful below
1718 $dbr =& $this->getDB();
1719 $ns = $this->mTitle->getNamespace();
1720 $title = $this->mTitle->getDBkey();
1721 $revisions = $dbr->select( array( 'page', 'revision' ),
1722 array( 'rev_id', 'rev_user_text' ),
1723 array(
1724 'page_namespace' => $ns,
1725 'page_title' => $title,
1726 'rev_page = page_id'
1727 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1728 );
1729
1730 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1731 $skin=$wgUser->getSkin();
1732 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1733 $wgOut->addHTML( $skin->historyLink() .'</b>');
1734 }
1735
1736 # Fetch article text
1737 $rev = Revision::newFromTitle( $this->mTitle );
1738
1739 # Fetch name(s) of contributors
1740 $rev_name = '';
1741 $all_same_user = true;
1742 while( $row = $dbr->fetchObject( $revisions ) ) {
1743 if( $rev_name != '' && $rev_name != $row->rev_user_text ) {
1744 $all_same_user = false;
1745 } else {
1746 $rev_name = $row->rev_user_text;
1747 }
1748 }
1749
1750 if( !is_null( $rev ) ) {
1751 # if this is a mini-text, we can paste part of it into the deletion reason
1752 $text = $rev->getText();
1753
1754 #if this is empty, an earlier revision may contain "useful" text
1755 $blanked = false;
1756 if( $text == '' ) {
1757 $prev = $rev->getPrevious();
1758 if( $prev ) {
1759 $text = $prev->getText();
1760 $blanked = true;
1761 }
1762 }
1763
1764 $length = strlen( $text );
1765
1766 # this should not happen, since it is not possible to store an empty, new
1767 # page. Let's insert a standard text in case it does, though
1768 if( $length == 0 && $reason === '' ) {
1769 $reason = wfMsgForContent( 'exblank' );
1770 }
1771
1772 if( $length < 500 && $reason === '' ) {
1773 # comment field=255, let's grep the first 150 to have some user
1774 # space left
1775 global $wgContLang;
1776 $text = $wgContLang->truncate( $text, 150, '...' );
1777
1778 # let's strip out newlines
1779 $text = preg_replace( "/[\n\r]/", '', $text );
1780
1781 if( !$blanked ) {
1782 if( !$all_same_user ) {
1783 $reason = wfMsgForContent( 'excontent', $text );
1784 } else {
1785 $reason = wfMsgForContent( 'excontentauthor', $text, $rev_name );
1786 }
1787 } else {
1788 $reason = wfMsgForContent( 'exbeforeblank', $text );
1789 }
1790 }
1791 }
1792
1793 return $this->confirmDelete( '', $reason );
1794 }
1795
1796 /**
1797 * Output deletion confirmation dialog
1798 */
1799 function confirmDelete( $par, $reason ) {
1800 global $wgOut, $wgUser;
1801
1802 wfDebug( "Article::confirmDelete\n" );
1803
1804 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1805 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1806 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1807 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1808
1809 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1810
1811 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1812 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1813 $token = htmlspecialchars( $wgUser->editToken() );
1814
1815 $wgOut->addHTML( "
1816 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1817 <table border='0'>
1818 <tr>
1819 <td align='right'>
1820 <label for='wpReason'>{$delcom}:</label>
1821 </td>
1822 <td align='left'>
1823 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1824 </td>
1825 </tr>
1826 <tr>
1827 <td>&nbsp;</td>
1828 <td>
1829 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1830 </td>
1831 </tr>
1832 </table>
1833 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1834 </form>\n" );
1835
1836 $wgOut->returnToMain( false );
1837 }
1838
1839
1840 /**
1841 * Perform a deletion and output success or failure messages
1842 */
1843 function doDelete( $reason ) {
1844 global $wgOut, $wgUser, $wgContLang;
1845 $fname = 'Article::doDelete';
1846 wfDebug( $fname."\n" );
1847
1848 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1849 if ( $this->doDeleteArticle( $reason ) ) {
1850 $deleted = $this->mTitle->getPrefixedText();
1851
1852 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1853 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1854
1855 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1856 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1857
1858 $wgOut->addWikiText( $text );
1859 $wgOut->returnToMain( false );
1860 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1861 } else {
1862 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1863 }
1864 }
1865 }
1866
1867 /**
1868 * Back-end article deletion
1869 * Deletes the article with database consistency, writes logs, purges caches
1870 * Returns success
1871 */
1872 function doDeleteArticle( $reason ) {
1873 global $wgUser, $wgUseSquid, $wgDeferredUpdateList;
1874 global $wgPostCommitUpdateList, $wgUseTrackbacks;
1875
1876 $fname = 'Article::doDeleteArticle';
1877 wfDebug( $fname."\n" );
1878
1879 $dbw =& wfGetDB( DB_MASTER );
1880 $ns = $this->mTitle->getNamespace();
1881 $t = $this->mTitle->getDBkey();
1882 $id = $this->mTitle->getArticleID();
1883
1884 if ( $t == '' || $id == 0 ) {
1885 return false;
1886 }
1887
1888 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ), -1 );
1889 array_push( $wgDeferredUpdateList, $u );
1890
1891 $linksTo = $this->mTitle->getLinksTo();
1892
1893 # Squid purging
1894 if ( $wgUseSquid ) {
1895 $urls = array(
1896 $this->mTitle->getInternalURL(),
1897 $this->mTitle->getInternalURL( 'history' )
1898 );
1899
1900 $u = SquidUpdate::newFromTitles( $linksTo, $urls );
1901 array_push( $wgPostCommitUpdateList, $u );
1902
1903 }
1904
1905 # Client and file cache invalidation
1906 Title::touchArray( $linksTo );
1907
1908
1909 // For now, shunt the revision data into the archive table.
1910 // Text is *not* removed from the text table; bulk storage
1911 // is left intact to avoid breaking block-compression or
1912 // immutable storage schemes.
1913 //
1914 // For backwards compatibility, note that some older archive
1915 // table entries will have ar_text and ar_flags fields still.
1916 //
1917 // In the future, we may keep revisions and mark them with
1918 // the rev_deleted field, which is reserved for this purpose.
1919 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1920 array(
1921 'ar_namespace' => 'page_namespace',
1922 'ar_title' => 'page_title',
1923 'ar_comment' => 'rev_comment',
1924 'ar_user' => 'rev_user',
1925 'ar_user_text' => 'rev_user_text',
1926 'ar_timestamp' => 'rev_timestamp',
1927 'ar_minor_edit' => 'rev_minor_edit',
1928 'ar_rev_id' => 'rev_id',
1929 'ar_text_id' => 'rev_text_id',
1930 ), array(
1931 'page_id' => $id,
1932 'page_id = rev_page'
1933 ), $fname
1934 );
1935
1936 # Now that it's safely backed up, delete it
1937 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1938 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1939
1940 if ($wgUseTrackbacks)
1941 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
1942
1943 # Clean up recentchanges entries...
1944 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1945
1946 # Finally, clean up the link tables
1947 $t = $this->mTitle->getPrefixedDBkey();
1948
1949 Article::onArticleDelete( $this->mTitle );
1950
1951 # Delete outgoing links
1952 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1953 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1954 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1955
1956 # Log the deletion
1957 $log = new LogPage( 'delete' );
1958 $log->addEntry( 'delete', $this->mTitle, $reason );
1959
1960 # Clear the cached article id so the interface doesn't act like we exist
1961 $this->mTitle->resetArticleID( 0 );
1962 $this->mTitle->mArticleID = 0;
1963 return true;
1964 }
1965
1966 /**
1967 * Revert a modification
1968 */
1969 function rollback() {
1970 global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
1971 $fname = 'Article::rollback';
1972
1973 if ( ! $wgUser->isAllowed('rollback') ) {
1974 $wgOut->sysopRequired();
1975 return;
1976 }
1977 if ( wfReadOnly() ) {
1978 $wgOut->readOnlyPage( $this->getContent( true ) );
1979 return;
1980 }
1981 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1982 array( $this->mTitle->getPrefixedText(),
1983 $wgRequest->getVal( 'from' ) ) ) ) {
1984 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1985 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1986 return;
1987 }
1988 $dbw =& wfGetDB( DB_MASTER );
1989
1990 # Enhanced rollback, marks edits rc_bot=1
1991 $bot = $wgRequest->getBool( 'bot' );
1992
1993 # Replace all this user's current edits with the next one down
1994 $tt = $this->mTitle->getDBKey();
1995 $n = $this->mTitle->getNamespace();
1996
1997 # Get the last editor, lock table exclusively
1998 $dbw->begin();
1999 $current = Revision::newFromTitle( $this->mTitle );
2000 if( is_null( $current ) ) {
2001 # Something wrong... no page?
2002 $dbw->rollback();
2003 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2004 return;
2005 }
2006
2007 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2008 if( $from != $current->getUserText() ) {
2009 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2010 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2011 htmlspecialchars( $this->mTitle->getPrefixedText()),
2012 htmlspecialchars( $from ),
2013 htmlspecialchars( $current->getUserText() ) ) );
2014 if( $current->getComment() != '') {
2015 $wgOut->addHTML(
2016 wfMsg( 'editcomment',
2017 htmlspecialchars( $current->getComment() ) ) );
2018 }
2019 return;
2020 }
2021
2022 # Get the last edit not by this guy
2023 $user = intval( $current->getUser() );
2024 $user_text = $dbw->addQuotes( $current->getUserText() );
2025 $s = $dbw->selectRow( 'revision',
2026 array( 'rev_id', 'rev_timestamp' ),
2027 array(
2028 'rev_page' => $current->getPage(),
2029 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2030 ), $fname,
2031 array(
2032 'USE INDEX' => 'page_timestamp',
2033 'ORDER BY' => 'rev_timestamp DESC' )
2034 );
2035 if( $s === false ) {
2036 # Something wrong
2037 $dbw->rollback();
2038 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2039 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2040 return;
2041 }
2042
2043 $set = array();
2044 if ( $bot ) {
2045 # Mark all reverted edits as bot
2046 $set['rc_bot'] = 1;
2047 }
2048 if ( $wgUseRCPatrol ) {
2049 # Mark all reverted edits as patrolled
2050 $set['rc_patrolled'] = 1;
2051 }
2052
2053 if ( $set ) {
2054 $dbw->update( 'recentchanges', $set,
2055 array( /* WHERE */
2056 'rc_cur_id' => $current->getPage(),
2057 'rc_user_text' => $current->getUserText(),
2058 "rc_timestamp > '{$s->rev_timestamp}'",
2059 ), $fname
2060 );
2061 }
2062
2063 # Get the edit summary
2064 $target = Revision::newFromId( $s->rev_id );
2065 $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2066 $newComment = $wgRequest->getText( 'summary', $newComment );
2067
2068 # Save it!
2069 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2070 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2071 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
2072
2073 $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle->userIsWatching(), $bot );
2074 Article::onArticleEdit( $this->mTitle );
2075
2076 $dbw->commit();
2077 $wgOut->returnToMain( false );
2078 }
2079
2080
2081 /**
2082 * Do standard deferred updates after page view
2083 * @private
2084 */
2085 function viewUpdates() {
2086 global $wgDeferredUpdateList;
2087
2088 if ( 0 != $this->getID() ) {
2089 global $wgDisableCounters;
2090 if( !$wgDisableCounters ) {
2091 Article::incViewCount( $this->getID() );
2092 $u = new SiteStatsUpdate( 1, 0, 0 );
2093 array_push( $wgDeferredUpdateList, $u );
2094 }
2095 }
2096
2097 # Update newtalk / watchlist notification status
2098 global $wgUser;
2099 $wgUser->clearNotification( $this->mTitle );
2100 }
2101
2102 /**
2103 * Do standard deferred updates after page edit.
2104 * Every 1000th edit, prune the recent changes table.
2105 * @private
2106 * @param string $text
2107 */
2108 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange, $newid) {
2109 global $wgDeferredUpdateList, $wgMessageCache, $wgUser, $wgParser, $wgParserCache;
2110
2111 $fname = 'Article::editUpdates';
2112 wfProfileIn( $fname );
2113
2114 # Parse the text
2115 $options = new ParserOptions;
2116 $poutput = $wgParser->parse( $text, $this->mTitle, $options, true, true, $newid );
2117
2118 # Save it to the parser cache
2119 $wgParserCache->save( $poutput, $this, $wgUser );
2120
2121 # Update the links tables
2122 $u = new LinksUpdate( $this->mTitle, $poutput );
2123 $u->doUpdate();
2124
2125 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
2126 wfSeedRandom();
2127 if ( 0 == mt_rand( 0, 999 ) ) {
2128 # Periodically flush old entries from the recentchanges table.
2129 global $wgRCMaxAge;
2130
2131 $dbw =& wfGetDB( DB_MASTER );
2132 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2133 $recentchanges = $dbw->tableName( 'recentchanges' );
2134 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2135 $dbw->query( $sql );
2136 }
2137 }
2138
2139 $id = $this->getID();
2140 $title = $this->mTitle->getPrefixedDBkey();
2141 $shortTitle = $this->mTitle->getDBkey();
2142
2143 if ( 0 == $id ) {
2144 wfProfileOut( $fname );
2145 return;
2146 }
2147
2148 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2149 array_push( $wgDeferredUpdateList, $u );
2150 $u = new SearchUpdate( $id, $title, $text );
2151 array_push( $wgDeferredUpdateList, $u );
2152
2153 # If this is another user's talk page, update newtalk
2154
2155 if ($this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName()) {
2156 $other = User::newFromName( $shortTitle );
2157 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2158 // An anonymous user
2159 $other = new User();
2160 $other->setName( $shortTitle );
2161 }
2162 if( $other ) {
2163 $other->setNewtalk( true );
2164 }
2165 }
2166
2167 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2168 $wgMessageCache->replace( $shortTitle, $text );
2169 }
2170
2171 wfProfileOut( $fname );
2172 }
2173
2174 /**
2175 * @todo document this function
2176 * @private
2177 * @param string $oldid Revision ID of this article revision
2178 */
2179 function setOldSubtitle( $oldid=0 ) {
2180 global $wgLang, $wgOut, $wgUser;
2181
2182 $current = ( $oldid == $this->mLatest );
2183 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2184 $sk = $wgUser->getSkin();
2185 $lnk = $current
2186 ? wfMsg( 'currentrevisionlink' )
2187 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2188 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
2189 $nextlink = $current
2190 ? wfMsg( 'nextrevision' )
2191 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2192 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2193 $wgOut->setSubtitle( $r );
2194 }
2195
2196 /**
2197 * This function is called right before saving the wikitext,
2198 * so we can do things like signatures and links-in-context.
2199 *
2200 * @param string $text
2201 */
2202 function preSaveTransform( $text ) {
2203 global $wgParser, $wgUser;
2204 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2205 }
2206
2207 /* Caching functions */
2208
2209 /**
2210 * checkLastModified returns true if it has taken care of all
2211 * output to the client that is necessary for this request.
2212 * (that is, it has sent a cached version of the page)
2213 */
2214 function tryFileCache() {
2215 static $called = false;
2216 if( $called ) {
2217 wfDebug( " tryFileCache() -- called twice!?\n" );
2218 return;
2219 }
2220 $called = true;
2221 if($this->isFileCacheable()) {
2222 $touched = $this->mTouched;
2223 $cache = new CacheManager( $this->mTitle );
2224 if($cache->isFileCacheGood( $touched )) {
2225 global $wgOut;
2226 wfDebug( " tryFileCache() - about to load\n" );
2227 $cache->loadFromFileCache();
2228 return true;
2229 } else {
2230 wfDebug( " tryFileCache() - starting buffer\n" );
2231 ob_start( array(&$cache, 'saveToFileCache' ) );
2232 }
2233 } else {
2234 wfDebug( " tryFileCache() - not cacheable\n" );
2235 }
2236 }
2237
2238 /**
2239 * Check if the page can be cached
2240 * @return bool
2241 */
2242 function isFileCacheable() {
2243 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2244 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2245
2246 return $wgUseFileCache
2247 and (!$wgShowIPinHeader)
2248 and ($this->getID() != 0)
2249 and ($wgUser->isAnon())
2250 and (!$wgUser->getNewtalk())
2251 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2252 and (empty( $action ) || $action == 'view')
2253 and (!isset($oldid))
2254 and (!isset($diff))
2255 and (!isset($redirect))
2256 and (!isset($printable))
2257 and (!$this->mRedirectedFrom);
2258 }
2259
2260 /**
2261 * Loads page_touched and returns a value indicating if it should be used
2262 *
2263 */
2264 function checkTouched() {
2265 $fname = 'Article::checkTouched';
2266 if( !$this->mDataLoaded ) {
2267 $dbr =& $this->getDB();
2268 $data = $this->pageDataFromId( $dbr, $this->getId() );
2269 if( $data ) {
2270 $this->loadPageData( $data );
2271 }
2272 }
2273 return !$this->mIsRedirect;
2274 }
2275
2276 /**
2277 * Get the page_touched field
2278 */
2279 function getTouched() {
2280 # Ensure that page data has been loaded
2281 if( !$this->mDataLoaded ) {
2282 $dbr =& $this->getDB();
2283 $data = $this->pageDataFromId( $dbr, $this->getId() );
2284 if( $data ) {
2285 $this->loadPageData( $data );
2286 }
2287 }
2288 return $this->mTouched;
2289 }
2290
2291 /**
2292 * Edit an article without doing all that other stuff
2293 * The article must already exist; link tables etc
2294 * are not updated, caches are not flushed.
2295 *
2296 * @param string $text text submitted
2297 * @param string $comment comment submitted
2298 * @param bool $minor whereas it's a minor modification
2299 */
2300 function quickEdit( $text, $comment = '', $minor = 0 ) {
2301 $fname = 'Article::quickEdit';
2302 wfProfileIn( $fname );
2303
2304 $dbw =& wfGetDB( DB_MASTER );
2305 $dbw->begin();
2306 $revision = new Revision( array(
2307 'page' => $this->getId(),
2308 'text' => $text,
2309 'comment' => $comment,
2310 'minor_edit' => $minor ? 1 : 0,
2311 ) );
2312 $revisionId = $revision->insertOn( $dbw );
2313 $this->updateRevisionOn( $dbw, $revision );
2314 $dbw->commit();
2315
2316 wfProfileOut( $fname );
2317 }
2318
2319 /**
2320 * Used to increment the view counter
2321 *
2322 * @static
2323 * @param integer $id article id
2324 */
2325 function incViewCount( $id ) {
2326 $id = intval( $id );
2327 global $wgHitcounterUpdateFreq;
2328
2329 $dbw =& wfGetDB( DB_MASTER );
2330 $pageTable = $dbw->tableName( 'page' );
2331 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2332 $acchitsTable = $dbw->tableName( 'acchits' );
2333
2334 if( $wgHitcounterUpdateFreq <= 1 ){ //
2335 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2336 return;
2337 }
2338
2339 # Not important enough to warrant an error page in case of failure
2340 $oldignore = $dbw->ignoreErrors( true );
2341
2342 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2343
2344 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2345 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2346 # Most of the time (or on SQL errors), skip row count check
2347 $dbw->ignoreErrors( $oldignore );
2348 return;
2349 }
2350
2351 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2352 $row = $dbw->fetchObject( $res );
2353 $rown = intval( $row->n );
2354 if( $rown >= $wgHitcounterUpdateFreq ){
2355 wfProfileIn( 'Article::incViewCount-collect' );
2356 $old_user_abort = ignore_user_abort( true );
2357
2358 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2359 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2360 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2361 'GROUP BY hc_id');
2362 $dbw->query("DELETE FROM $hitcounterTable");
2363 $dbw->query('UNLOCK TABLES');
2364 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2365 'WHERE page_id = hc_id');
2366 $dbw->query("DROP TABLE $acchitsTable");
2367
2368 ignore_user_abort( $old_user_abort );
2369 wfProfileOut( 'Article::incViewCount-collect' );
2370 }
2371 $dbw->ignoreErrors( $oldignore );
2372 }
2373
2374 /**#@+
2375 * The onArticle*() functions are supposed to be a kind of hooks
2376 * which should be called whenever any of the specified actions
2377 * are done.
2378 *
2379 * This is a good place to put code to clear caches, for instance.
2380 *
2381 * This is called on page move and undelete, as well as edit
2382 * @static
2383 * @param $title_obj a title object
2384 */
2385
2386 function onArticleCreate($title_obj) {
2387 global $wgUseSquid, $wgPostCommitUpdateList;
2388
2389 $title_obj->touchLinks();
2390 $titles = $title_obj->getLinksTo();
2391
2392 # Purge squid
2393 if ( $wgUseSquid ) {
2394 $urls = $title_obj->getSquidURLs();
2395 foreach ( $titles as $linkTitle ) {
2396 $urls[] = $linkTitle->getInternalURL();
2397 }
2398 $u = new SquidUpdate( $urls );
2399 array_push( $wgPostCommitUpdateList, $u );
2400 }
2401 }
2402
2403 function onArticleDelete( $title ) {
2404 global $wgMessageCache;
2405
2406 $title->touchLinks();
2407
2408 if( $title->getNamespace() == NS_MEDIAWIKI) {
2409 $wgMessageCache->replace( $title->getDBkey(), false );
2410 }
2411 }
2412
2413 /**
2414 * Purge caches on page update etc
2415 */
2416 function onArticleEdit( $title ) {
2417 global $wgUseSquid, $wgPostCommitUpdateList, $wgUseFileCache;
2418
2419 $urls = array();
2420
2421 // Template namespace? Purge all articles linking here.
2422 // FIXME: When a templatelinks table arrives, use it for all includes.
2423 if ( $title->getNamespace() == NS_TEMPLATE) {
2424 $titles = $title->getLinksTo();
2425 Title::touchArray( $titles );
2426 if ( $wgUseSquid ) {
2427 foreach ( $titles as $link ) {
2428 $urls[] = $link->getInternalURL();
2429 }
2430 }
2431 }
2432
2433 # Squid updates
2434 if ( $wgUseSquid ) {
2435 $urls = array_merge( $urls, $title->getSquidURLs() );
2436 $u = new SquidUpdate( $urls );
2437 array_push( $wgPostCommitUpdateList, $u );
2438 }
2439
2440 # File cache
2441 if ( $wgUseFileCache ) {
2442 $cm = new CacheManager( $title );
2443 @unlink( $cm->fileCacheName() );
2444 }
2445 }
2446
2447 /**#@-*/
2448
2449 /**
2450 * Info about this page
2451 * Called for ?action=info when $wgAllowPageInfo is on.
2452 *
2453 * @access public
2454 */
2455 function info() {
2456 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2457 $fname = 'Article::info';
2458
2459 if ( !$wgAllowPageInfo ) {
2460 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2461 return;
2462 }
2463
2464 $page = $this->mTitle->getSubjectPage();
2465
2466 $wgOut->setPagetitle( $page->getPrefixedText() );
2467 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2468
2469 # first, see if the page exists at all.
2470 $exists = $page->getArticleId() != 0;
2471 if( !$exists ) {
2472 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2473 $wgOut->addHTML(wfMsgWeirdKey ( $this->mTitle->getText() ) );
2474 } else {
2475 $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2476 }
2477 } else {
2478 $dbr =& $this->getDB( DB_SLAVE );
2479 $wl_clause = array(
2480 'wl_title' => $page->getDBkey(),
2481 'wl_namespace' => $page->getNamespace() );
2482 $numwatchers = $dbr->selectField(
2483 'watchlist',
2484 'COUNT(*)',
2485 $wl_clause,
2486 $fname,
2487 $this->getSelectOptions() );
2488
2489 $pageInfo = $this->pageCountInfo( $page );
2490 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2491
2492 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2493 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2494 if( $talkInfo ) {
2495 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2496 }
2497 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2498 if( $talkInfo ) {
2499 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2500 }
2501 $wgOut->addHTML( '</ul>' );
2502
2503 }
2504 }
2505
2506 /**
2507 * Return the total number of edits and number of unique editors
2508 * on a given page. If page does not exist, returns false.
2509 *
2510 * @param Title $title
2511 * @return array
2512 * @access private
2513 */
2514 function pageCountInfo( $title ) {
2515 $id = $title->getArticleId();
2516 if( $id == 0 ) {
2517 return false;
2518 }
2519
2520 $dbr =& $this->getDB( DB_SLAVE );
2521
2522 $rev_clause = array( 'rev_page' => $id );
2523 $fname = 'Article::pageCountInfo';
2524
2525 $edits = $dbr->selectField(
2526 'revision',
2527 'COUNT(rev_page)',
2528 $rev_clause,
2529 $fname,
2530 $this->getSelectOptions() );
2531
2532 $authors = $dbr->selectField(
2533 'revision',
2534 'COUNT(DISTINCT rev_user_text)',
2535 $rev_clause,
2536 $fname,
2537 $this->getSelectOptions() );
2538
2539 return array( 'edits' => $edits, 'authors' => $authors );
2540 }
2541
2542 /**
2543 * Return a list of templates used by this article.
2544 * Uses the templatelinks table
2545 *
2546 * @return array Array of Title objects
2547 */
2548 function getUsedTemplates() {
2549 $result = array();
2550 $id = $this->mTitle->getArticleID();
2551
2552 $dbr =& wfGetDB( DB_SLAVE );
2553 $res = $dbr->select( array( 'templatelinks' ),
2554 array( 'tl_namespace', 'tl_title' ),
2555 array( 'tl_from' => $id ),
2556 'Article:getUsedTemplates' );
2557 if ( false !== $res ) {
2558 if ( $dbr->numRows( $res ) ) {
2559 while ( $row = $dbr->fetchObject( $res ) ) {
2560 $result[] = Title::makeTitle( $row->tl_namespace, $row->tl_title );
2561 }
2562 }
2563 }
2564 $dbr->freeResult( $res );
2565 return $result;
2566 }
2567 }
2568
2569 ?>