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