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