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