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