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