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