* Add support for a version key in $wgExtensionCredits
[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;
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 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1236 }
1237 return $good;
1238 }
1239
1240 /**
1241 * After we've either updated or inserted the article, update
1242 * the link tables and redirect to the new page.
1243 */
1244 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1245 global $wgUseDumbLinkUpdate, $wgAntiLockFlags, $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1246 global $wgUseEnotif;
1247
1248 $wgLinkCache = new LinkCache();
1249
1250 if ( !$wgUseDumbLinkUpdate ) {
1251 # Preload links to reduce lock time
1252 if ( $wgAntiLockFlags & ALF_PRELOAD_LINKS ) {
1253 $wgLinkCache->preFill( $this->mTitle );
1254 $wgLinkCache->clear();
1255 }
1256 }
1257
1258 # Parse the text and replace links with placeholders
1259 $wgOut = new OutputPage();
1260
1261 # Pass the current title along in case we're creating a wiki page
1262 # which is different than the currently displayed one (e.g. image
1263 # pages created on file uploads); otherwise, link updates will
1264 # go wrong.
1265 $wgOut->addWikiTextWithTitle( $text, $this->mTitle );
1266
1267 if ( !$wgUseDumbLinkUpdate ) {
1268 # Move the current links back to the second register
1269 $wgLinkCache->swapRegisters();
1270
1271 # Get old version of link table to allow incremental link updates
1272 # Lock this data now since it is needed for an update
1273 $wgLinkCache->forUpdate( true );
1274 $wgLinkCache->preFill( $this->mTitle );
1275
1276 # Swap this old version back into its rightful place
1277 $wgLinkCache->swapRegisters();
1278 }
1279
1280 if( $this->isRedirect( $text ) )
1281 $r = 'redirect=no';
1282 else
1283 $r = '';
1284 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1285
1286 if ( $wgUseEnotif ) {
1287 # this would be better as an extension hook
1288 include_once( "UserMailer.php" );
1289 $wgEnotif = new EmailNotification ();
1290 $wgEnotif->notifyOnPageChange( $this->mTitle, $now, $summary, $me2, $oldid );
1291 }
1292 }
1293
1294 /**
1295 * Mark this particular edit as patrolled
1296 */
1297 function markpatrolled() {
1298 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1299 $wgOut->setRobotpolicy( 'noindex,follow' );
1300
1301 if ( !$wgUseRCPatrol )
1302 {
1303 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1304 return;
1305 }
1306 if ( $wgUser->isAnon() )
1307 {
1308 $wgOut->loginToUse();
1309 return;
1310 }
1311 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1312 {
1313 $wgOut->sysopRequired();
1314 return;
1315 }
1316 $rcid = $wgRequest->getVal( 'rcid' );
1317 if ( !is_null ( $rcid ) )
1318 {
1319 RecentChange::markPatrolled( $rcid );
1320 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1321 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1322
1323 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1324 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1325 }
1326 else
1327 {
1328 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1329 }
1330 }
1331
1332 /**
1333 * Validate function
1334 */
1335 function validate() {
1336 global $wgOut, $wgUser, $wgRequest, $wgUseValidation;
1337
1338 if ( !$wgUseValidation ) # Are we using article validation at all?
1339 {
1340 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
1341 return ;
1342 }
1343
1344 $wgOut->setRobotpolicy( 'noindex,follow' );
1345 $revision = $wgRequest->getVal( 'revision' );
1346
1347 include_once ( "SpecialValidate.php" ) ; # The "Validation" class
1348
1349 $v = new Validation ;
1350 if ( $wgRequest->getVal ( "mode" , "" ) == "list" )
1351 $t = $v->showList ( $this ) ;
1352 else if ( $wgRequest->getVal ( "mode" , "" ) == "details" )
1353 $t = $v->showDetails ( $this , $wgRequest->getVal( 'revision' ) ) ;
1354 else
1355 $t = $v->validatePageForm ( $this , $revision ) ;
1356
1357 $wgOut->addHTML ( $t ) ;
1358 }
1359
1360 /**
1361 * Add this page to $wgUser's watchlist
1362 */
1363
1364 function watch() {
1365
1366 global $wgUser, $wgOut;
1367
1368 if ( $wgUser->isAnon() ) {
1369 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1370 return;
1371 }
1372 if ( wfReadOnly() ) {
1373 $wgOut->readOnlyPage();
1374 return;
1375 }
1376
1377 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1378
1379 $wgUser->addWatch( $this->mTitle );
1380 $wgUser->saveSettings();
1381
1382 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1383
1384 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1385 $wgOut->setRobotpolicy( 'noindex,follow' );
1386
1387 $link = $this->mTitle->getPrefixedText();
1388 $text = wfMsg( 'addedwatchtext', $link );
1389 $wgOut->addWikiText( $text );
1390 }
1391
1392 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1393 }
1394
1395 /**
1396 * Stop watching a page
1397 */
1398
1399 function unwatch() {
1400
1401 global $wgUser, $wgOut;
1402
1403 if ( $wgUser->isAnon() ) {
1404 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1405 return;
1406 }
1407 if ( wfReadOnly() ) {
1408 $wgOut->readOnlyPage();
1409 return;
1410 }
1411
1412 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1413
1414 $wgUser->removeWatch( $this->mTitle );
1415 $wgUser->saveSettings();
1416
1417 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1418
1419 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1420 $wgOut->setRobotpolicy( 'noindex,follow' );
1421
1422 $link = $this->mTitle->getPrefixedText();
1423 $text = wfMsg( 'removedwatchtext', $link );
1424 $wgOut->addWikiText( $text );
1425 }
1426
1427 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1428 }
1429
1430 /**
1431 * protect a page
1432 */
1433 function protect( $limit = 'sysop' ) {
1434 global $wgUser, $wgOut, $wgRequest;
1435
1436 if ( ! $wgUser->isAllowed('protect') ) {
1437 $wgOut->sysopRequired();
1438 return;
1439 }
1440 if ( wfReadOnly() ) {
1441 $wgOut->readOnlyPage();
1442 return;
1443 }
1444 $id = $this->mTitle->getArticleID();
1445 if ( 0 == $id ) {
1446 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1447 return;
1448 }
1449
1450 $confirm = $wgRequest->wasPosted() &&
1451 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1452 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1453 $reason = $wgRequest->getText( 'wpReasonProtect' );
1454
1455 if ( $confirm ) {
1456 $dbw =& wfGetDB( DB_MASTER );
1457 $dbw->update( 'page',
1458 array( /* SET */
1459 'page_touched' => $dbw->timestamp(),
1460 'page_restrictions' => (string)$limit
1461 ), array( /* WHERE */
1462 'page_id' => $id
1463 ), 'Article::protect'
1464 );
1465
1466 $restrictions = "move=" . $limit;
1467 if( !$moveonly ) {
1468 $restrictions .= ":edit=" . $limit;
1469 }
1470 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1471
1472 $dbw =& wfGetDB( DB_MASTER );
1473 $dbw->update( 'page',
1474 array( /* SET */
1475 'page_touched' => $dbw->timestamp(),
1476 'page_restrictions' => $restrictions
1477 ), array( /* WHERE */
1478 'page_id' => $id
1479 ), 'Article::protect'
1480 );
1481
1482 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1483
1484 $log = new LogPage( 'protect' );
1485 if ( $limit === '' ) {
1486 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1487 } else {
1488 $log->addEntry( 'protect', $this->mTitle, $reason );
1489 }
1490 $wgOut->redirect( $this->mTitle->getFullURL() );
1491 }
1492 return;
1493 } else {
1494 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1495 return $this->confirmProtect( '', $reason, $limit );
1496 }
1497 }
1498
1499 /**
1500 * Output protection confirmation dialog
1501 */
1502 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1503 global $wgOut, $wgUser;
1504
1505 wfDebug( "Article::confirmProtect\n" );
1506
1507 $sub = $this->mTitle->getPrefixedText();
1508 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1509
1510 $check = '';
1511 $protcom = '';
1512 $moveonly = '';
1513
1514 if ( $limit === '' ) {
1515 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1516 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1517 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1518 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1519 $formaction = $this->mTitle->escapeLocalURL( 'action=unprotect' . $par );
1520 } else {
1521 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1522 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1523 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1524 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1525 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1526 $formaction = $this->mTitle->escapeLocalURL( 'action=protect' . $par );
1527 }
1528
1529 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1530 $token = htmlspecialchars( $wgUser->editToken() );
1531
1532 $wgOut->addHTML( "
1533 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1534 <table border='0'>
1535 <tr>
1536 <td align='right'>
1537 <label for='wpReasonProtect'>{$protcom}:</label>
1538 </td>
1539 <td align='left'>
1540 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1541 </td>
1542 </tr>" );
1543 if($moveonly != '') {
1544 $wgOut->AddHTML( "
1545 <tr>
1546 <td align='right'>
1547 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1548 </td>
1549 <td align='left'>
1550 <label for='wpMoveOnly'>{$moveonly}</label>
1551 </td>
1552 </tr> " );
1553 }
1554 $wgOut->addHTML( "
1555 <tr>
1556 <td>&nbsp;</td>
1557 <td>
1558 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1559 </td>
1560 </tr>
1561 </table>
1562 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1563 </form>" );
1564
1565 $wgOut->returnToMain( false );
1566 }
1567
1568 /**
1569 * Unprotect the pages
1570 */
1571 function unprotect() {
1572 return $this->protect( '' );
1573 }
1574
1575 /*
1576 * UI entry point for page deletion
1577 */
1578 function delete() {
1579 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1580 $fname = 'Article::delete';
1581 $confirm = $wgRequest->wasPosted() &&
1582 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1583 $reason = $wgRequest->getText( 'wpReason' );
1584
1585 # This code desperately needs to be totally rewritten
1586
1587 # Check permissions
1588 if( ( !$wgUser->isAllowed( 'delete' ) ) ) {
1589 $wgOut->sysopRequired();
1590 return;
1591 }
1592 if( wfReadOnly() ) {
1593 $wgOut->readOnlyPage();
1594 return;
1595 }
1596
1597 # Better double-check that it hasn't been deleted yet!
1598 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1599 if( !$this->mTitle->exists() ) {
1600 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1601 return;
1602 }
1603
1604 if( $confirm ) {
1605 $this->doDelete( $reason );
1606 return;
1607 }
1608
1609 # determine whether this page has earlier revisions
1610 # and insert a warning if it does
1611 # we select the text because it might be useful below
1612 $dbr =& $this->getDB();
1613 $ns = $this->mTitle->getNamespace();
1614 $title = $this->mTitle->getDBkey();
1615 $revisions = $dbr->select( array( 'page', 'revision' ),
1616 array( 'rev_id', 'rev_user_text' ),
1617 array(
1618 'page_namespace' => $ns,
1619 'page_title' => $title,
1620 'rev_page = page_id'
1621 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1622 );
1623
1624 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1625 $skin=$wgUser->getSkin();
1626 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1627 $wgOut->addHTML( $skin->historyLink() .'</b>');
1628 }
1629
1630 # Fetch cur_text
1631 $rev =& Revision::newFromTitle( $this->mTitle );
1632
1633 # Fetch name(s) of contributors
1634 $rev_name = '';
1635 $all_same_user = true;
1636 while( $row = $dbr->fetchObject( $revisions ) ) {
1637 if( $rev_name != '' && $rev_name != $row->rev_user_text ) {
1638 $all_same_user = false;
1639 } else {
1640 $rev_name = $row->rev_user_text;
1641 }
1642 }
1643
1644 if( !is_null( $rev ) ) {
1645 # if this is a mini-text, we can paste part of it into the deletion reason
1646 $text = $rev->getText();
1647
1648 #if this is empty, an earlier revision may contain "useful" text
1649 $blanked = false;
1650 if( $text == '' ) {
1651 $prev = $rev->getPrevious();
1652 if( $prev ) {
1653 $text = $prev->getText();
1654 $blanked = true;
1655 }
1656 }
1657
1658 $length = strlen( $text );
1659
1660 # this should not happen, since it is not possible to store an empty, new
1661 # page. Let's insert a standard text in case it does, though
1662 if( $length == 0 && $reason === '' ) {
1663 $reason = wfMsg( 'exblank' );
1664 }
1665
1666 if( $length < 500 && $reason === '' ) {
1667 # comment field=255, let's grep the first 150 to have some user
1668 # space left
1669 global $wgContLang;
1670 $text = $wgContLang->truncate( $text, 150, '...' );
1671
1672 # let's strip out newlines
1673 $text = preg_replace( "/[\n\r]/", '', $text );
1674
1675 if( !$blanked ) {
1676 if( !$all_same_user ) {
1677 $reason = wfMsg( 'excontent', $text );
1678 } else {
1679 $reason = wfMsg( 'excontentauthor', $text, $rev_name );
1680 }
1681 } else {
1682 $reason = wfMsg( 'exbeforeblank', $text );
1683 }
1684 }
1685 }
1686
1687 return $this->confirmDelete( '', $reason );
1688 }
1689
1690 /**
1691 * Output deletion confirmation dialog
1692 */
1693 function confirmDelete( $par, $reason ) {
1694 global $wgOut, $wgUser;
1695
1696 wfDebug( "Article::confirmDelete\n" );
1697
1698 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1699 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1700 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1701 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1702
1703 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1704
1705 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1706 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1707 $token = htmlspecialchars( $wgUser->editToken() );
1708
1709 $wgOut->addHTML( "
1710 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1711 <table border='0'>
1712 <tr>
1713 <td align='right'>
1714 <label for='wpReason'>{$delcom}:</label>
1715 </td>
1716 <td align='left'>
1717 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1718 </td>
1719 </tr>
1720 <tr>
1721 <td>&nbsp;</td>
1722 <td>
1723 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1724 </td>
1725 </tr>
1726 </table>
1727 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1728 </form>\n" );
1729
1730 $wgOut->returnToMain( false );
1731 }
1732
1733
1734 /**
1735 * Perform a deletion and output success or failure messages
1736 */
1737 function doDelete( $reason ) {
1738 global $wgOut, $wgUser, $wgContLang;
1739 $fname = 'Article::doDelete';
1740 wfDebug( $fname."\n" );
1741
1742 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1743 if ( $this->doDeleteArticle( $reason ) ) {
1744 $deleted = $this->mTitle->getPrefixedText();
1745
1746 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1747 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1748
1749 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1750 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1751
1752 $wgOut->addWikiText( $text );
1753 $wgOut->returnToMain( false );
1754 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1755 } else {
1756 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1757 }
1758 }
1759 }
1760
1761 /**
1762 * Back-end article deletion
1763 * Deletes the article with database consistency, writes logs, purges caches
1764 * Returns success
1765 */
1766 function doDeleteArticle( $reason ) {
1767 global $wgUser;
1768 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1769
1770 $fname = 'Article::doDeleteArticle';
1771 wfDebug( $fname."\n" );
1772
1773 $dbw =& wfGetDB( DB_MASTER );
1774 $ns = $this->mTitle->getNamespace();
1775 $t = $this->mTitle->getDBkey();
1776 $id = $this->mTitle->getArticleID();
1777
1778 if ( $t == '' || $id == 0 ) {
1779 return false;
1780 }
1781
1782 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ), -1 );
1783 array_push( $wgDeferredUpdateList, $u );
1784
1785 $linksTo = $this->mTitle->getLinksTo();
1786
1787 # Squid purging
1788 if ( $wgUseSquid ) {
1789 $urls = array(
1790 $this->mTitle->getInternalURL(),
1791 $this->mTitle->getInternalURL( 'history' )
1792 );
1793
1794 $u = SquidUpdate::newFromTitles( $linksTo, $urls );
1795 array_push( $wgPostCommitUpdateList, $u );
1796
1797 }
1798
1799 # Client and file cache invalidation
1800 Title::touchArray( $linksTo );
1801
1802
1803 // For now, shunt the revision data into the archive table.
1804 // Text is *not* removed from the text table; bulk storage
1805 // is left intact to avoid breaking block-compression or
1806 // immutable storage schemes.
1807 //
1808 // For backwards compatibility, note that some older archive
1809 // table entries will have ar_text and ar_flags fields still.
1810 //
1811 // In the future, we may keep revisions and mark them with
1812 // the rev_deleted field, which is reserved for this purpose.
1813 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1814 array(
1815 'ar_namespace' => 'page_namespace',
1816 'ar_title' => 'page_title',
1817 'ar_comment' => 'rev_comment',
1818 'ar_user' => 'rev_user',
1819 'ar_user_text' => 'rev_user_text',
1820 'ar_timestamp' => 'rev_timestamp',
1821 'ar_minor_edit' => 'rev_minor_edit',
1822 'ar_rev_id' => 'rev_id',
1823 'ar_text_id' => 'rev_text_id',
1824 ), array(
1825 'page_id' => $id,
1826 'page_id = rev_page'
1827 ), $fname
1828 );
1829
1830 # Now that it's safely backed up, delete it
1831 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1832 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1833
1834 # Clean up recentchanges entries...
1835 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1836
1837 # Finally, clean up the link tables
1838 $t = $this->mTitle->getPrefixedDBkey();
1839
1840 Article::onArticleDelete( $this->mTitle );
1841
1842 # Delete outgoing links
1843 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1844 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1845 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1846
1847 # Log the deletion
1848 $log = new LogPage( 'delete' );
1849 $log->addEntry( 'delete', $this->mTitle, $reason );
1850
1851 # Clear the cached article id so the interface doesn't act like we exist
1852 $this->mTitle->resetArticleID( 0 );
1853 $this->mTitle->mArticleID = 0;
1854 return true;
1855 }
1856
1857 /**
1858 * Revert a modification
1859 */
1860 function rollback() {
1861 global $wgUser, $wgOut, $wgRequest;
1862 $fname = 'Article::rollback';
1863
1864 if ( ! $wgUser->isAllowed('rollback') ) {
1865 $wgOut->sysopRequired();
1866 return;
1867 }
1868 if ( wfReadOnly() ) {
1869 $wgOut->readOnlyPage( $this->getContent( true ) );
1870 return;
1871 }
1872 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1873 array( $this->mTitle->getPrefixedText(),
1874 $wgRequest->getVal( 'from' ) ) ) ) {
1875 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1876 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1877 return;
1878 }
1879 $dbw =& wfGetDB( DB_MASTER );
1880
1881 # Enhanced rollback, marks edits rc_bot=1
1882 $bot = $wgRequest->getBool( 'bot' );
1883
1884 # Replace all this user's current edits with the next one down
1885 $tt = $this->mTitle->getDBKey();
1886 $n = $this->mTitle->getNamespace();
1887
1888 # Get the last editor, lock table exclusively
1889 $dbw->begin();
1890 $current = Revision::newFromTitle( $this->mTitle );
1891 if( is_null( $current ) ) {
1892 # Something wrong... no page?
1893 $dbw->rollback();
1894 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1895 return;
1896 }
1897
1898 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1899 if( $from != $current->getUserText() ) {
1900 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1901 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1902 htmlspecialchars( $this->mTitle->getPrefixedText()),
1903 htmlspecialchars( $from ),
1904 htmlspecialchars( $current->getUserText() ) ) );
1905 if( $current->getComment() != '') {
1906 $wgOut->addHTML(
1907 wfMsg( 'editcomment',
1908 htmlspecialchars( $current->getComment() ) ) );
1909 }
1910 return;
1911 }
1912
1913 # Get the last edit not by this guy
1914 $user = IntVal( $current->getUser() );
1915 $user_text = $dbw->addQuotes( $current->getUserText() );
1916 $s = $dbw->selectRow( 'revision',
1917 array( 'rev_id', 'rev_timestamp' ),
1918 array(
1919 'rev_page' => $current->getPage(),
1920 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
1921 ), $fname,
1922 array(
1923 'USE INDEX' => 'page_timestamp',
1924 'ORDER BY' => 'rev_timestamp DESC' )
1925 );
1926 if( $s === false ) {
1927 # Something wrong
1928 $dbw->rollback();
1929 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1930 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1931 return;
1932 }
1933
1934 if ( $bot ) {
1935 # Mark all reverted edits as bot
1936 $dbw->update( 'recentchanges',
1937 array( /* SET */
1938 'rc_bot' => 1
1939 ), array( /* WHERE */
1940 'rc_cur_id' => $current->getPage(),
1941 'rc_user_text' => $current->getUserText(),
1942 "rc_timestamp > '{$s->rev_timestamp}'",
1943 ), $fname
1944 );
1945 }
1946
1947 # Save it!
1948 $target = Revision::newFromId( $s->rev_id );
1949 $newcomment = wfMsg( 'revertpage', $target->getUserText(), $from );
1950
1951 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1952 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1953 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1954
1955 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle->userIsWatching(), $bot );
1956 Article::onArticleEdit( $this->mTitle );
1957
1958 $dbw->commit();
1959 $wgOut->returnToMain( false );
1960 }
1961
1962
1963 /**
1964 * Do standard deferred updates after page view
1965 * @private
1966 */
1967 function viewUpdates() {
1968 global $wgDeferredUpdateList, $wgUseEnotif;
1969
1970 if ( 0 != $this->getID() ) {
1971 global $wgDisableCounters;
1972 if( !$wgDisableCounters ) {
1973 Article::incViewCount( $this->getID() );
1974 $u = new SiteStatsUpdate( 1, 0, 0 );
1975 array_push( $wgDeferredUpdateList, $u );
1976 }
1977 }
1978
1979 # Update newtalk status if user is reading their own
1980 # talk page
1981
1982 global $wgUser;
1983 if ($this->mTitle->getNamespace() == NS_USER_TALK &&
1984 $this->mTitle->getText() == $wgUser->getName())
1985 {
1986 if ( $wgUseEnotif ) {
1987 require_once( 'UserTalkUpdate.php' );
1988 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(), $this->mTitle->getDBkey(), false, false, false );
1989 } else {
1990 $wgUser->setNewtalk(0);
1991 $wgUser->saveNewtalk();
1992 }
1993 } elseif ( $wgUseEnotif ) {
1994 $wgUser->clearNotification( $this->mTitle );
1995 }
1996
1997 }
1998
1999 /**
2000 * Do standard deferred updates after page edit.
2001 * Every 1000th edit, prune the recent changes table.
2002 * @private
2003 * @param string $text
2004 */
2005 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
2006 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
2007 global $wgMessageCache, $wgUser, $wgUseEnotif;
2008
2009 wfSeedRandom();
2010 if ( 0 == mt_rand( 0, 999 ) ) {
2011 # Periodically flush old entries from the recentchanges table.
2012 global $wgRCMaxAge;
2013 $dbw =& wfGetDB( DB_MASTER );
2014 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
2015 $recentchanges = $dbw->tableName( 'recentchanges' );
2016 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
2017 $dbw->query( $sql );
2018 }
2019 $id = $this->getID();
2020 $title = $this->mTitle->getPrefixedDBkey();
2021 $shortTitle = $this->mTitle->getDBkey();
2022
2023 if ( 0 != $id ) {
2024 $u = new LinksUpdate( $id, $title );
2025 array_push( $wgDeferredUpdateList, $u );
2026 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
2027 array_push( $wgDeferredUpdateList, $u );
2028 $u = new SearchUpdate( $id, $title, $text );
2029 array_push( $wgDeferredUpdateList, $u );
2030
2031 # If this is another user's talk page, update newtalk
2032
2033 if ($this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName()) {
2034 if ( $wgUseEnotif ) {
2035 require_once( 'UserTalkUpdate.php' );
2036 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle, $summary,
2037 $minoredit, $timestamp_of_pagechange);
2038 } else {
2039 $other = User::newFromName( $shortTitle );
2040 if( is_null( $other ) && User::isIP( $shortTitle ) ) {
2041 // An anonymous user
2042 $other = new User();
2043 $other->setName( $shortTitle );
2044 }
2045 if( $other ) {
2046 $other->setNewtalk(1);
2047 $other->saveNewtalk();
2048 }
2049 }
2050 }
2051
2052 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2053 $wgMessageCache->replace( $shortTitle, $text );
2054 }
2055 }
2056 }
2057
2058 /**
2059 * @todo document this function
2060 * @private
2061 * @param string $oldid Revision ID of this article revision
2062 */
2063 function setOldSubtitle( $oldid=0 ) {
2064 global $wgLang, $wgOut, $wgUser;
2065
2066 $current = ( $oldid == $this->mLatest );
2067 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2068 $sk = $wgUser->getSkin();
2069 $lnk = $current
2070 ? wfMsg( 'currentrevisionlink' )
2071 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2072 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
2073 $nextlink = $current
2074 ? wfMsg( 'nextrevision' )
2075 : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
2076 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
2077 $wgOut->setSubtitle( $r );
2078 }
2079
2080 /**
2081 * This function is called right before saving the wikitext,
2082 * so we can do things like signatures and links-in-context.
2083 *
2084 * @param string $text
2085 */
2086 function preSaveTransform( $text ) {
2087 global $wgParser, $wgUser;
2088 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
2089 }
2090
2091 /* Caching functions */
2092
2093 /**
2094 * checkLastModified returns true if it has taken care of all
2095 * output to the client that is necessary for this request.
2096 * (that is, it has sent a cached version of the page)
2097 */
2098 function tryFileCache() {
2099 static $called = false;
2100 if( $called ) {
2101 wfDebug( " tryFileCache() -- called twice!?\n" );
2102 return;
2103 }
2104 $called = true;
2105 if($this->isFileCacheable()) {
2106 $touched = $this->mTouched;
2107 $cache = new CacheManager( $this->mTitle );
2108 if($cache->isFileCacheGood( $touched )) {
2109 global $wgOut;
2110 wfDebug( " tryFileCache() - about to load\n" );
2111 $cache->loadFromFileCache();
2112 return true;
2113 } else {
2114 wfDebug( " tryFileCache() - starting buffer\n" );
2115 ob_start( array(&$cache, 'saveToFileCache' ) );
2116 }
2117 } else {
2118 wfDebug( " tryFileCache() - not cacheable\n" );
2119 }
2120 }
2121
2122 /**
2123 * Check if the page can be cached
2124 * @return bool
2125 */
2126 function isFileCacheable() {
2127 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2128 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2129
2130 return $wgUseFileCache
2131 and (!$wgShowIPinHeader)
2132 and ($this->getID() != 0)
2133 and ($wgUser->isAnon())
2134 and (!$wgUser->getNewtalk())
2135 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2136 and (empty( $action ) || $action == 'view')
2137 and (!isset($oldid))
2138 and (!isset($diff))
2139 and (!isset($redirect))
2140 and (!isset($printable))
2141 and (!$this->mRedirectedFrom);
2142 }
2143
2144 /**
2145 * Loads cur_touched and returns a value indicating if it should be used
2146 *
2147 */
2148 function checkTouched() {
2149 $fname = 'Article::checkTouched';
2150 if( !$this->mDataLoaded ) {
2151 $dbr =& $this->getDB();
2152 $data = $this->pageDataFromId( $dbr, $this->getId() );
2153 if( $data ) {
2154 $this->loadPageData( $data );
2155 }
2156 }
2157 return !$this->mIsRedirect;
2158 }
2159
2160 /**
2161 * Edit an article without doing all that other stuff
2162 * The article must already exist; link tables etc
2163 * are not updated, caches are not flushed.
2164 *
2165 * @param string $text text submitted
2166 * @param string $comment comment submitted
2167 * @param bool $minor whereas it's a minor modification
2168 */
2169 function quickEdit( $text, $comment = '', $minor = 0 ) {
2170 $fname = 'Article::quickEdit';
2171 wfProfileIn( $fname );
2172
2173 $dbw =& wfGetDB( DB_MASTER );
2174 $dbw->begin();
2175 $revision = new Revision( array(
2176 'page' => $this->getId(),
2177 'text' => $text,
2178 'comment' => $comment,
2179 'minor_edit' => $minor ? 1 : 0,
2180 ) );
2181 $revisionId = $revision->insertOn( $dbw );
2182 $this->updateRevisionOn( $dbw, $revision );
2183 $dbw->commit();
2184
2185 wfProfileOut( $fname );
2186 }
2187
2188 /**
2189 * Used to increment the view counter
2190 *
2191 * @static
2192 * @param integer $id article id
2193 */
2194 function incViewCount( $id ) {
2195 $id = intval( $id );
2196 global $wgHitcounterUpdateFreq;
2197
2198 $dbw =& wfGetDB( DB_MASTER );
2199 $pageTable = $dbw->tableName( 'page' );
2200 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2201 $acchitsTable = $dbw->tableName( 'acchits' );
2202
2203 if( $wgHitcounterUpdateFreq <= 1 ){ //
2204 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2205 return;
2206 }
2207
2208 # Not important enough to warrant an error page in case of failure
2209 $oldignore = $dbw->ignoreErrors( true );
2210
2211 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2212
2213 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2214 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2215 # Most of the time (or on SQL errors), skip row count check
2216 $dbw->ignoreErrors( $oldignore );
2217 return;
2218 }
2219
2220 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2221 $row = $dbw->fetchObject( $res );
2222 $rown = intval( $row->n );
2223 if( $rown >= $wgHitcounterUpdateFreq ){
2224 wfProfileIn( 'Article::incViewCount-collect' );
2225 $old_user_abort = ignore_user_abort( true );
2226
2227 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2228 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2229 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2230 'GROUP BY hc_id');
2231 $dbw->query("DELETE FROM $hitcounterTable");
2232 $dbw->query('UNLOCK TABLES');
2233 $dbw->query("UPDATE $pageTable,$acchitsTable SET page_counter=page_counter + hc_n ".
2234 'WHERE page_id = hc_id');
2235 $dbw->query("DROP TABLE $acchitsTable");
2236
2237 ignore_user_abort( $old_user_abort );
2238 wfProfileOut( 'Article::incViewCount-collect' );
2239 }
2240 $dbw->ignoreErrors( $oldignore );
2241 }
2242
2243 /**#@+
2244 * The onArticle*() functions are supposed to be a kind of hooks
2245 * which should be called whenever any of the specified actions
2246 * are done.
2247 *
2248 * This is a good place to put code to clear caches, for instance.
2249 *
2250 * This is called on page move and undelete, as well as edit
2251 * @static
2252 * @param $title_obj a title object
2253 */
2254
2255 function onArticleCreate($title_obj) {
2256 global $wgUseSquid, $wgPostCommitUpdateList;
2257
2258 $title_obj->touchLinks();
2259 $titles = $title_obj->getLinksTo();
2260
2261 # Purge squid
2262 if ( $wgUseSquid ) {
2263 $urls = $title_obj->getSquidURLs();
2264 foreach ( $titles as $linkTitle ) {
2265 $urls[] = $linkTitle->getInternalURL();
2266 }
2267 $u = new SquidUpdate( $urls );
2268 array_push( $wgPostCommitUpdateList, $u );
2269 }
2270 }
2271
2272 function onArticleDelete($title_obj) {
2273 $title_obj->touchLinks();
2274 }
2275
2276 function onArticleEdit($title_obj) {
2277 // This would be an appropriate place to purge caches.
2278 // Why's this not in here now?
2279 }
2280
2281 /**#@-*/
2282
2283 /**
2284 * Info about this page
2285 * Called for ?action=info when $wgAllowPageInfo is on.
2286 *
2287 * @access public
2288 */
2289 function info() {
2290 global $wgLang, $wgOut, $wgAllowPageInfo;
2291 $fname = 'Article::info';
2292
2293 if ( !$wgAllowPageInfo ) {
2294 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2295 return;
2296 }
2297
2298 $page = $this->mTitle->getSubjectPage();
2299
2300 $wgOut->setPagetitle( $page->getPrefixedText() );
2301 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2302
2303 # first, see if the page exists at all.
2304 $exists = $page->getArticleId() != 0;
2305 if( !$exists ) {
2306 $wgOut->addHTML( wfMsg('noarticletext') );
2307 } else {
2308 $dbr =& $this->getDB( DB_SLAVE );
2309 $wl_clause = array(
2310 'wl_title' => $page->getDBkey(),
2311 'wl_namespace' => $page->getNamespace() );
2312 $numwatchers = $dbr->selectField(
2313 'watchlist',
2314 'COUNT(*)',
2315 $wl_clause,
2316 $fname,
2317 $this->getSelectOptions() );
2318
2319 $pageInfo = $this->pageCountInfo( $page );
2320 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2321
2322 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2323 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2324 if( $talkInfo ) {
2325 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2326 }
2327 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2328 if( $talkInfo ) {
2329 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2330 }
2331 $wgOut->addHTML( '</ul>' );
2332
2333 }
2334 }
2335
2336 /**
2337 * Return the total number of edits and number of unique editors
2338 * on a given page. If page does not exist, returns false.
2339 *
2340 * @param Title $title
2341 * @return array
2342 * @access private
2343 */
2344 function pageCountInfo( $title ) {
2345 $id = $title->getArticleId();
2346 if( $id == 0 ) {
2347 return false;
2348 }
2349
2350 $dbr =& $this->getDB( DB_SLAVE );
2351
2352 $rev_clause = array( 'rev_page' => $id );
2353 $fname = 'Article::pageCountInfo';
2354
2355 $edits = $dbr->selectField(
2356 'revision',
2357 'COUNT(rev_page)',
2358 $rev_clause,
2359 $fname,
2360 $this->getSelectOptions() );
2361
2362 $authors = $dbr->selectField(
2363 'revision',
2364 'COUNT(DISTINCT rev_user_text)',
2365 $rev_clause,
2366 $fname,
2367 $this->getSelectOptions() );
2368
2369 return array( 'edits' => $edits, 'authors' => $authors );
2370 }
2371
2372 /**
2373 * Return a list of templates used by this article.
2374 * Uses the links table to find the templates
2375 *
2376 * @return array
2377 */
2378 function getUsedTemplates() {
2379 $result = array();
2380 $id = $this->mTitle->getArticleID();
2381
2382 $db =& wfGetDB( DB_SLAVE );
2383 $res = $db->select( array( 'pagelinks' ),
2384 array( 'pl_title' ),
2385 array(
2386 'pl_from' => $id,
2387 'pl_namespace' => NS_TEMPLATE ),
2388 'Article:getUsedTemplates' );
2389 if ( false !== $res ) {
2390 if ( $db->numRows( $res ) ) {
2391 while ( $row = $db->fetchObject( $res ) ) {
2392 $result[] = $row->pl_title;
2393 }
2394 }
2395 }
2396 $db->freeResult( $res );
2397 return $result;
2398 }
2399
2400
2401 }
2402
2403
2404 ?>