hack support for <includeonly> into preload parameter so that categories can
[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->addPrimaryWikiText( $text, $this );
814 } else {
815 # Display content, don't attempt to save to parser cache
816
817 # Don't show section-edit links on old revisions... this way lies madness.
818 if( !$this->isCurrent() ) {
819 $oldEditSectionSetting = $wgOut->mParserOptions->setEditSection( false );
820 }
821 $wgOut->addWikiText( $text );
822
823 if( !$this->isCurrent() ) {
824 $wgOut->mParserOptions->setEditSection( $oldEditSectionSetting );
825 }
826 }
827 }
828 /* title may have been set from the cache */
829 $t = $wgOut->getPageTitle();
830 if( empty( $t ) ) {
831 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
832 }
833
834 # If we have been passed an &rcid= parameter, we want to give the user a
835 # chance to mark this new article as patrolled.
836 if ( $wgUseRCPatrol
837 && !is_null($rcid)
838 && $rcid != 0
839 && $wgUser->isLoggedIn()
840 && ( $wgUser->isAllowed('patrol') || !$wgOnlySysopsCanPatrol ) )
841 {
842 $wgOut->addHTML(
843 "<div class='patrollink'>" .
844 wfMsg ( 'markaspatrolledlink',
845 $sk->makeKnownLinkObj( $this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
846 ) .
847 '</div>'
848 );
849 }
850
851 # Trackbacks
852 if ($wgUseTrackbacks)
853 $this->addTrackbacks();
854
855 # Put link titles into the link cache
856 $wgOut->transformBuffer();
857
858 # Add link titles as META keywords
859 $wgOut->addMetaTags() ;
860
861 $this->viewUpdates();
862 wfProfileOut( $fname );
863 }
864
865 function addTrackbacks() {
866 global $wgOut, $wgUser;
867
868 $dbr =& wfGetDB(DB_SLAVE);
869 $tbs = $dbr->select(
870 /* FROM */ 'trackbacks',
871 /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
872 /* WHERE */ array('tb_page' => $this->getID())
873 );
874
875 if (!$dbr->numrows($tbs))
876 return;
877
878 $tbtext = "";
879 while ($o = $dbr->fetchObject($tbs)) {
880 $rmvtxt = "";
881 if ($wgUser->isSysop()) {
882 $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
883 . $o->tb_id . "&token=" . $wgUser->editToken());
884 $rmvtxt = wfMsg('trackbackremove', $delurl);
885 }
886 $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
887 $o->tb_title,
888 $o->tb_url,
889 $o->tb_ex,
890 $o->tb_name,
891 $rmvtxt);
892 }
893 $wgOut->addWikitext(wfMsg('trackbackbox', $tbtext));
894 }
895
896 function deletetrackback() {
897 global $wgUser, $wgRequest, $wgOut, $wgTitle;
898
899 if (!$wgUser->matchEditToken($wgRequest->getVal('token'))) {
900 $wgOut->addWikitext(wfMsg('sessionfailure'));
901 return;
902 }
903
904 if ((!$wgUser->isAllowed('delete'))) {
905 $wgOut->sysopRequired();
906 return;
907 }
908
909 if (wfReadOnly()) {
910 $wgOut->readOnlyPage();
911 return;
912 }
913
914 $db =& wfGetDB(DB_MASTER);
915 $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
916 $wgTitle->invalidateCache();
917 $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
918 }
919
920 function render() {
921 global $wgOut;
922
923 $wgOut->setArticleBodyOnly(true);
924 $this->view();
925 }
926
927 function purge() {
928 global $wgUser, $wgRequest, $wgOut, $wgUseSquid;
929
930 if ( $wgUser->isLoggedIn() || $wgRequest->wasPosted() ) {
931 // Invalidate the cache
932 $this->mTitle->invalidateCache();
933
934 if ( $wgUseSquid ) {
935 // Commit the transaction before the purge is sent
936 $dbw = wfGetDB( DB_MASTER );
937 $dbw->immediateCommit();
938
939 // Send purge
940 $update = SquidUpdate::newSimplePurge( $this->mTitle );
941 $update->doUpdate();
942 }
943 // Redirect to the article
944 $wgOut->redirect( $this->mTitle->getFullURL() );
945 } else {
946 $msg = $wgOut->parse( wfMsg( 'confirm_purge' ) );
947 $action = $this->mTitle->escapeLocalURL( 'action=purge' );
948 $button = htmlspecialchars( wfMsg( 'confirm_purge_button' ) );
949 $msg = str_replace( '$1',
950 "<form method=\"post\" action=\"$action\">\n" .
951 "<input type=\"submit\" name=\"submit\" value=\"$button\" />\n" .
952 "</form>\n", $msg );
953
954 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
955 $wgOut->setRobotpolicy( 'noindex,nofollow' );
956 $wgOut->addHTML( $msg );
957 }
958 }
959
960 /**
961 * Insert a new empty page record for this article.
962 * This *must* be followed up by creating a revision
963 * and running $this->updateToLatest( $rev_id );
964 * or else the record will be left in a funky state.
965 * Best if all done inside a transaction.
966 *
967 * @param Database $dbw
968 * @param string $restrictions
969 * @return int The newly created page_id key
970 * @access private
971 */
972 function insertOn( &$dbw, $restrictions = '' ) {
973 $fname = 'Article::insertOn';
974 wfProfileIn( $fname );
975
976 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
977 $dbw->insert( 'page', array(
978 'page_id' => $page_id,
979 'page_namespace' => $this->mTitle->getNamespace(),
980 'page_title' => $this->mTitle->getDBkey(),
981 'page_counter' => 0,
982 'page_restrictions' => $restrictions,
983 'page_is_redirect' => 0, # Will set this shortly...
984 'page_is_new' => 1,
985 'page_random' => wfRandom(),
986 'page_touched' => $dbw->timestamp(),
987 'page_latest' => 0, # Fill this in shortly...
988 'page_len' => 0, # Fill this in shortly...
989 ), $fname );
990 $newid = $dbw->insertId();
991
992 $this->mTitle->resetArticleId( $newid );
993
994 wfProfileOut( $fname );
995 return $newid;
996 }
997
998 /**
999 * Update the page record to point to a newly saved revision.
1000 *
1001 * @param Database $dbw
1002 * @param Revision $revision -- for ID number, and text used to set
1003 length and redirect status fields
1004 * @param int $lastRevision -- if given, will not overwrite the page field
1005 * when different from the currently set value.
1006 * Giving 0 indicates the new page flag should
1007 * be set on.
1008 * @return bool true on success, false on failure
1009 * @access private
1010 */
1011 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
1012 $fname = 'Article::updateToRevision';
1013 wfProfileIn( $fname );
1014
1015 $conditions = array( 'page_id' => $this->getId() );
1016 if( !is_null( $lastRevision ) ) {
1017 # An extra check against threads stepping on each other
1018 $conditions['page_latest'] = $lastRevision;
1019 }
1020
1021 $text = $revision->getText();
1022 $dbw->update( 'page',
1023 array( /* SET */
1024 'page_latest' => $revision->getId(),
1025 'page_touched' => $dbw->timestamp(),
1026 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
1027 'page_is_redirect' => Article::isRedirect( $text ) ? 1 : 0,
1028 'page_len' => strlen( $text ),
1029 ),
1030 $conditions,
1031 $fname );
1032
1033 wfProfileOut( $fname );
1034 return ( $dbw->affectedRows() != 0 );
1035 }
1036
1037 /**
1038 * If the given revision is newer than the currently set page_latest,
1039 * update the page record. Otherwise, do nothing.
1040 *
1041 * @param Database $dbw
1042 * @param Revision $revision
1043 */
1044 function updateIfNewerOn( &$dbw, $revision ) {
1045 $fname = 'Article::updateIfNewerOn';
1046 wfProfileIn( $fname );
1047
1048 $row = $dbw->selectRow(
1049 array( 'revision', 'page' ),
1050 array( 'rev_id', 'rev_timestamp' ),
1051 array(
1052 'page_id' => $this->getId(),
1053 'page_latest=rev_id' ),
1054 $fname );
1055 if( $row ) {
1056 if( wfTimestamp(TS_MW, $row->rev_timestamp) >= $revision->getTimestamp() ) {
1057 wfProfileOut( $fname );
1058 return false;
1059 }
1060 $prev = $row->rev_id;
1061 } else {
1062 # No or missing previous revision; mark the page as new
1063 $prev = 0;
1064 }
1065
1066 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
1067 wfProfileOut( $fname );
1068 return $ret;
1069 }
1070
1071 /**
1072 * Theoretically we could defer these whole insert and update
1073 * functions for after display, but that's taking a big leap
1074 * of faith, and we want to be able to report database
1075 * errors at some point.
1076 * @private
1077 */
1078 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false, $comment=false ) {
1079 global $wgOut, $wgUser;
1080 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1081
1082 $fname = 'Article::insertNewArticle';
1083 wfProfileIn( $fname );
1084
1085 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1086 &$summary, &$isminor, &$watchthis, NULL ) ) ) {
1087 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1088 wfProfileOut( $fname );
1089 return false;
1090 }
1091
1092 $this->mGoodAdjustment = $this->isCountable( $text );
1093 $this->mTotalAdjustment = 1;
1094
1095 $ns = $this->mTitle->getNamespace();
1096 $ttl = $this->mTitle->getDBkey();
1097
1098 # If this is a comment, add the summary as headline
1099 if($comment && $summary!="") {
1100 $text="== {$summary} ==\n\n".$text;
1101 }
1102 $text = $this->preSaveTransform( $text );
1103 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ? 1 : 0;
1104 $now = wfTimestampNow();
1105
1106 $dbw =& wfGetDB( DB_MASTER );
1107
1108 # Add the page record; stake our claim on this title!
1109 $newid = $this->insertOn( $dbw );
1110
1111 # Save the revision text...
1112 $revision = new Revision( array(
1113 'page' => $newid,
1114 'comment' => $summary,
1115 'minor_edit' => $isminor,
1116 'text' => $text
1117 ) );
1118 $revisionId = $revision->insertOn( $dbw );
1119
1120 $this->mTitle->resetArticleID( $newid );
1121
1122 # Update the page record with revision data
1123 $this->updateRevisionOn( $dbw, $revision, 0 );
1124
1125 Article::onArticleCreate( $this->mTitle );
1126 if(!$suppressRC) {
1127 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, 'default',
1128 '', strlen( $text ), $revisionId );
1129 }
1130
1131 if ($watchthis) {
1132 if(!$this->mTitle->userIsWatching()) $this->watch();
1133 } else {
1134 if ( $this->mTitle->userIsWatching() ) {
1135 $this->unwatch();
1136 }
1137 }
1138
1139 # The talk page isn't in the regular link tables, so we need to update manually:
1140 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
1141 $dbw->update( 'page',
1142 array( 'page_touched' => $dbw->timestamp($now) ),
1143 array( 'page_namespace' => $talkns,
1144 'page_title' => $ttl ),
1145 $fname );
1146
1147 # standard deferred updates
1148 $this->editUpdates( $text, $summary, $isminor, $now );
1149
1150 $oldid = 0; # new article
1151 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
1152
1153 wfRunHooks( 'ArticleSaveComplete', array( &$this, &$wgUser, $text,
1154 $summary, $isminor,
1155 $watchthis, NULL ) );
1156 wfProfileOut( $fname );
1157 }
1158
1159 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
1160 $this->replaceSection( $section, $text, $summary, $edittime );
1161 }
1162
1163 /**
1164 * @return string Complete article text, or null if error
1165 */
1166 function replaceSection($section, $text, $summary = '', $edittime = NULL) {
1167 $fname = 'Article::replaceSection';
1168 wfProfileIn( $fname );
1169
1170 if ($section != '') {
1171 if( is_null( $edittime ) ) {
1172 $rev = Revision::newFromTitle( $this->mTitle );
1173 } else {
1174 $dbw =& wfGetDB( DB_MASTER );
1175 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1176 }
1177 if( is_null( $rev ) ) {
1178 wfDebug( "Article::replaceSection asked for bogus section (page: " .
1179 $this->getId() . "; section: $section; edittime: $edittime)\n" );
1180 return null;
1181 }
1182 $oldtext = $rev->getText();
1183
1184 if($section=='new') {
1185 if($summary) $subject="== {$summary} ==\n\n";
1186 $text=$oldtext."\n\n".$subject.$text;
1187 } else {
1188
1189 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1190 # comments to be stripped as well)
1191 $striparray=array();
1192 $parser=new Parser();
1193 $parser->mOutputType=OT_WIKI;
1194 $parser->mOptions = new ParserOptions();
1195 $oldtext=$parser->strip($oldtext, $striparray, true);
1196
1197 # now that we can be sure that no pseudo-sections are in the source,
1198 # split it up
1199 # Unfortunately we can't simply do a preg_replace because that might
1200 # replace the wrong section, so we have to use the section counter instead
1201 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
1202 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
1203 $secs[$section*2]=$text."\n\n"; // replace with edited
1204
1205 # section 0 is top (intro) section
1206 if($section!=0) {
1207
1208 # headline of old section - we need to go through this section
1209 # to determine if there are any subsections that now need to
1210 # be erased, as the mother section has been replaced with
1211 # the text of all subsections.
1212 $headline=$secs[$section*2-1];
1213 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
1214 $hlevel=$matches[1];
1215
1216 # determine headline level for wikimarkup headings
1217 if(strpos($hlevel,'=')!==false) {
1218 $hlevel=strlen($hlevel);
1219 }
1220
1221 $secs[$section*2-1]=''; // erase old headline
1222 $count=$section+1;
1223 $break=false;
1224 while(!empty($secs[$count*2-1]) && !$break) {
1225
1226 $subheadline=$secs[$count*2-1];
1227 preg_match(
1228 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1229 $subhlevel=$matches[1];
1230 if(strpos($subhlevel,'=')!==false) {
1231 $subhlevel=strlen($subhlevel);
1232 }
1233 if($subhlevel > $hlevel) {
1234 // erase old subsections
1235 $secs[$count*2-1]='';
1236 $secs[$count*2]='';
1237 }
1238 if($subhlevel <= $hlevel) {
1239 $break=true;
1240 }
1241 $count++;
1242
1243 }
1244
1245 }
1246 $text=join('',$secs);
1247 # reinsert the stuff that we stripped out earlier
1248 $text=$parser->unstrip($text,$striparray);
1249 $text=$parser->unstripNoWiki($text,$striparray);
1250 }
1251
1252 }
1253 wfProfileOut( $fname );
1254 return $text;
1255 }
1256
1257 /**
1258 * Change an existing article. Puts the previous version back into the old table, updates RC
1259 * and all necessary caches, mostly via the deferred update array.
1260 *
1261 * It is possible to call this function from a command-line script, but note that you should
1262 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1263 */
1264 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1265 global $wgOut, $wgUser;
1266 global $wgDBtransactions, $wgMwRedir;
1267 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList, $wgUseFileCache;
1268
1269 $fname = 'Article::updateArticle';
1270 wfProfileIn( $fname );
1271 $good = true;
1272
1273 if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
1274 &$summary, &$minor,
1275 &$watchthis, &$sectionanchor ) ) ) {
1276 wfDebug( "$fname: ArticleSave hook aborted save!\n" );
1277 wfProfileOut( $fname );
1278 return false;
1279 }
1280
1281 $isminor = ( $minor && $wgUser->isLoggedIn() );
1282 if ( $this->isRedirect( $text ) ) {
1283 # Remove all content but redirect
1284 # This could be done by reconstructing the redirect from a title given by
1285 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1286 # wants to see
1287 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1288 $redir = 1;
1289 $text = $m[1] . "\n";
1290 }
1291 }
1292 else { $redir = 0; }
1293
1294 $text = $this->preSaveTransform( $text );
1295 $dbw =& wfGetDB( DB_MASTER );
1296 $now = wfTimestampNow();
1297
1298 # Update article, but only if changed.
1299
1300 # It's important that we either rollback or complete, otherwise an attacker could
1301 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1302 # could conceivably have the same effect, especially if cur is locked for long periods.
1303 if( !$wgDBtransactions ) {
1304 $userAbort = ignore_user_abort( true );
1305 }
1306
1307 $oldtext = $this->getContent( true );
1308 $oldsize = strlen( $oldtext );
1309 $newsize = strlen( $text );
1310 $lastRevision = 0;
1311
1312 if ( 0 != strcmp( $text, $oldtext ) ) {
1313 $this->mGoodAdjustment = $this->isCountable( $text )
1314 - $this->isCountable( $oldtext );
1315 $this->mTotalAdjustment = 0;
1316 $now = wfTimestampNow();
1317
1318 $lastRevision = $dbw->selectField(
1319 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1320
1321 $revision = new Revision( array(
1322 'page' => $this->getId(),
1323 'comment' => $summary,
1324 'minor_edit' => $isminor,
1325 'text' => $text
1326 ) );
1327
1328 $dbw->immediateCommit();
1329 $dbw->begin();
1330 $revisionId = $revision->insertOn( $dbw );
1331
1332 # Update page
1333 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1334
1335 if( !$ok ) {
1336 /* Belated edit conflict! Run away!! */
1337 $good = false;
1338 $dbw->rollback();
1339 } else {
1340 # Update recentchanges and purge cache and whatnot
1341 $bot = (int)($wgUser->isBot() || $forceBot);
1342 RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1343 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1344 $revisionId );
1345 Article::onArticleEdit( $this->mTitle );
1346 $dbw->commit();
1347 }
1348 }
1349
1350 if( !$wgDBtransactions ) {
1351 ignore_user_abort( $userAbort );
1352 }
1353
1354 if ( $good ) {
1355 if ($watchthis) {
1356 if (!$this->mTitle->userIsWatching()) {
1357 $dbw->immediateCommit();
1358 $dbw->begin();
1359 $this->watch();
1360 $dbw->commit();
1361 }
1362 } else {
1363 if ( $this->mTitle->userIsWatching() ) {
1364 $dbw->immediateCommit();
1365 $dbw->begin();
1366 $this->unwatch();
1367 $dbw->commit();
1368 }
1369 }
1370 # standard deferred updates
1371 $this->editUpdates( $text, $summary, $minor, $now );
1372
1373
1374 $urls = array();
1375 # Template namespace
1376 # Purge all articles linking here
1377 if ( $this->mTitle->getNamespace() == NS_TEMPLATE) {
1378 $titles = $this->mTitle->getLinksTo();
1379 Title::touchArray( $titles );
1380 if ( $wgUseSquid ) {
1381 foreach ( $titles as $title ) {
1382 $urls[] = $title->getInternalURL();
1383 }
1384 }
1385 }
1386
1387 # Squid updates
1388 if ( $wgUseSquid ) {
1389 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
1390 $u = new SquidUpdate( $urls );
1391 array_push( $wgPostCommitUpdateList, $u );
1392 }
1393
1394 # File cache
1395 if ( $wgUseFileCache ) {
1396 $cm = new CacheManager($this->mTitle);
1397 @unlink($cm->fileCacheName());
1398 }
1399
1400 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1401 }
1402 wfRunHooks( 'ArticleSaveComplete',
1403 array( &$this, &$wgUser, $text,
1404 $summary, $minor,
1405 $watchthis, $sectionanchor ) );
1406 wfProfileOut( $fname );
1407 return $good;
1408 }
1409
1410 /**
1411 * After we've either updated or inserted the article, update
1412 * the link tables and redirect to the new page.
1413 */
1414 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1415 global $wgUseDumbLinkUpdate, $wgAntiLockFlags, $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1416 global $wgUseEnotif;
1417
1418 $fname = 'Article::showArticle';
1419 wfProfileIn( $fname );
1420
1421 $wgLinkCache = new LinkCache();
1422
1423 if ( !$wgUseDumbLinkUpdate ) {
1424 # Preload links to reduce lock time
1425 if ( $wgAntiLockFlags & ALF_PRELOAD_LINKS ) {
1426 $wgLinkCache->preFill( $this->mTitle );
1427 $wgLinkCache->clear();
1428 }
1429 }
1430
1431 # Parse the text and save it to the parser cache
1432 $wgOut = new OutputPage();
1433 $wgOut->setParserOptions( ParserOptions::newFromUser( $wgUser ) );
1434 $wgOut->addPrimaryWikiText( $text, $this );
1435
1436 if ( !$wgUseDumbLinkUpdate ) {
1437 # Move the current links back to the second register
1438 $wgLinkCache->swapRegisters();
1439
1440 # Get old version of link table to allow incremental link updates
1441 # Lock this data now since it is needed for an update
1442 $wgLinkCache->forUpdate( true );
1443 $wgLinkCache->preFill( $this->mTitle );
1444
1445 # Swap this old version back into its rightful place
1446 $wgLinkCache->swapRegisters();
1447 }
1448
1449 if( $this->isRedirect( $text ) )
1450 $r = 'redirect=no';
1451 else
1452 $r = '';
1453 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1454
1455 if ( $wgUseEnotif ) {
1456 # this would be better as an extension hook
1457 include_once( "UserMailer.php" );
1458 $wgEnotif = new EmailNotification ();
1459 $wgEnotif->notifyOnPageChange( $this->mTitle, $now, $summary, $me2, $oldid );
1460 }
1461 wfProfileOut( $fname );
1462 }
1463
1464 /**
1465 * Mark this particular edit as patrolled
1466 */
1467 function markpatrolled() {
1468 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1469 $wgOut->setRobotpolicy( 'noindex,follow' );
1470
1471 if ( !$wgUseRCPatrol )
1472 {
1473 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1474 return;
1475 }
1476 if ( $wgUser->isAnon() )
1477 {
1478 $wgOut->loginToUse();
1479 return;
1480 }
1481 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1482 {
1483 $wgOut->sysopRequired();
1484 return;
1485 }
1486 $rcid = $wgRequest->getVal( 'rcid' );
1487 if ( !is_null ( $rcid ) )
1488 {
1489 RecentChange::markPatrolled( $rcid );
1490 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1491 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1492
1493 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1494 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1495 }
1496 else
1497 {
1498 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1499 }
1500 }
1501
1502 /**
1503 * Validate function
1504 */
1505 function validate() {
1506 global $wgOut, $wgUser, $wgRequest, $wgUseValidation;
1507
1508 if ( !$wgUseValidation ) # Are we using article validation at all?
1509 {
1510 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
1511 return ;
1512 }
1513
1514 $wgOut->setRobotpolicy( 'noindex,follow' );
1515 $revision = $wgRequest->getVal( 'revision' );
1516
1517 include_once ( "SpecialValidate.php" ) ; # The "Validation" class
1518
1519 $v = new Validation ;
1520 if ( $wgRequest->getVal ( "mode" , "" ) == "list" )
1521 $t = $v->showList ( $this ) ;
1522 else if ( $wgRequest->getVal ( "mode" , "" ) == "details" )
1523 $t = $v->showDetails ( $this , $wgRequest->getVal( 'revision' ) ) ;
1524 else
1525 $t = $v->validatePageForm ( $this , $revision ) ;
1526
1527 $wgOut->addHTML ( $t ) ;
1528 }
1529
1530 /**
1531 * Add this page to $wgUser's watchlist
1532 */
1533
1534 function watch() {
1535
1536 global $wgUser, $wgOut;
1537
1538 if ( $wgUser->isAnon() ) {
1539 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1540 return;
1541 }
1542 if ( wfReadOnly() ) {
1543 $wgOut->readOnlyPage();
1544 return;
1545 }
1546
1547 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1548
1549 $wgUser->addWatch( $this->mTitle );
1550 $wgUser->saveSettings();
1551
1552 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1553
1554 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1555 $wgOut->setRobotpolicy( 'noindex,follow' );
1556
1557 $link = $this->mTitle->getPrefixedText();
1558 $text = wfMsg( 'addedwatchtext', $link );
1559 $wgOut->addWikiText( $text );
1560 }
1561
1562 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1563 }
1564
1565 /**
1566 * Stop watching a page
1567 */
1568
1569 function unwatch() {
1570
1571 global $wgUser, $wgOut;
1572
1573 if ( $wgUser->isAnon() ) {
1574 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1575 return;
1576 }
1577 if ( wfReadOnly() ) {
1578 $wgOut->readOnlyPage();
1579 return;
1580 }
1581
1582 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1583
1584 $wgUser->removeWatch( $this->mTitle );
1585 $wgUser->saveSettings();
1586
1587 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1588
1589 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1590 $wgOut->setRobotpolicy( 'noindex,follow' );
1591
1592 $link = $this->mTitle->getPrefixedText();
1593 $text = wfMsg( 'removedwatchtext', $link );
1594 $wgOut->addWikiText( $text );
1595 }
1596
1597 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1598 }
1599
1600 /**
1601 * protect a page
1602 */
1603 function protect( $limit = 'sysop' ) {
1604 global $wgUser, $wgOut, $wgRequest;
1605
1606 if ( ! $wgUser->isAllowed('protect') ) {
1607 $wgOut->sysopRequired();
1608 return;
1609 }
1610 if ( wfReadOnly() ) {
1611 $wgOut->readOnlyPage();
1612 return;
1613 }
1614 $id = $this->mTitle->getArticleID();
1615 if ( 0 == $id ) {
1616 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1617 return;
1618 }
1619
1620 $confirm = $wgRequest->wasPosted() &&
1621 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1622 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1623 $reason = $wgRequest->getText( 'wpReasonProtect' );
1624
1625 if ( $confirm ) {
1626 $dbw =& wfGetDB( DB_MASTER );
1627 $dbw->update( 'page',
1628 array( /* SET */
1629 'page_touched' => $dbw->timestamp(),
1630 'page_restrictions' => (string)$limit
1631 ), array( /* WHERE */
1632 'page_id' => $id
1633 ), 'Article::protect'
1634 );
1635
1636 $restrictions = "move=" . $limit;
1637 if( !$moveonly ) {
1638 $restrictions .= ":edit=" . $limit;
1639 }
1640 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1641
1642 $dbw =& wfGetDB( DB_MASTER );
1643 $dbw->update( 'page',
1644 array( /* SET */
1645 'page_touched' => $dbw->timestamp(),
1646 'page_restrictions' => $restrictions
1647 ), array( /* WHERE */
1648 'page_id' => $id
1649 ), 'Article::protect'
1650 );
1651
1652 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1653
1654 $log = new LogPage( 'protect' );
1655 if ( $limit === '' ) {
1656 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1657 } else {
1658 $log->addEntry( 'protect', $this->mTitle, $reason );
1659 }
1660 $wgOut->redirect( $this->mTitle->getFullURL() );
1661 }
1662 return;
1663 } else {
1664 return $this->confirmProtect( '', '', $limit );
1665 }
1666 }
1667
1668 /**
1669 * Output protection confirmation dialog
1670 */
1671 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1672 global $wgOut, $wgUser;
1673
1674 wfDebug( "Article::confirmProtect\n" );
1675
1676 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1677 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1678
1679 $check = '';
1680 $protcom = '';
1681 $moveonly = '';
1682
1683 if ( $limit === '' ) {
1684 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1685 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1686 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1687 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1688 $formaction = $this->mTitle->escapeLocalURL( 'action=unprotect' . $par );
1689 } else {
1690 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1691 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1692 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1693 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1694 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1695 $formaction = $this->mTitle->escapeLocalURL( 'action=protect' . $par );
1696 }
1697
1698 $confirm = htmlspecialchars( wfMsg( 'protectpage' ) );
1699 $token = htmlspecialchars( $wgUser->editToken() );
1700
1701 $wgOut->addHTML( "
1702 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1703 <table border='0'>
1704 <tr>
1705 <td align='right'>
1706 <label for='wpReasonProtect'>{$protcom}:</label>
1707 </td>
1708 <td align='left'>
1709 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1710 </td>
1711 </tr>" );
1712 if($moveonly != '') {
1713 $wgOut->AddHTML( "
1714 <tr>
1715 <td align='right'>
1716 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1717 </td>
1718 <td align='left'>
1719 <label for='wpMoveOnly'>{$moveonly}</label>
1720 </td>
1721 </tr> " );
1722 }
1723 $wgOut->addHTML( "
1724 <tr>
1725 <td>&nbsp;</td>
1726 <td>
1727 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1728 </td>
1729 </tr>
1730 </table>
1731 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1732 </form>" );
1733
1734 $wgOut->returnToMain( false );
1735 }
1736
1737 /**
1738 * Unprotect the pages
1739 */
1740 function unprotect() {
1741 return $this->protect( '' );
1742 }
1743
1744 /*
1745 * UI entry point for page deletion
1746 */
1747 function delete() {
1748 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1749 $fname = 'Article::delete';
1750 $confirm = $wgRequest->wasPosted() &&
1751 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1752 $reason = $wgRequest->getText( 'wpReason' );
1753
1754 # This code desperately needs to be totally rewritten
1755
1756 # Check permissions
1757 if( ( !$wgUser->isAllowed( 'delete' ) ) ) {
1758 $wgOut->sysopRequired();
1759 return;
1760 }
1761 if( wfReadOnly() ) {
1762 $wgOut->readOnlyPage();
1763 return;
1764 }
1765
1766 # Better double-check that it hasn't been deleted yet!
1767 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1768 if( !$this->mTitle->exists() ) {
1769 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1770 return;
1771 }
1772
1773 if( $confirm ) {
1774 $this->doDelete( $reason );
1775 return;
1776 }
1777
1778 # determine whether this page has earlier revisions
1779 # and insert a warning if it does
1780 # we select the text because it might be useful below
1781 $dbr =& $this->getDB();
1782 $ns = $this->mTitle->getNamespace();
1783 $title = $this->mTitle->getDBkey();
1784 $revisions = $dbr->select( array( 'page', 'revision' ),
1785 array( 'rev_id', 'rev_user_text' ),
1786 array(
1787 'page_namespace' => $ns,
1788 'page_title' => $title,
1789 'rev_page = page_id'
1790 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1791 );
1792
1793 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1794 $skin=$wgUser->getSkin();
1795 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1796 $wgOut->addHTML( $skin->historyLink() .'</b>');
1797 }
1798
1799 # Fetch cur_text
1800 $rev = Revision::newFromTitle( $this->mTitle );
1801
1802 # Fetch name(s) of contributors
1803 $rev_name = '';
1804 $all_same_user = true;
1805 while( $row = $dbr->fetchObject( $revisions ) ) {
1806 if( $rev_name != '' && $rev_name != $row->rev_user_text ) {
1807 $all_same_user = false;
1808 } else {
1809 $rev_name = $row->rev_user_text;
1810 }
1811 }
1812
1813 if( !is_null( $rev ) ) {
1814 # if this is a mini-text, we can paste part of it into the deletion reason
1815 $text = $rev->getText();
1816
1817 #if this is empty, an earlier revision may contain "useful" text
1818 $blanked = false;
1819 if( $text == '' ) {
1820 $prev = $rev->getPrevious();
1821 if( $prev ) {
1822 $text = $prev->getText();
1823 $blanked = true;
1824 }
1825 }
1826
1827 $length = strlen( $text );
1828
1829 # this should not happen, since it is not possible to store an empty, new
1830 # page. Let's insert a standard text in case it does, though
1831 if( $length == 0 && $reason === '' ) {
1832 $reason = wfMsgForContent( 'exblank' );
1833 }
1834
1835 if( $length < 500 && $reason === '' ) {
1836 # comment field=255, let's grep the first 150 to have some user
1837 # space left
1838 global $wgContLang;
1839 $text = $wgContLang->truncate( $text, 150, '...' );
1840
1841 # let's strip out newlines
1842 $text = preg_replace( "/[\n\r]/", '', $text );
1843
1844 if( !$blanked ) {
1845 if( !$all_same_user ) {
1846 $reason = wfMsgForContent( 'excontent', $text );
1847 } else {
1848 $reason = wfMsgForContent( 'excontentauthor', $text, $rev_name );
1849 }
1850 } else {
1851 $reason = wfMsgForContent( 'exbeforeblank', $text );
1852 }
1853 }
1854 }
1855
1856 return $this->confirmDelete( '', $reason );
1857 }
1858
1859 /**
1860 * Output deletion confirmation dialog
1861 */
1862 function confirmDelete( $par, $reason ) {
1863 global $wgOut, $wgUser;
1864
1865 wfDebug( "Article::confirmDelete\n" );
1866
1867 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1868 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1869 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1870 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1871
1872 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1873
1874 $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
1875 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1876 $token = htmlspecialchars( $wgUser->editToken() );
1877
1878 $wgOut->addHTML( "
1879 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1880 <table border='0'>
1881 <tr>
1882 <td align='right'>
1883 <label for='wpReason'>{$delcom}:</label>
1884 </td>
1885 <td align='left'>
1886 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1887 </td>
1888 </tr>
1889 <tr>
1890 <td>&nbsp;</td>
1891 <td>
1892 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1893 </td>
1894 </tr>
1895 </table>
1896 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1897 </form>\n" );
1898
1899 $wgOut->returnToMain( false );
1900 }
1901
1902
1903 /**
1904 * Perform a deletion and output success or failure messages
1905 */
1906 function doDelete( $reason ) {
1907 global $wgOut, $wgUser, $wgContLang;
1908 $fname = 'Article::doDelete';
1909 wfDebug( $fname."\n" );
1910
1911 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1912 if ( $this->doDeleteArticle( $reason ) ) {
1913 $deleted = $this->mTitle->getPrefixedText();
1914
1915 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1916 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1917
1918 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1919 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1920
1921 $wgOut->addWikiText( $text );
1922 $wgOut->returnToMain( false );
1923 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1924 } else {
1925 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1926 }
1927 }
1928 }
1929
1930 /**
1931 * Back-end article deletion
1932 * Deletes the article with database consistency, writes logs, purges caches
1933 * Returns success
1934 */
1935 function doDeleteArticle( $reason ) {
1936 global $wgUser;
1937 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1938 global $wgUseTrackbacks;
1939
1940 $fname = 'Article::doDeleteArticle';
1941 wfDebug( $fname."\n" );
1942
1943 $dbw =& wfGetDB( DB_MASTER );
1944 $ns = $this->mTitle->getNamespace();
1945 $t = $this->mTitle->getDBkey();
1946 $id = $this->mTitle->getArticleID();
1947
1948 if ( $t == '' || $id == 0 ) {
1949 return false;
1950 }
1951
1952 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ), -1 );
1953 array_push( $wgDeferredUpdateList, $u );
1954
1955 $linksTo = $this->mTitle->getLinksTo();
1956
1957 # Squid purging
1958 if ( $wgUseSquid ) {
1959 $urls = array(
1960 $this->mTitle->getInternalURL(),
1961 $this->mTitle->getInternalURL( 'history' )
1962 );
1963
1964 $u = SquidUpdate::newFromTitles( $linksTo, $urls );
1965 array_push( $wgPostCommitUpdateList, $u );
1966
1967 }
1968
1969 # Client and file cache invalidation
1970 Title::touchArray( $linksTo );
1971
1972
1973 // For now, shunt the revision data into the archive table.
1974 // Text is *not* removed from the text table; bulk storage
1975 // is left intact to avoid breaking block-compression or
1976 // immutable storage schemes.
1977 //
1978 // For backwards compatibility, note that some older archive
1979 // table entries will have ar_text and ar_flags fields still.
1980 //
1981 // In the future, we may keep revisions and mark them with
1982 // the rev_deleted field, which is reserved for this purpose.
1983 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1984 array(
1985 'ar_namespace' => 'page_namespace',
1986 'ar_title' => 'page_title',
1987 'ar_comment' => 'rev_comment',
1988 'ar_user' => 'rev_user',
1989 'ar_user_text' => 'rev_user_text',
1990 'ar_timestamp' => 'rev_timestamp',
1991 'ar_minor_edit' => 'rev_minor_edit',
1992 'ar_rev_id' => 'rev_id',
1993 'ar_text_id' => 'rev_text_id',
1994 ), array(
1995 'page_id' => $id,
1996 'page_id = rev_page'
1997 ), $fname
1998 );
1999
2000 # Now that it's safely backed up, delete it
2001 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
2002 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
2003
2004 if ($wgUseTrackbacks)
2005 $dbw->delete( 'trackbacks', array( 'tb_page' => $id ), $fname );
2006
2007 # Clean up recentchanges entries...
2008 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
2009
2010 # Finally, clean up the link tables
2011 $t = $this->mTitle->getPrefixedDBkey();
2012
2013 Article::onArticleDelete( $this->mTitle );
2014
2015 # Delete outgoing links
2016 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
2017 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
2018 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
2019
2020 # Log the deletion
2021 $log = new LogPage( 'delete' );
2022 $log->addEntry( 'delete', $this->mTitle, $reason );
2023
2024 # Clear the cached article id so the interface doesn't act like we exist
2025 $this->mTitle->resetArticleID( 0 );
2026 $this->mTitle->mArticleID = 0;
2027 return true;
2028 }
2029
2030 /**
2031 * Revert a modification
2032 */
2033 function rollback() {
2034 global $wgUser, $wgOut, $wgRequest;
2035 $fname = 'Article::rollback';
2036
2037 if ( ! $wgUser->isAllowed('rollback') ) {
2038 $wgOut->sysopRequired();
2039 return;
2040 }
2041 if ( wfReadOnly() ) {
2042 $wgOut->readOnlyPage( $this->getContent( true ) );
2043 return;
2044 }
2045 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
2046 array( $this->mTitle->getPrefixedText(),
2047 $wgRequest->getVal( 'from' ) ) ) ) {
2048 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
2049 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
2050 return;
2051 }
2052 $dbw =& wfGetDB( DB_MASTER );
2053
2054 # Enhanced rollback, marks edits rc_bot=1
2055 $bot = $wgRequest->getBool( 'bot' );
2056
2057 # Replace all this user's current edits with the next one down
2058 $tt = $this->mTitle->getDBKey();
2059 $n = $this->mTitle->getNamespace();
2060
2061 # Get the last editor, lock table exclusively
2062 $dbw->begin();
2063 $current = Revision::newFromTitle( $this->mTitle );
2064 if( is_null( $current ) ) {
2065 # Something wrong... no page?
2066 $dbw->rollback();
2067 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
2068 return;
2069 }
2070
2071 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
2072 if( $from != $current->getUserText() ) {
2073 $wgOut->setPageTitle( wfMsg('rollbackfailed') );
2074 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
2075 htmlspecialchars( $this->mTitle->getPrefixedText()),
2076 htmlspecialchars( $from ),
2077 htmlspecialchars( $current->getUserText() ) ) );
2078 if( $current->getComment() != '') {
2079 $wgOut->addHTML(
2080 wfMsg( 'editcomment',
2081 htmlspecialchars( $current->getComment() ) ) );
2082 }
2083 return;
2084 }
2085
2086 # Get the last edit not by this guy
2087 $user = intval( $current->getUser() );
2088 $user_text = $dbw->addQuotes( $current->getUserText() );
2089 $s = $dbw->selectRow( 'revision',
2090 array( 'rev_id', 'rev_timestamp' ),
2091 array(
2092 'rev_page' => $current->getPage(),
2093 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
2094 ), $fname,
2095 array(
2096 'USE INDEX' => 'page_timestamp',
2097 'ORDER BY' => 'rev_timestamp DESC' )
2098 );
2099 if( $s === false ) {
2100 # Something wrong
2101 $dbw->rollback();
2102 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
2103 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
2104 return;
2105 }
2106
2107 if ( $bot ) {
2108 # Mark all reverted edits as bot
2109 $dbw->update( 'recentchanges',
2110 array( /* SET */
2111 'rc_bot' => 1
2112 ), array( /* WHERE */
2113 'rc_cur_id' => $current->getPage(),
2114 'rc_user_text' => $current->getUserText(),
2115 "rc_timestamp > '{$s->rev_timestamp}'",
2116 ), $fname
2117 );
2118 }
2119
2120 # Save it!
2121 $target = Revision::newFromId( $s->rev_id );
2122 $newcomment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
2123
2124 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
2125 $wgOut->setRobotpolicy( 'noindex,nofollow' );
2126 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
2127
2128 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle->userIsWatching(), $bot );
2129 Article::onArticleEdit( $this->mTitle );
2130
2131 $dbw->commit();
2132 $wgOut->returnToMain( false );
2133 }
2134
2135
2136 /**
2137 * Do standard deferred updates after page view
2138 * @private
2139 */
2140 function viewUpdates() {
2141 global $wgDeferredUpdateList, $wgUseEnotif;
2142
2143 if ( 0 != $this->getID() ) {
2144 global $wgDisableCounters;
2145 if( !$wgDisableCounters ) {
2146 Article::incViewCount( $this->getID() );
2147 $u = new SiteStatsUpdate( 1, 0, 0 );
2148 array_push( $wgDeferredUpdateList, $u );
2149 }
2150 }
2151
2152 # Update newtalk status if user is reading their own
2153 # talk page
2154
2155 global $wgUser;
2156 if ($this->mTitle->getNamespace() == NS_USER_TALK &&
2157 $this->mTitle->getText() == $wgUser->getName())
2158 {
2159 if ( $wgUseEnotif ) {
2160 require_once( 'UserTalkUpdate.php' );
2161 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(), $this->mTitle->getDBkey(), false, false, false );
2162 } else {
2163 $wgUser->setNewtalk(0);
2164 $wgUser->saveNewtalk();
2165 }
2166 } elseif ( $wgUseEnotif ) {
2167 $wgUser->clearNotification( $this->mTitle );
2168 }
2169
2170 }
2171
2172 /**
2173 * Do standard deferred updates after page edit.
2174 * Every 1000th edit, prune the recent changes table.
2175 * @private
2176 * @param string $text
2177 */
2178 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
2179 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
2180 global $wgMessageCache, $wgUser, $wgUseEnotif;
2181
2182 if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', &$this ) ) {
2183 wfSeedRandom();
2184 if ( 0 == mt_rand( 0, 999 ) ) {
2185 # Periodically flush old entries from the recentchanges table.
2186 global $wgRCMaxAge;
2187
2188 $dbw =& wfGetDB( DB_MASTER );
2189 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2190 $recentchanges = $dbw->tableName( 'recentchanges' );
2191 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2192 $dbw->query( $sql );
2193 }
2194 }
2195
2196 $id = $this->getID();
2197 $title = $this->mTitle->getPrefixedDBkey();
2198 $shortTitle = $this->mTitle->getDBkey();
2199
2200 if ( 0 != $id ) {
2201 $u = new LinksUpdate( $id, $title );
2202 array_push( $wgDeferredUpdateList, $u );
2203 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2204 array_push( $wgDeferredUpdateList, $u );
2205 $u = new SearchUpdate( $id, $title, $text );
2206 array_push( $wgDeferredUpdateList, $u );
2207
2208 # If this is another user's talk page, update newtalk
2209
2210 if ($this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName()) {
2211 if ( $wgUseEnotif ) {
2212 require_once( 'UserTalkUpdate.php' );
2213 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle, $summary,
2214 $minoredit, $timestamp_of_pagechange);
2215 } else {
2216 $other = User::newFromName( $shortTitle );
2217 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2218 // An anonymous user
2219 $other = new User();
2220 $other->setName( $shortTitle );
2221 }
2222 if( $other ) {
2223 $other->setNewtalk(1);
2224 $other->saveNewtalk();
2225 }
2226 }
2227 }
2228
2229 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2230 $wgMessageCache->replace( $shortTitle, $text );
2231 }
2232 }
2233 }
2234
2235 /**
2236 * @todo document this function
2237 * @private
2238 * @param string $oldid Revision ID of this article revision
2239 */
2240 function setOldSubtitle( $oldid=0 ) {
2241 global $wgLang, $wgOut, $wgUser;
2242
2243 $current = ( $oldid == $this->mLatest );
2244 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2245 $sk = $wgUser->getSkin();
2246 $lnk = $current
2247 ? wfMsg( 'currentrevisionlink' )
2248 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2249 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
2250 $nextlink = $current
2251 ? wfMsg( 'nextrevision' )
2252 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2253 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2254 $wgOut->setSubtitle( $r );
2255 }
2256
2257 /**
2258 * This function is called right before saving the wikitext,
2259 * so we can do things like signatures and links-in-context.
2260 *
2261 * @param string $text
2262 */
2263 function preSaveTransform( $text ) {
2264 global $wgParser, $wgUser;
2265 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2266 }
2267
2268 /* Caching functions */
2269
2270 /**
2271 * checkLastModified returns true if it has taken care of all
2272 * output to the client that is necessary for this request.
2273 * (that is, it has sent a cached version of the page)
2274 */
2275 function tryFileCache() {
2276 static $called = false;
2277 if( $called ) {
2278 wfDebug( " tryFileCache() -- called twice!?\n" );
2279 return;
2280 }
2281 $called = true;
2282 if($this->isFileCacheable()) {
2283 $touched = $this->mTouched;
2284 $cache = new CacheManager( $this->mTitle );
2285 if($cache->isFileCacheGood( $touched )) {
2286 global $wgOut;
2287 wfDebug( " tryFileCache() - about to load\n" );
2288 $cache->loadFromFileCache();
2289 return true;
2290 } else {
2291 wfDebug( " tryFileCache() - starting buffer\n" );
2292 ob_start( array(&$cache, 'saveToFileCache' ) );
2293 }
2294 } else {
2295 wfDebug( " tryFileCache() - not cacheable\n" );
2296 }
2297 }
2298
2299 /**
2300 * Check if the page can be cached
2301 * @return bool
2302 */
2303 function isFileCacheable() {
2304 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2305 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2306
2307 return $wgUseFileCache
2308 and (!$wgShowIPinHeader)
2309 and ($this->getID() != 0)
2310 and ($wgUser->isAnon())
2311 and (!$wgUser->getNewtalk())
2312 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2313 and (empty( $action ) || $action == 'view')
2314 and (!isset($oldid))
2315 and (!isset($diff))
2316 and (!isset($redirect))
2317 and (!isset($printable))
2318 and (!$this->mRedirectedFrom);
2319 }
2320
2321 /**
2322 * Loads cur_touched and returns a value indicating if it should be used
2323 *
2324 */
2325 function checkTouched() {
2326 $fname = 'Article::checkTouched';
2327 if( !$this->mDataLoaded ) {
2328 $dbr =& $this->getDB();
2329 $data = $this->pageDataFromId( $dbr, $this->getId() );
2330 if( $data ) {
2331 $this->loadPageData( $data );
2332 }
2333 }
2334 return !$this->mIsRedirect;
2335 }
2336
2337 /**
2338 * Edit an article without doing all that other stuff
2339 * The article must already exist; link tables etc
2340 * are not updated, caches are not flushed.
2341 *
2342 * @param string $text text submitted
2343 * @param string $comment comment submitted
2344 * @param bool $minor whereas it's a minor modification
2345 */
2346 function quickEdit( $text, $comment = '', $minor = 0 ) {
2347 $fname = 'Article::quickEdit';
2348 wfProfileIn( $fname );
2349
2350 $dbw =& wfGetDB( DB_MASTER );
2351 $dbw->begin();
2352 $revision = new Revision( array(
2353 'page' => $this->getId(),
2354 'text' => $text,
2355 'comment' => $comment,
2356 'minor_edit' => $minor ? 1 : 0,
2357 ) );
2358 $revisionId = $revision->insertOn( $dbw );
2359 $this->updateRevisionOn( $dbw, $revision );
2360 $dbw->commit();
2361
2362 wfProfileOut( $fname );
2363 }
2364
2365 /**
2366 * Used to increment the view counter
2367 *
2368 * @static
2369 * @param integer $id article id
2370 */
2371 function incViewCount( $id ) {
2372 $id = intval( $id );
2373 global $wgHitcounterUpdateFreq;
2374
2375 $dbw =& wfGetDB( DB_MASTER );
2376 $pageTable = $dbw->tableName( 'page' );
2377 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2378 $acchitsTable = $dbw->tableName( 'acchits' );
2379
2380 if( $wgHitcounterUpdateFreq <= 1 ){ //
2381 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2382 return;
2383 }
2384
2385 # Not important enough to warrant an error page in case of failure
2386 $oldignore = $dbw->ignoreErrors( true );
2387
2388 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2389
2390 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2391 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2392 # Most of the time (or on SQL errors), skip row count check
2393 $dbw->ignoreErrors( $oldignore );
2394 return;
2395 }
2396
2397 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2398 $row = $dbw->fetchObject( $res );
2399 $rown = intval( $row->n );
2400 if( $rown >= $wgHitcounterUpdateFreq ){
2401 wfProfileIn( 'Article::incViewCount-collect' );
2402 $old_user_abort = ignore_user_abort( true );
2403
2404 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2405 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2406 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2407 'GROUP BY hc_id');
2408 $dbw->query("DELETE FROM $hitcounterTable");
2409 $dbw->query('UNLOCK TABLES');
2410 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2411 'WHERE page_id = hc_id');
2412 $dbw->query("DROP TABLE $acchitsTable");
2413
2414 ignore_user_abort( $old_user_abort );
2415 wfProfileOut( 'Article::incViewCount-collect' );
2416 }
2417 $dbw->ignoreErrors( $oldignore );
2418 }
2419
2420 /**#@+
2421 * The onArticle*() functions are supposed to be a kind of hooks
2422 * which should be called whenever any of the specified actions
2423 * are done.
2424 *
2425 * This is a good place to put code to clear caches, for instance.
2426 *
2427 * This is called on page move and undelete, as well as edit
2428 * @static
2429 * @param $title_obj a title object
2430 */
2431
2432 function onArticleCreate($title_obj) {
2433 global $wgUseSquid, $wgPostCommitUpdateList;
2434
2435 $title_obj->touchLinks();
2436 $titles = $title_obj->getLinksTo();
2437
2438 # Purge squid
2439 if ( $wgUseSquid ) {
2440 $urls = $title_obj->getSquidURLs();
2441 foreach ( $titles as $linkTitle ) {
2442 $urls[] = $linkTitle->getInternalURL();
2443 }
2444 $u = new SquidUpdate( $urls );
2445 array_push( $wgPostCommitUpdateList, $u );
2446 }
2447 }
2448
2449 function onArticleDelete( $title ) {
2450 global $wgMessageCache;
2451
2452 $title->touchLinks();
2453
2454 if( $title->getNamespace() == NS_MEDIAWIKI) {
2455 $wgMessageCache->replace( $title->getDBkey(), false );
2456 }
2457 }
2458
2459 function onArticleEdit($title_obj) {
2460 // This would be an appropriate place to purge caches.
2461 // Why's this not in here now?
2462 }
2463
2464 /**#@-*/
2465
2466 /**
2467 * Info about this page
2468 * Called for ?action=info when $wgAllowPageInfo is on.
2469 *
2470 * @access public
2471 */
2472 function info() {
2473 global $wgLang, $wgOut, $wgAllowPageInfo, $wgUser;
2474 $fname = 'Article::info';
2475
2476 if ( !$wgAllowPageInfo ) {
2477 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2478 return;
2479 }
2480
2481 $page = $this->mTitle->getSubjectPage();
2482
2483 $wgOut->setPagetitle( $page->getPrefixedText() );
2484 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2485
2486 # first, see if the page exists at all.
2487 $exists = $page->getArticleId() != 0;
2488 if( !$exists ) {
2489 $wgOut->addHTML( wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
2490 } else {
2491 $dbr =& $this->getDB( DB_SLAVE );
2492 $wl_clause = array(
2493 'wl_title' => $page->getDBkey(),
2494 'wl_namespace' => $page->getNamespace() );
2495 $numwatchers = $dbr->selectField(
2496 'watchlist',
2497 'COUNT(*)',
2498 $wl_clause,
2499 $fname,
2500 $this->getSelectOptions() );
2501
2502 $pageInfo = $this->pageCountInfo( $page );
2503 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2504
2505 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2506 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2507 if( $talkInfo ) {
2508 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2509 }
2510 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2511 if( $talkInfo ) {
2512 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2513 }
2514 $wgOut->addHTML( '</ul>' );
2515
2516 }
2517 }
2518
2519 /**
2520 * Return the total number of edits and number of unique editors
2521 * on a given page. If page does not exist, returns false.
2522 *
2523 * @param Title $title
2524 * @return array
2525 * @access private
2526 */
2527 function pageCountInfo( $title ) {
2528 $id = $title->getArticleId();
2529 if( $id == 0 ) {
2530 return false;
2531 }
2532
2533 $dbr =& $this->getDB( DB_SLAVE );
2534
2535 $rev_clause = array( 'rev_page' => $id );
2536 $fname = 'Article::pageCountInfo';
2537
2538 $edits = $dbr->selectField(
2539 'revision',
2540 'COUNT(rev_page)',
2541 $rev_clause,
2542 $fname,
2543 $this->getSelectOptions() );
2544
2545 $authors = $dbr->selectField(
2546 'revision',
2547 'COUNT(DISTINCT rev_user_text)',
2548 $rev_clause,
2549 $fname,
2550 $this->getSelectOptions() );
2551
2552 return array( 'edits' => $edits, 'authors' => $authors );
2553 }
2554
2555 /**
2556 * Return a list of templates used by this article.
2557 * Uses the links table to find the templates
2558 *
2559 * @return array
2560 */
2561 function getUsedTemplates() {
2562 $result = array();
2563 $id = $this->mTitle->getArticleID();
2564
2565 $db =& wfGetDB( DB_SLAVE );
2566 $res = $db->select( array( 'pagelinks' ),
2567 array( 'pl_title' ),
2568 array(
2569 'pl_from' => $id,
2570 'pl_namespace' => NS_TEMPLATE ),
2571 'Article:getUsedTemplates' );
2572 if ( false !== $res ) {
2573 if ( $db->numRows( $res ) ) {
2574 while ( $row = $db->fetchObject( $res ) ) {
2575 $result[] = $row->pl_title;
2576 }
2577 }
2578 }
2579 $db->freeResult( $res );
2580 return $result;
2581 }
2582 }
2583
2584 ?>