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