57a1fe0bdeaa9a6cdbdafa338942d3ac71604400
[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 * Returns true if this article exists in the database.
496 * @return bool
497 */
498 function exists() {
499 return $this->getId() != 0;
500 }
501
502 /**
503 * Get the view count for this article
504 */
505 function getCount() {
506 if ( -1 == $this->mCounter ) {
507 $id = $this->getID();
508 $dbr =& $this->getDB();
509 $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
510 'Article::getCount', $this->getSelectOptions() );
511 }
512 return $this->mCounter;
513 }
514
515 /**
516 * Would the given text make this article a "good" article (i.e.,
517 * suitable for including in the article count)?
518 * @param string $text Text to analyze
519 * @return integer 1 if it can be counted else 0
520 */
521 function isCountable( $text ) {
522 global $wgUseCommaCount;
523
524 if ( NS_MAIN != $this->mTitle->getNamespace() ) { return 0; }
525 if ( $this->isRedirect( $text ) ) { return 0; }
526 $token = ($wgUseCommaCount ? ',' : '[[' );
527 if ( false === strstr( $text, $token ) ) { return 0; }
528 return 1;
529 }
530
531 /**
532 * Tests if the article text represents a redirect
533 */
534 function isRedirect( $text = false ) {
535 if ( $text === false ) {
536 $this->loadContent();
537 $titleObj = Title::newFromRedirect( $this->fetchContent() );
538 } else {
539 $titleObj = Title::newFromRedirect( $text );
540 }
541 return $titleObj !== NULL;
542 }
543
544 /**
545 * Returns true if the currently-referenced revision is the current edit
546 * to this page (and it exists).
547 * @return bool
548 */
549 function isCurrent() {
550 return $this->exists() &&
551 isset( $this->mRevision ) &&
552 $this->mRevision->isCurrent();
553 }
554
555 /**
556 * Loads everything except the text
557 * This isn't necessary for all uses, so it's only done if needed.
558 * @private
559 */
560 function loadLastEdit() {
561 global $wgOut;
562
563 if ( -1 != $this->mUser )
564 return;
565
566 # New or non-existent articles have no user information
567 $id = $this->getID();
568 if ( 0 == $id ) return;
569
570 $this->mLastRevision = Revision::loadFromPageId( $this->getDB(), $id );
571 if( !is_null( $this->mLastRevision ) ) {
572 $this->mUser = $this->mLastRevision->getUser();
573 $this->mUserText = $this->mLastRevision->getUserText();
574 $this->mTimestamp = $this->mLastRevision->getTimestamp();
575 $this->mComment = $this->mLastRevision->getComment();
576 $this->mMinorEdit = $this->mLastRevision->isMinor();
577 }
578 }
579
580 function getTimestamp() {
581 $this->loadLastEdit();
582 return $this->mTimestamp;
583 }
584
585 function getUser() {
586 $this->loadLastEdit();
587 return $this->mUser;
588 }
589
590 function getUserText() {
591 $this->loadLastEdit();
592 return $this->mUserText;
593 }
594
595 function getComment() {
596 $this->loadLastEdit();
597 return $this->mComment;
598 }
599
600 function getMinorEdit() {
601 $this->loadLastEdit();
602 return $this->mMinorEdit;
603 }
604
605 function getRevIdFetched() {
606 $this->loadLastEdit();
607 return $this->mRevIdFetched;
608 }
609
610 function getContributors($limit = 0, $offset = 0) {
611 $fname = 'Article::getContributors';
612
613 # XXX: this is expensive; cache this info somewhere.
614
615 $title = $this->mTitle;
616 $contribs = array();
617 $dbr =& $this->getDB();
618 $revTable = $dbr->tableName( 'revision' );
619 $userTable = $dbr->tableName( 'user' );
620 $encDBkey = $dbr->addQuotes( $title->getDBkey() );
621 $ns = $title->getNamespace();
622 $user = $this->getUser();
623 $pageId = $this->getId();
624
625 $sql = "SELECT rev_user, rev_user_text, user_real_name, MAX(rev_timestamp) as timestamp
626 FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
627 WHERE rev_page = $pageId
628 AND rev_user != $user
629 GROUP BY rev_user, rev_user_text, user_real_name
630 ORDER BY timestamp DESC";
631
632 if ($limit > 0) { $sql .= ' LIMIT '.$limit; }
633 $sql .= ' '. $this->getSelectOptions();
634
635 $res = $dbr->query($sql, $fname);
636
637 while ( $line = $dbr->fetchObject( $res ) ) {
638 $contribs[] = array($line->rev_user, $line->rev_user_text, $line->user_real_name);
639 }
640
641 $dbr->freeResult($res);
642 return $contribs;
643 }
644
645 /**
646 * This is the default action of the script: just view the page of
647 * the given title.
648 */
649 function view() {
650 global $wgUser, $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgLang;
651 global $wgLinkCache, $IP, $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol;
652 global $wgEnotif, $wgParser, $wgParserCache;
653 $sk = $wgUser->getSkin();
654
655 $fname = 'Article::view';
656 wfProfileIn( $fname );
657 # Get variables from query string
658 $oldid = $this->getOldID();
659 $diff = $wgRequest->getVal( 'diff' );
660 $rcid = $wgRequest->getVal( 'rcid' );
661 $rdfrom = $wgRequest->getVal( 'rdfrom' );
662
663 $wgOut->setArticleFlag( true );
664 $wgOut->setRobotpolicy( 'index,follow' );
665 # If we got diff and oldid in the query, we want to see a
666 # diff page instead of the article.
667
668 if ( !is_null( $diff ) ) {
669 require_once( 'DifferenceEngine.php' );
670 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
671
672 $de = new DifferenceEngine( $oldid, $diff, $rcid );
673 // DifferenceEngine directly fetched the revision:
674 $this->mRevIdFetched = $de->mNewid;
675 $de->showDiffPage();
676
677 if( $diff == 0 ) {
678 # Run view updates for current revision only
679 $this->viewUpdates();
680 }
681 wfProfileOut( $fname );
682 return;
683 }
684
685 if ( empty( $oldid ) && $this->checkTouched() ) {
686 $wgOut->setETag($wgParserCache->getETag($this, $wgUser));
687
688 if( $wgOut->checkLastModified( $this->mTouched ) ){
689 wfProfileOut( $fname );
690 return;
691 } else if ( $this->tryFileCache() ) {
692 # tell wgOut that output is taken care of
693 $wgOut->disable();
694 $this->viewUpdates();
695 wfProfileOut( $fname );
696 return;
697 }
698 }
699 # Should the parser cache be used?
700 $pcache = $wgEnableParserCache &&
701 intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
702 $this->exists() &&
703 empty( $oldid );
704 wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
705
706 $outputDone = false;
707 if ( $pcache ) {
708 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
709 $outputDone = true;
710 }
711 }
712 if ( !$outputDone ) {
713 $text = $this->getContent( false ); # May change mTitle by following a redirect
714
715 # Another whitelist check in case oldid or redirects are altering the title
716 if ( !$this->mTitle->userCanRead() ) {
717 $wgOut->loginToUse();
718 $wgOut->output();
719 exit;
720 }
721
722 # We're looking at an old revision
723
724 if ( !empty( $oldid ) ) {
725 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
726 $wgOut->setRobotpolicy( 'noindex,follow' );
727 }
728 if ( '' != $this->mRedirectedFrom ) {
729 $sk = $wgUser->getSkin();
730 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, '',
731 'redirect=no' );
732 $s = wfMsg( 'redirectedfrom', $redir );
733 $wgOut->setSubtitle( $s );
734
735 # Can't cache redirects
736 $pcache = false;
737 } elseif ( !empty( $rdfrom ) ) {
738 global $wgRedirectSources;
739 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
740 $sk = $wgUser->getSkin();
741 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
742 $s = wfMsg( 'redirectedfrom', $redir );
743 $wgOut->setSubtitle( $s );
744 }
745 }
746
747 # wrap user css and user js in pre and don't parse
748 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
749 if (
750 $this->mTitle->getNamespace() == NS_USER &&
751 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
752 ) {
753 $wgOut->addWikiText( wfMsg('clearyourcache'));
754 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
755 } else if ( $rt = Title::newFromRedirect( $text ) ) {
756 # Display redirect
757 $imageUrl = $wgStylePath.'/common/images/redirect.png';
758 $targetUrl = $rt->escapeLocalURL();
759 $titleText = htmlspecialchars( $rt->getPrefixedText() );
760 $link = $sk->makeLinkObj( $rt );
761
762 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
763 '<span class="redirectText">'.$link.'</span>' );
764
765 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
766 $catlinks = $parseout->getCategoryLinks();
767 $wgOut->addCategoryLinks($catlinks);
768 $skin = $wgUser->getSkin();
769 } else if ( $pcache ) {
770 # Display content and save to parser cache
771 $wgOut->addPrimaryWikiText( $text, $this );
772 } else {
773 # Display content, don't attempt to save to parser cache
774
775 # Don't show section-edit links on old revisions... this way lies madness.
776 if( !$this->isCurrent() ) {
777 $oldEditSectionSetting = $wgOut->mParserOptions->setEditSection( false );
778 }
779 $wgOut->addWikiText( $text );
780
781 if( !$this->isCurrent() ) {
782 $wgOut->mParserOptions->setEditSection( $oldEditSectionSetting );
783 }
784 }
785 }
786 /* title may have been set from the cache */
787 $t = $wgOut->getPageTitle();
788 if( empty( $t ) ) {
789 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
790 }
791
792 # If we have been passed an &rcid= parameter, we want to give the user a
793 # chance to mark this new article as patrolled.
794 if ( $wgUseRCPatrol
795 && !is_null($rcid)
796 && $rcid != 0
797 && $wgUser->isLoggedIn()
798 && ( $wgUser->isAllowed('patrol') || !$wgOnlySysopsCanPatrol ) )
799 {
800 $wgOut->addHTML(
801 "<div class='patrollink'>" .
802 wfMsg ( 'markaspatrolledlink',
803 $sk->makeKnownLinkObj( $this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
804 ) .
805 '</div>'
806 );
807 }
808
809 # Put link titles into the link cache
810 $wgOut->transformBuffer();
811
812 # Add link titles as META keywords
813 $wgOut->addMetaTags() ;
814
815 $this->viewUpdates();
816 wfProfileOut( $fname );
817 }
818
819 /**
820 * Insert a new empty page record for this article.
821 * This *must* be followed up by creating a revision
822 * and running $this->updateToLatest( $rev_id );
823 * or else the record will be left in a funky state.
824 * Best if all done inside a transaction.
825 *
826 * @param Database $dbw
827 * @param string $restrictions
828 * @return int The newly created page_id key
829 * @access private
830 */
831 function insertOn( &$dbw, $restrictions = '' ) {
832 $fname = 'Article::insertOn';
833 wfProfileIn( $fname );
834
835 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
836 $dbw->insert( 'page', array(
837 'page_id' => $page_id,
838 'page_namespace' => $this->mTitle->getNamespace(),
839 'page_title' => $this->mTitle->getDBkey(),
840 'page_counter' => 0,
841 'page_restrictions' => $restrictions,
842 'page_is_redirect' => 0, # Will set this shortly...
843 'page_is_new' => 1,
844 'page_random' => wfRandom(),
845 'page_touched' => $dbw->timestamp(),
846 'page_latest' => 0, # Fill this in shortly...
847 ), $fname );
848 $newid = $dbw->insertId();
849
850 $this->mTitle->resetArticleId( $newid );
851
852 wfProfileOut( $fname );
853 return $newid;
854 }
855
856 /**
857 * Update the page record to point to a newly saved revision.
858 *
859 * @param Database $dbw
860 * @param Revision $revision -- for ID number, and text used to set
861 length and redirect status fields
862 * @param int $lastRevision -- if given, will not overwrite the page field
863 * when different from the currently set value.
864 * Giving 0 indicates the new page flag should
865 * be set on.
866 * @return bool true on success, false on failure
867 * @access private
868 */
869 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
870 $fname = 'Article::updateToRevision';
871 wfProfileIn( $fname );
872
873 $conditions = array( 'page_id' => $this->getId() );
874 if( !is_null( $lastRevision ) ) {
875 # An extra check against threads stepping on each other
876 $conditions['page_latest'] = $lastRevision;
877 }
878 $text = $revision->getText();
879 $dbw->update( 'page',
880 array( /* SET */
881 'page_latest' => $revision->getId(),
882 'page_touched' => $dbw->timestamp(),
883 'page_is_new' => ($lastRevision === 0) ? 1 : 0,
884 'page_is_redirect' => Article::isRedirect( $text ),
885 'page_len' => strlen( $text ),
886 ),
887 $conditions,
888 $fname );
889
890 wfProfileOut( $fname );
891 return ( $dbw->affectedRows() != 0 );
892 }
893
894 /**
895 * If the given revision is newer than the currently set page_latest,
896 * update the page record. Otherwise, do nothing.
897 *
898 * @param Database $dbw
899 * @param Revision $revision
900 */
901 function updateIfNewerOn( &$dbw, $revision ) {
902 $fname = 'Article::updateIfNewerOn';
903 wfProfileIn( $fname );
904
905 $row = $dbw->selectRow(
906 array( 'revision', 'page' ),
907 array( 'rev_id', 'rev_timestamp' ),
908 array(
909 'page_id' => $this->getId(),
910 'page_latest=rev_id' ),
911 $fname );
912 if( $row ) {
913 if( $row->rev_timestamp >= $revision->getTimestamp() ) {
914 wfProfileOut( $fname );
915 return false;
916 }
917 $prev = $row->rev_id;
918 } else {
919 # No or missing previous revision; mark the page as new
920 $prev = 0;
921 }
922
923 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
924 wfProfileOut( $fname );
925 return $ret;
926 }
927
928 /**
929 * Theoretically we could defer these whole insert and update
930 * functions for after display, but that's taking a big leap
931 * of faith, and we want to be able to report database
932 * errors at some point.
933 * @private
934 */
935 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false ) {
936 global $wgOut, $wgUser;
937 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
938
939 $fname = 'Article::insertNewArticle';
940
941 $this->mGoodAdjustment = $this->isCountable( $text );
942 $this->mTotalAdjustment = 1;
943
944 $ns = $this->mTitle->getNamespace();
945 $ttl = $this->mTitle->getDBkey();
946 $text = $this->preSaveTransform( $text );
947 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ? 1 : 0;
948 $now = wfTimestampNow();
949
950 $dbw =& wfGetDB( DB_MASTER );
951
952 # Add the page record; stake our claim on this title!
953 $newid = $this->insertOn( $dbw );
954
955 # Save the revision text...
956 $revision = new Revision( array(
957 'page' => $newid,
958 'comment' => $summary,
959 'minor_edit' => $isminor,
960 'text' => $text
961 ) );
962 $revisionId = $revision->insertOn( $dbw );
963
964 $this->mTitle->resetArticleID( $newid );
965
966 # Update the page record with revision data
967 $this->updateRevisionOn( $dbw, $revision, 0 );
968
969 Article::onArticleCreate( $this->mTitle );
970 if(!$suppressRC) {
971 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, 'default',
972 '', strlen( $text ), $revisionId );
973 }
974
975 if ($watchthis) {
976 if(!$this->mTitle->userIsWatching()) $this->watch();
977 } else {
978 if ( $this->mTitle->userIsWatching() ) {
979 $this->unwatch();
980 }
981 }
982
983 # The talk page isn't in the regular link tables, so we need to update manually:
984 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
985 $dbw->update( 'page',
986 array( 'page_touched' => $dbw->timestamp($now) ),
987 array( 'page_namespace' => $talkns,
988 'page_title' => $ttl ),
989 $fname );
990
991 # standard deferred updates
992 $this->editUpdates( $text, $summary, $isminor, $now );
993
994 $oldid = 0; # new article
995 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
996 }
997
998 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
999 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
1000 if ($section != '') {
1001 if( is_null( $edittime ) ) {
1002 $rev = Revision::newFromTitle( $this->mTitle );
1003 } else {
1004 $dbw =& wfGetDB( DB_MASTER );
1005 $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
1006 }
1007 $oldtext = $rev->getText();
1008
1009 if($section=='new') {
1010 if($summary) $subject="== {$summary} ==\n\n";
1011 $text=$oldtext."\n\n".$subject.$text;
1012 } else {
1013
1014 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
1015 # comments to be stripped as well)
1016 $striparray=array();
1017 $parser=new Parser();
1018 $parser->mOutputType=OT_WIKI;
1019 $oldtext=$parser->strip($oldtext, $striparray, true);
1020
1021 # now that we can be sure that no pseudo-sections are in the source,
1022 # split it up
1023 # Unfortunately we can't simply do a preg_replace because that might
1024 # replace the wrong section, so we have to use the section counter instead
1025 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
1026 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
1027 $secs[$section*2]=$text."\n\n"; // replace with edited
1028
1029 # section 0 is top (intro) section
1030 if($section!=0) {
1031
1032 # headline of old section - we need to go through this section
1033 # to determine if there are any subsections that now need to
1034 # be erased, as the mother section has been replaced with
1035 # the text of all subsections.
1036 $headline=$secs[$section*2-1];
1037 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
1038 $hlevel=$matches[1];
1039
1040 # determine headline level for wikimarkup headings
1041 if(strpos($hlevel,'=')!==false) {
1042 $hlevel=strlen($hlevel);
1043 }
1044
1045 $secs[$section*2-1]=''; // erase old headline
1046 $count=$section+1;
1047 $break=false;
1048 while(!empty($secs[$count*2-1]) && !$break) {
1049
1050 $subheadline=$secs[$count*2-1];
1051 preg_match(
1052 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1053 $subhlevel=$matches[1];
1054 if(strpos($subhlevel,'=')!==false) {
1055 $subhlevel=strlen($subhlevel);
1056 }
1057 if($subhlevel > $hlevel) {
1058 // erase old subsections
1059 $secs[$count*2-1]='';
1060 $secs[$count*2]='';
1061 }
1062 if($subhlevel <= $hlevel) {
1063 $break=true;
1064 }
1065 $count++;
1066
1067 }
1068
1069 }
1070 $text=join('',$secs);
1071 # reinsert the stuff that we stripped out earlier
1072 $text=$parser->unstrip($text,$striparray);
1073 $text=$parser->unstripNoWiki($text,$striparray);
1074 }
1075
1076 }
1077 return $text;
1078 }
1079
1080 /**
1081 * Change an existing article. Puts the previous version back into the old table, updates RC
1082 * and all necessary caches, mostly via the deferred update array.
1083 *
1084 * It is possible to call this function from a command-line script, but note that you should
1085 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1086 */
1087 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1088 global $wgOut, $wgUser;
1089 global $wgDBtransactions, $wgMwRedir;
1090 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList;
1091
1092 $fname = 'Article::updateArticle';
1093 $good = true;
1094
1095 $isminor = ( $minor && $wgUser->isLoggedIn() );
1096 if ( $this->isRedirect( $text ) ) {
1097 # Remove all content but redirect
1098 # This could be done by reconstructing the redirect from a title given by
1099 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1100 # wants to see
1101 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1102 $redir = 1;
1103 $text = $m[1] . "\n";
1104 }
1105 }
1106 else { $redir = 0; }
1107
1108 $text = $this->preSaveTransform( $text );
1109 $dbw =& wfGetDB( DB_MASTER );
1110 $now = wfTimestampNow();
1111
1112 # Update article, but only if changed.
1113
1114 # It's important that we either rollback or complete, otherwise an attacker could
1115 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1116 # could conceivably have the same effect, especially if cur is locked for long periods.
1117 if( !$wgDBtransactions ) {
1118 $userAbort = ignore_user_abort( true );
1119 }
1120
1121 $oldtext = $this->getContent( true );
1122 $oldsize = strlen( $oldtext );
1123 $newsize = strlen( $text );
1124 $lastRevision = 0;
1125
1126 if ( 0 != strcmp( $text, $oldtext ) ) {
1127 $this->mGoodAdjustment = $this->isCountable( $text )
1128 - $this->isCountable( $oldtext );
1129 $this->mTotalAdjustment = 0;
1130 $now = wfTimestampNow();
1131
1132 $lastRevision = $dbw->selectField(
1133 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1134
1135 $revision = new Revision( array(
1136 'page' => $this->getId(),
1137 'comment' => $summary,
1138 'minor_edit' => $isminor,
1139 'text' => $text
1140 ) );
1141 $revisionId = $revision->insertOn( $dbw );
1142
1143 # Update page
1144 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1145
1146 if( !$ok ) {
1147 /* Belated edit conflict! Run away!! */
1148 $good = false;
1149 } else {
1150 # Update recentchanges and purge cache and whatnot
1151 $bot = (int)($wgUser->isBot() || $forceBot);
1152 RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
1153 $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
1154 $revisionId );
1155 Article::onArticleEdit( $this->mTitle );
1156 }
1157 }
1158
1159 if( !$wgDBtransactions ) {
1160 ignore_user_abort( $userAbort );
1161 }
1162
1163 if ( $good ) {
1164 if ($watchthis) {
1165 if (!$this->mTitle->userIsWatching()) $this->watch();
1166 } else {
1167 if ( $this->mTitle->userIsWatching() ) {
1168 $this->unwatch();
1169 }
1170 }
1171 # standard deferred updates
1172 $this->editUpdates( $text, $summary, $minor, $now );
1173
1174
1175 $urls = array();
1176 # Template namespace
1177 # Purge all articles linking here
1178 if ( $this->mTitle->getNamespace() == NS_TEMPLATE) {
1179 $titles = $this->mTitle->getLinksTo();
1180 Title::touchArray( $titles );
1181 if ( $wgUseSquid ) {
1182 foreach ( $titles as $title ) {
1183 $urls[] = $title->getInternalURL();
1184 }
1185 }
1186 }
1187
1188 # Squid updates
1189 if ( $wgUseSquid ) {
1190 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
1191 $u = new SquidUpdate( $urls );
1192 array_push( $wgPostCommitUpdateList, $u );
1193 }
1194
1195 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $isminor, $now, $summary, $lastRevision );
1196 }
1197 return $good;
1198 }
1199
1200 /**
1201 * After we've either updated or inserted the article, update
1202 * the link tables and redirect to the new page.
1203 */
1204 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1205 global $wgUseDumbLinkUpdate, $wgAntiLockFlags, $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1206 global $wgUseEnotif;
1207
1208 $wgLinkCache = new LinkCache();
1209
1210 if ( !$wgUseDumbLinkUpdate ) {
1211 # Preload links to reduce lock time
1212 if ( $wgAntiLockFlags & ALF_PRELOAD_LINKS ) {
1213 $wgLinkCache->preFill( $this->mTitle );
1214 $wgLinkCache->clear();
1215 }
1216 }
1217
1218 # Parse the text and replace links with placeholders
1219 $wgOut = new OutputPage();
1220
1221 # Pass the current title along in case we're creating a wiki page
1222 # which is different than the currently displayed one (e.g. image
1223 # pages created on file uploads); otherwise, link updates will
1224 # go wrong.
1225 $wgOut->addWikiTextWithTitle( $text, $this->mTitle );
1226
1227 if ( !$wgUseDumbLinkUpdate ) {
1228 # Move the current links back to the second register
1229 $wgLinkCache->swapRegisters();
1230
1231 # Get old version of link table to allow incremental link updates
1232 # Lock this data now since it is needed for an update
1233 $wgLinkCache->forUpdate( true );
1234 $wgLinkCache->preFill( $this->mTitle );
1235
1236 # Swap this old version back into its rightful place
1237 $wgLinkCache->swapRegisters();
1238 }
1239
1240 if( $this->isRedirect( $text ) )
1241 $r = 'redirect=no';
1242 else
1243 $r = '';
1244 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1245
1246 if ( $wgUseEnotif ) {
1247 # this would be better as an extension hook
1248 include_once( "UserMailer.php" );
1249 $wgEnotif = new EmailNotification ();
1250 $wgEnotif->notifyOnPageChange( $this->mTitle, $now, $summary, $me2, $oldid );
1251 }
1252 }
1253
1254 /**
1255 * Mark this particular edit as patrolled
1256 */
1257 function markpatrolled() {
1258 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1259 $wgOut->setRobotpolicy( 'noindex,follow' );
1260
1261 if ( !$wgUseRCPatrol )
1262 {
1263 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1264 return;
1265 }
1266 if ( $wgUser->isAnon() )
1267 {
1268 $wgOut->loginToUse();
1269 return;
1270 }
1271 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1272 {
1273 $wgOut->sysopRequired();
1274 return;
1275 }
1276 $rcid = $wgRequest->getVal( 'rcid' );
1277 if ( !is_null ( $rcid ) )
1278 {
1279 RecentChange::markPatrolled( $rcid );
1280 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1281 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1282
1283 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1284 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1285 }
1286 else
1287 {
1288 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1289 }
1290 }
1291
1292 /**
1293 * Validate function
1294 */
1295 function validate() {
1296 global $wgOut, $wgUser, $wgRequest, $wgUseValidation;
1297
1298 if ( !$wgUseValidation ) # Are we using article validation at all?
1299 {
1300 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
1301 return ;
1302 }
1303
1304 $wgOut->setRobotpolicy( 'noindex,follow' );
1305 $revision = $wgRequest->getVal( 'revision' );
1306
1307 include_once ( "SpecialValidate.php" ) ; # The "Validation" class
1308
1309 $v = new Validation ;
1310 if ( $wgRequest->getVal ( "mode" , "" ) == "list" )
1311 $t = $v->showList ( $this ) ;
1312 else if ( $wgRequest->getVal ( "mode" , "" ) == "details" )
1313 $t = $v->showDetails ( $this , $wgRequest->getVal( 'revision' ) ) ;
1314 else
1315 $t = $v->validatePageForm ( $this , $revision ) ;
1316
1317 $wgOut->addHTML ( $t ) ;
1318 }
1319
1320 /**
1321 * Add this page to $wgUser's watchlist
1322 */
1323
1324 function watch() {
1325
1326 global $wgUser, $wgOut;
1327
1328 if ( $wgUser->isAnon() ) {
1329 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1330 return;
1331 }
1332 if ( wfReadOnly() ) {
1333 $wgOut->readOnlyPage();
1334 return;
1335 }
1336
1337 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1338
1339 $wgUser->addWatch( $this->mTitle );
1340 $wgUser->saveSettings();
1341
1342 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1343
1344 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1345 $wgOut->setRobotpolicy( 'noindex,follow' );
1346
1347 $link = $this->mTitle->getPrefixedText();
1348 $text = wfMsg( 'addedwatchtext', $link );
1349 $wgOut->addWikiText( $text );
1350 }
1351
1352 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1353 }
1354
1355 /**
1356 * Stop watching a page
1357 */
1358
1359 function unwatch() {
1360
1361 global $wgUser, $wgOut;
1362
1363 if ( $wgUser->isAnon() ) {
1364 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1365 return;
1366 }
1367 if ( wfReadOnly() ) {
1368 $wgOut->readOnlyPage();
1369 return;
1370 }
1371
1372 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1373
1374 $wgUser->removeWatch( $this->mTitle );
1375 $wgUser->saveSettings();
1376
1377 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1378
1379 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1380 $wgOut->setRobotpolicy( 'noindex,follow' );
1381
1382 $link = $this->mTitle->getPrefixedText();
1383 $text = wfMsg( 'removedwatchtext', $link );
1384 $wgOut->addWikiText( $text );
1385 }
1386
1387 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1388 }
1389
1390 /**
1391 * protect a page
1392 */
1393 function protect( $limit = 'sysop' ) {
1394 global $wgUser, $wgOut, $wgRequest;
1395
1396 if ( ! $wgUser->isAllowed('protect') ) {
1397 $wgOut->sysopRequired();
1398 return;
1399 }
1400 if ( wfReadOnly() ) {
1401 $wgOut->readOnlyPage();
1402 return;
1403 }
1404 $id = $this->mTitle->getArticleID();
1405 if ( 0 == $id ) {
1406 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1407 return;
1408 }
1409
1410 $confirm = $wgRequest->wasPosted() &&
1411 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1412 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1413 $reason = $wgRequest->getText( 'wpReasonProtect' );
1414
1415 if ( $confirm ) {
1416 $dbw =& wfGetDB( DB_MASTER );
1417 $dbw->update( 'page',
1418 array( /* SET */
1419 'page_touched' => $dbw->timestamp(),
1420 'page_restrictions' => (string)$limit
1421 ), array( /* WHERE */
1422 'page_id' => $id
1423 ), 'Article::protect'
1424 );
1425
1426 $restrictions = "move=" . $limit;
1427 if( !$moveonly ) {
1428 $restrictions .= ":edit=" . $limit;
1429 }
1430 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1431
1432 $dbw =& wfGetDB( DB_MASTER );
1433 $dbw->update( 'page',
1434 array( /* SET */
1435 'page_touched' => $dbw->timestamp(),
1436 'page_restrictions' => $restrictions
1437 ), array( /* WHERE */
1438 'page_id' => $id
1439 ), 'Article::protect'
1440 );
1441
1442 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1443
1444 $log = new LogPage( 'protect' );
1445 if ( $limit === '' ) {
1446 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1447 } else {
1448 $log->addEntry( 'protect', $this->mTitle, $reason );
1449 }
1450 $wgOut->redirect( $this->mTitle->getFullURL() );
1451 }
1452 return;
1453 } else {
1454 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1455 return $this->confirmProtect( '', $reason, $limit );
1456 }
1457 }
1458
1459 /**
1460 * Output protection confirmation dialog
1461 */
1462 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1463 global $wgOut, $wgUser;
1464
1465 wfDebug( "Article::confirmProtect\n" );
1466
1467 $sub = $this->mTitle->getPrefixedText();
1468 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1469
1470 $check = '';
1471 $protcom = '';
1472 $moveonly = '';
1473
1474 if ( $limit === '' ) {
1475 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1476 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1477 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1478 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1479 $formaction = $this->mTitle->escapeLocalURL( 'action=unprotect' . $par );
1480 } else {
1481 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1482 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1483 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1484 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1485 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1486 $formaction = $this->mTitle->escapeLocalURL( 'action=protect' . $par );
1487 }
1488
1489 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1490 $token = htmlspecialchars( $wgUser->editToken() );
1491
1492 $wgOut->addHTML( "
1493 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1494 <table border='0'>
1495 <tr>
1496 <td align='right'>
1497 <label for='wpReasonProtect'>{$protcom}:</label>
1498 </td>
1499 <td align='left'>
1500 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1501 </td>
1502 </tr>" );
1503 if($moveonly != '') {
1504 $wgOut->AddHTML( "
1505 <tr>
1506 <td align='right'>
1507 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1508 </td>
1509 <td align='left'>
1510 <label for='wpMoveOnly'>{$moveonly}</label>
1511 </td>
1512 </tr> " );
1513 }
1514 $wgOut->addHTML( "
1515 <tr>
1516 <td>&nbsp;</td>
1517 <td>
1518 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1519 </td>
1520 </tr>
1521 </table>
1522 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1523 </form>" );
1524
1525 $wgOut->returnToMain( false );
1526 }
1527
1528 /**
1529 * Unprotect the pages
1530 */
1531 function unprotect() {
1532 return $this->protect( '' );
1533 }
1534
1535 /*
1536 * UI entry point for page deletion
1537 */
1538 function delete() {
1539 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1540 $fname = 'Article::delete';
1541 $confirm = $wgRequest->wasPosted() &&
1542 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1543 $reason = $wgRequest->getText( 'wpReason' );
1544
1545 # This code desperately needs to be totally rewritten
1546
1547 # Check permissions
1548 if( ( !$wgUser->isAllowed( 'delete' ) ) ) {
1549 $wgOut->sysopRequired();
1550 return;
1551 }
1552 if( wfReadOnly() ) {
1553 $wgOut->readOnlyPage();
1554 return;
1555 }
1556
1557 # Better double-check that it hasn't been deleted yet!
1558 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1559 if( !$this->mTitle->exists() ) {
1560 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1561 return;
1562 }
1563
1564 if( $confirm ) {
1565 $this->doDelete( $reason );
1566 return;
1567 }
1568
1569 # determine whether this page has earlier revisions
1570 # and insert a warning if it does
1571 # we select the text because it might be useful below
1572 $dbr =& $this->getDB();
1573 $ns = $this->mTitle->getNamespace();
1574 $title = $this->mTitle->getDBkey();
1575 $revisions = $dbr->select( array( 'page', 'revision' ),
1576 array( 'rev_id', 'rev_user_text' ),
1577 array(
1578 'page_namespace' => $ns,
1579 'page_title' => $title,
1580 'rev_page = page_id'
1581 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1582 );
1583
1584 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1585 $skin=$wgUser->getSkin();
1586 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1587 $wgOut->addHTML( $skin->historyLink() .'</b>');
1588 }
1589
1590 # Fetch cur_text
1591 $rev =& Revision::newFromTitle( $this->mTitle );
1592
1593 # Fetch name(s) of contributors
1594 $rev_name = '';
1595 $all_same_user = true;
1596 while( $row = $dbr->fetchObject( $revisions ) ) {
1597 if( $rev_name != '' && $rev_name != $row->rev_user_text ) {
1598 $all_same_user = false;
1599 } else {
1600 $rev_name = $row->rev_user_text;
1601 }
1602 }
1603
1604 if( !is_null( $rev ) ) {
1605 # if this is a mini-text, we can paste part of it into the deletion reason
1606 $text = $rev->getText();
1607
1608 #if this is empty, an earlier revision may contain "useful" text
1609 $blanked = false;
1610 if( $text == '' ) {
1611 $prev = $rev->getPrevious();
1612 if( $prev ) {
1613 $text = $prev->getText();
1614 $blanked = true;
1615 }
1616 }
1617
1618 $length = strlen( $text );
1619
1620 # this should not happen, since it is not possible to store an empty, new
1621 # page. Let's insert a standard text in case it does, though
1622 if( $length == 0 && $reason === '' ) {
1623 $reason = wfMsg( 'exblank' );
1624 }
1625
1626 if( $length < 500 && $reason === '' ) {
1627 # comment field=255, let's grep the first 150 to have some user
1628 # space left
1629 global $wgContLang;
1630 $text = $wgContLang->truncate( $text, 150, '...' );
1631
1632 # let's strip out newlines
1633 $text = preg_replace( "/[\n\r]/", '', $text );
1634
1635 if( !$blanked ) {
1636 if( !$all_same_user ) {
1637 $reason = wfMsg( 'excontent', $text );
1638 } else {
1639 $reason = wfMsg( 'excontentauthor', $text, $rev_name );
1640 }
1641 } else {
1642 $reason = wfMsg( 'exbeforeblank', $text );
1643 }
1644 }
1645 }
1646
1647 return $this->confirmDelete( '', $reason );
1648 }
1649
1650 /**
1651 * Output deletion confirmation dialog
1652 */
1653 function confirmDelete( $par, $reason ) {
1654 global $wgOut, $wgUser;
1655
1656 wfDebug( "Article::confirmDelete\n" );
1657
1658 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1659 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1660 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1661 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1662
1663 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1664
1665 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1666 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1667 $token = htmlspecialchars( $wgUser->editToken() );
1668
1669 $wgOut->addHTML( "
1670 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1671 <table border='0'>
1672 <tr>
1673 <td align='right'>
1674 <label for='wpReason'>{$delcom}:</label>
1675 </td>
1676 <td align='left'>
1677 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1678 </td>
1679 </tr>
1680 <tr>
1681 <td>&nbsp;</td>
1682 <td>
1683 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1684 </td>
1685 </tr>
1686 </table>
1687 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1688 </form>\n" );
1689
1690 $wgOut->returnToMain( false );
1691 }
1692
1693
1694 /**
1695 * Perform a deletion and output success or failure messages
1696 */
1697 function doDelete( $reason ) {
1698 global $wgOut, $wgUser, $wgContLang;
1699 $fname = 'Article::doDelete';
1700 wfDebug( $fname."\n" );
1701
1702 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1703 if ( $this->doDeleteArticle( $reason ) ) {
1704 $deleted = $this->mTitle->getPrefixedText();
1705
1706 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1707 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1708
1709 $loglink = '[[Special:Log/delete|' . wfMsg( 'deletionlog' ) . ']]';
1710 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1711
1712 $wgOut->addWikiText( $text );
1713 $wgOut->returnToMain( false );
1714 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1715 } else {
1716 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1717 }
1718 }
1719 }
1720
1721 /**
1722 * Back-end article deletion
1723 * Deletes the article with database consistency, writes logs, purges caches
1724 * Returns success
1725 */
1726 function doDeleteArticle( $reason ) {
1727 global $wgUser;
1728 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1729
1730 $fname = 'Article::doDeleteArticle';
1731 wfDebug( $fname."\n" );
1732
1733 $dbw =& wfGetDB( DB_MASTER );
1734 $ns = $this->mTitle->getNamespace();
1735 $t = $this->mTitle->getDBkey();
1736 $id = $this->mTitle->getArticleID();
1737
1738 if ( $t == '' || $id == 0 ) {
1739 return false;
1740 }
1741
1742 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ), -1 );
1743 array_push( $wgDeferredUpdateList, $u );
1744
1745 $linksTo = $this->mTitle->getLinksTo();
1746
1747 # Squid purging
1748 if ( $wgUseSquid ) {
1749 $urls = array(
1750 $this->mTitle->getInternalURL(),
1751 $this->mTitle->getInternalURL( 'history' )
1752 );
1753
1754 $u = SquidUpdate::newFromTitles( $linksTo, $urls );
1755 array_push( $wgPostCommitUpdateList, $u );
1756
1757 }
1758
1759 # Client and file cache invalidation
1760 Title::touchArray( $linksTo );
1761
1762
1763 // For now, shunt the revision data into the archive table.
1764 // Text is *not* removed from the text table; bulk storage
1765 // is left intact to avoid breaking block-compression or
1766 // immutable storage schemes.
1767 //
1768 // For backwards compatibility, note that some older archive
1769 // table entries will have ar_text and ar_flags fields still.
1770 //
1771 // In the future, we may keep revisions and mark them with
1772 // the rev_deleted field, which is reserved for this purpose.
1773 $dbw->insertSelect( 'archive', array( 'page', 'revision' ),
1774 array(
1775 'ar_namespace' => 'page_namespace',
1776 'ar_title' => 'page_title',
1777 'ar_comment' => 'rev_comment',
1778 'ar_user' => 'rev_user',
1779 'ar_user_text' => 'rev_user_text',
1780 'ar_timestamp' => 'rev_timestamp',
1781 'ar_minor_edit' => 'rev_minor_edit',
1782 'ar_rev_id' => 'rev_id',
1783 'ar_text_id' => 'rev_text_id',
1784 ), array(
1785 'page_id' => $id,
1786 'page_id = rev_page'
1787 ), $fname
1788 );
1789
1790 # Now that it's safely backed up, delete it
1791 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1792 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1793
1794 # Clean up recentchanges entries...
1795 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1796
1797 # Finally, clean up the link tables
1798 $t = $this->mTitle->getPrefixedDBkey();
1799
1800 Article::onArticleDelete( $this->mTitle );
1801
1802 # Delete outgoing links
1803 $dbw->delete( 'pagelinks', array( 'pl_from' => $id ) );
1804 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1805 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1806
1807 # Log the deletion
1808 $log = new LogPage( 'delete' );
1809 $log->addEntry( 'delete', $this->mTitle, $reason );
1810
1811 # Clear the cached article id so the interface doesn't act like we exist
1812 $this->mTitle->resetArticleID( 0 );
1813 $this->mTitle->mArticleID = 0;
1814 return true;
1815 }
1816
1817 /**
1818 * Revert a modification
1819 */
1820 function rollback() {
1821 global $wgUser, $wgOut, $wgRequest;
1822 $fname = 'Article::rollback';
1823
1824 if ( ! $wgUser->isAllowed('rollback') ) {
1825 $wgOut->sysopRequired();
1826 return;
1827 }
1828 if ( wfReadOnly() ) {
1829 $wgOut->readOnlyPage( $this->getContent( true ) );
1830 return;
1831 }
1832 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1833 array( $this->mTitle->getPrefixedText(),
1834 $wgRequest->getVal( 'from' ) ) ) ) {
1835 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1836 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1837 return;
1838 }
1839 $dbw =& wfGetDB( DB_MASTER );
1840
1841 # Enhanced rollback, marks edits rc_bot=1
1842 $bot = $wgRequest->getBool( 'bot' );
1843
1844 # Replace all this user's current edits with the next one down
1845 $tt = $this->mTitle->getDBKey();
1846 $n = $this->mTitle->getNamespace();
1847
1848 # Get the last editor, lock table exclusively
1849 $dbw->begin();
1850 $current = Revision::newFromTitle( $this->mTitle );
1851 if( is_null( $current ) ) {
1852 # Something wrong... no page?
1853 $dbw->rollback();
1854 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1855 return;
1856 }
1857
1858 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1859 if( $from != $current->getUserText() ) {
1860 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1861 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1862 htmlspecialchars( $this->mTitle->getPrefixedText()),
1863 htmlspecialchars( $from ),
1864 htmlspecialchars( $current->getUserText() ) ) );
1865 if( $current->getComment() != '') {
1866 $wgOut->addHTML(
1867 wfMsg( 'editcomment',
1868 htmlspecialchars( $current->getComment() ) ) );
1869 }
1870 return;
1871 }
1872
1873 # Get the last edit not by this guy
1874 $user = IntVal( $current->getUser() );
1875 $user_text = $dbw->addQuotes( $current->getUserText() );
1876 $s = $dbw->selectRow( 'revision',
1877 array( 'rev_id', 'rev_timestamp' ),
1878 array(
1879 'rev_page' => $current->getPage(),
1880 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
1881 ), $fname,
1882 array(
1883 'USE INDEX' => 'page_timestamp',
1884 'ORDER BY' => 'rev_timestamp DESC' )
1885 );
1886 if( $s === false ) {
1887 # Something wrong
1888 $dbw->rollback();
1889 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1890 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1891 return;
1892 }
1893
1894 if ( $bot ) {
1895 # Mark all reverted edits as bot
1896 $dbw->update( 'recentchanges',
1897 array( /* SET */
1898 'rc_bot' => 1
1899 ), array( /* WHERE */
1900 'rc_cur_id' => $current->getPage(),
1901 'rc_user_text' => $current->getUserText(),
1902 "rc_timestamp > '{$s->rev_timestamp}'",
1903 ), $fname
1904 );
1905 }
1906
1907 # Save it!
1908 $target = Revision::newFromId( $s->rev_id );
1909 $newcomment = wfMsg( 'revertpage', $target->getUserText(), $from );
1910
1911 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1912 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1913 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1914
1915 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle->userIsWatching(), $bot );
1916 Article::onArticleEdit( $this->mTitle );
1917
1918 $dbw->commit();
1919 $wgOut->returnToMain( false );
1920 }
1921
1922
1923 /**
1924 * Do standard deferred updates after page view
1925 * @private
1926 */
1927 function viewUpdates() {
1928 global $wgDeferredUpdateList, $wgUseEnotif;
1929
1930 if ( 0 != $this->getID() ) {
1931 global $wgDisableCounters;
1932 if( !$wgDisableCounters ) {
1933 Article::incViewCount( $this->getID() );
1934 $u = new SiteStatsUpdate( 1, 0, 0 );
1935 array_push( $wgDeferredUpdateList, $u );
1936 }
1937 }
1938
1939 # Update newtalk status if user is reading their own
1940 # talk page
1941
1942 global $wgUser;
1943 if ($this->mTitle->getNamespace() == NS_USER_TALK &&
1944 $this->mTitle->getText() == $wgUser->getName())
1945 {
1946 if ( $wgUseEnotif ) {
1947 require_once( 'UserTalkUpdate.php' );
1948 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(), $this->mTitle->getDBkey(), false, false, false );
1949 } else {
1950 $wgUser->setNewtalk(0);
1951 $wgUser->saveNewtalk();
1952 }
1953 } elseif ( $wgUseEnotif ) {
1954 $wgUser->clearNotification( $this->mTitle );
1955 }
1956
1957 }
1958
1959 /**
1960 * Do standard deferred updates after page edit.
1961 * Every 1000th edit, prune the recent changes table.
1962 * @private
1963 * @param string $text
1964 */
1965 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1966 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1967 global $wgMessageCache, $wgUser, $wgUseEnotif;
1968
1969 wfSeedRandom();
1970 if ( 0 == mt_rand( 0, 999 ) ) {
1971 # Periodically flush old entries from the recentchanges table.
1972 global $wgRCMaxAge;
1973 $dbw =& wfGetDB( DB_MASTER );
1974 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1975 $recentchanges = $dbw->tableName( 'recentchanges' );
1976 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
1977 $dbw->query( $sql );
1978 }
1979 $id = $this->getID();
1980 $title = $this->mTitle->getPrefixedDBkey();
1981 $shortTitle = $this->mTitle->getDBkey();
1982
1983 if ( 0 != $id ) {
1984 $u = new LinksUpdate( $id, $title );
1985 array_push( $wgDeferredUpdateList, $u );
1986 $u = new SiteStatsUpdate( 0, 1, $this->mGoodAdjustment, $this->mTotalAdjustment );
1987 array_push( $wgDeferredUpdateList, $u );
1988 $u = new SearchUpdate( $id, $title, $text );
1989 array_push( $wgDeferredUpdateList, $u );
1990
1991 # If this is another user's talk page, update newtalk
1992
1993 if ($this->mTitle->getNamespace() == NS_USER_TALK && $shortTitle != $wgUser->getName()) {
1994 if ( $wgUseEnotif ) {
1995 require_once( 'UserTalkUpdate.php' );
1996 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle, $summary,
1997 $minoredit, $timestamp_of_pagechange);
1998 } else {
1999 $other = User::newFromName($shortTitle);
2000 if ($other) {
2001 $other->setNewtalk(1);
2002 $other->saveNewtalk();
2003 }
2004 }
2005 }
2006
2007 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
2008 $wgMessageCache->replace( $shortTitle, $text );
2009 }
2010 }
2011 }
2012
2013 /**
2014 * @todo document this function
2015 * @private
2016 * @param string $oldid Revision ID of this article revision
2017 */
2018 function setOldSubtitle( $oldid=0 ) {
2019 global $wgLang, $wgOut, $wgUser;
2020
2021 $current = ( $oldid == $this->mLatest );
2022 $td = $wgLang->timeanddate( $this->mTimestamp, true );
2023 $sk = $wgUser->getSkin();
2024 $lnk = $current
2025 ? wfMsg( 'currentrevisionlink' )
2026 : $lnk = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
2027 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
2028 $nextlink = $current
2029 ? wfMsg( 'nextrevision' )
2030 : $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 ?>