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