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