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