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