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