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