Decouple revision.rev_id from text.old_id
[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 = false;
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 $de = new DifferenceEngine( $oldid, $diff, $rcid );
650 $de->showDiffPage();
651 if( $diff == 0 ) {
652 # Run view updates for current revision only
653 $this->viewUpdates();
654 }
655 wfProfileOut( $fname );
656 return;
657 }
658 if ( empty( $oldid ) && $this->checkTouched() ) {
659 if( $wgOut->checkLastModified( $this->mTouched ) ){
660 wfProfileOut( $fname );
661 return;
662 } else if ( $this->tryFileCache() ) {
663 # tell wgOut that output is taken care of
664 $wgOut->disable();
665 $this->viewUpdates();
666 wfProfileOut( $fname );
667 return;
668 }
669 }
670 # Should the parser cache be used?
671 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
672 $pcache = true;
673 } else {
674 $pcache = false;
675 }
676
677 $outputDone = false;
678 if ( $pcache ) {
679 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
680 $outputDone = true;
681 }
682 }
683 if ( !$outputDone ) {
684 $text = $this->getContent( false ); # May change mTitle by following a redirect
685
686 # Another whitelist check in case oldid or redirects are altering the title
687 if ( !$this->mTitle->userCanRead() ) {
688 $wgOut->loginToUse();
689 $wgOut->output();
690 exit;
691 }
692
693
694 # We're looking at an old revision
695
696 if ( !empty( $oldid ) ) {
697 $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
698 $wgOut->setRobotpolicy( 'noindex,follow' );
699 }
700 if ( '' != $this->mRedirectedFrom ) {
701 $sk = $wgUser->getSkin();
702 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, '',
703 'redirect=no' );
704 $s = wfMsg( 'redirectedfrom', $redir );
705 $wgOut->setSubtitle( $s );
706
707 # Can't cache redirects
708 $pcache = false;
709 } elseif ( !empty( $rdfrom ) ) {
710 global $wgRedirectSources;
711 if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
712 $sk = $wgUser->getSkin();
713 $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
714 $s = wfMsg( 'redirectedfrom', $redir );
715 $wgOut->setSubtitle( $s );
716 }
717 }
718
719 # wrap user css and user js in pre and don't parse
720 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
721 if (
722 $this->mTitle->getNamespace() == NS_USER &&
723 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
724 ) {
725 $wgOut->addWikiText( wfMsg('clearyourcache'));
726 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
727 } else if ( $rt = Title::newFromRedirect( $text ) ) {
728 # Display redirect
729 $imageUrl = $wgStylePath.'/common/images/redirect.png';
730 $targetUrl = $rt->escapeLocalURL();
731 $titleText = htmlspecialchars( $rt->getPrefixedText() );
732 $link = $sk->makeLinkObj( $rt );
733
734 $wgOut->addHTML( '<img valign="center" src="'.$imageUrl.'" alt="#REDIRECT" />' .
735 '<span class="redirectText">'.$link.'</span>' );
736
737 $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
738 $catlinks = $parseout->getCategoryLinks();
739 $wgOut->addCategoryLinks($catlinks);
740 $skin = $wgUser->getSkin();
741 } else if ( $pcache ) {
742 # Display content and save to parser cache
743 $wgOut->addPrimaryWikiText( $text, $this );
744 } else {
745 # Display content, don't attempt to save to parser cache
746 $wgOut->addWikiText( $text );
747 }
748 }
749 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
750 # If we have been passed an &rcid= parameter, we want to give the user a
751 # chance to mark this new article as patrolled.
752 if ( $wgUseRCPatrol && !is_null ( $rcid ) && $rcid != 0 && $wgUser->isLoggedIn() &&
753 ( $wgUser->isAllowed('patrol') || !$wgOnlySysopsCanPatrol ) )
754 {
755 $wgOut->addHTML( wfMsg ( 'markaspatrolledlink',
756 $sk->makeKnownLinkObj ( $this->mTitle, wfMsg ( 'markaspatrolledtext' ),
757 'action=markpatrolled&rcid='.$rcid )
758 ) );
759 }
760
761 # Put link titles into the link cache
762 $wgOut->transformBuffer();
763
764 # Add link titles as META keywords
765 $wgOut->addMetaTags() ;
766
767 $this->viewUpdates();
768 wfProfileOut( $fname );
769 }
770
771 /**
772 * Insert a new empty page record for this article.
773 * This *must* be followed up by creating a revision
774 * and running $this->updateToLatest( $rev_id );
775 * or else the record will be left in a funky state.
776 * Best if all done inside a transaction.
777 *
778 * @param Database $dbw
779 * @param string $restrictions
780 * @return int The newly created page_id key
781 * @access private
782 */
783 function insertOn( &$dbw, $restrictions = '' ) {
784 $fname = 'Article::insertOn';
785 wfProfileIn( $fname );
786
787 $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
788 $dbw->insert( 'page', array(
789 'page_id' => $page_id,
790 'page_namespace' => $this->mTitle->getNamespace(),
791 'page_title' => $this->mTitle->getDBkey(),
792 'page_counter' => 0,
793 'page_restrictions' => $restrictions,
794 'page_is_redirect' => 0, # Will set this shortly...
795 'page_is_new' => 1,
796 'page_random' => wfRandom(),
797 'page_touched' => $dbw->timestamp(),
798 'page_latest' => 0, # Fill this in shortly...
799 ), $fname );
800 $newid = $dbw->insertId();
801
802 $this->mTitle->resetArticleId( $newid );
803
804 wfProfileOut( $fname );
805 return $newid;
806 }
807
808 /**
809 * Update the page record to point to a newly saved revision.
810 *
811 * @param Database $dbw
812 * @param Revision $revision -- for ID number, and text used to set
813 length and redirect status fields
814 * @param int $lastRevision -- if given, will not overwrite the page field
815 * when different from the currently set value.
816 * Giving 0 indicates the new page flag should
817 * be set on.
818 * @return bool true on success, false on failure
819 * @access private
820 */
821 function updateRevisionOn( &$dbw, $revision, $lastRevision = null ) {
822 $fname = 'Article::updateToRevision';
823 wfProfileIn( $fname );
824
825 $conditions = array( 'page_id' => $this->getId() );
826 if( !is_null( $lastRevision ) ) {
827 # An extra check against threads stepping on each other
828 $conditions['page_latest'] = $lastRevision;
829 }
830 $text = $revision->getText();
831 $dbw->update( 'page',
832 array( /* SET */
833 'page_latest' => $revision->getId(),
834 'page_touched' => $dbw->timestamp(),
835 'page_is_new' => ($lastRevision === 0) ? 0 : 1,
836 'page_is_redirect' => Article::isRedirect( $text ),
837 'page_len' => strlen( $text ),
838 ),
839 $conditions,
840 $fname );
841
842 wfProfileOut( $fname );
843 return ( $dbw->affectedRows() != 0 );
844 }
845
846 /**
847 * If the given revision is newer than the currently set page_latest,
848 * update the page record. Otherwise, do nothing.
849 *
850 * @param Database $dbw
851 * @param Revision $revision
852 */
853 function updateIfNewerOn( &$dbw, $revision ) {
854 $fname = 'Article::updateIfNewerOn';
855 wfProfileIn( $fname );
856
857 $row = $dbw->selectRow(
858 array( 'revision', 'page' ),
859 array( 'rev_id', 'rev_timestamp' ),
860 array(
861 'page_id' => $this->getId(),
862 'page_latest=rev_id' ),
863 $fname );
864 if( $row ) {
865 if( $row->rev_timestamp >= $revision->getTimestamp() ) {
866 wfProfileOut( $fname );
867 return false;
868 }
869 $prev = $row->rev_id;
870 } else {
871 # No or missing previous revision; mark the page as new
872 $prev = 0;
873 }
874
875 $ret = $this->updateRevisionOn( $dbw, $revision, $prev );
876 wfProfileOut( $fname );
877 return $ret;
878 }
879
880 /**
881 * Theoretically we could defer these whole insert and update
882 * functions for after display, but that's taking a big leap
883 * of faith, and we want to be able to report database
884 * errors at some point.
885 * @private
886 */
887 function insertNewArticle( $text, $summary, $isminor, $watchthis, $suppressRC=false ) {
888 global $wgOut, $wgUser;
889 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
890
891 $fname = 'Article::insertNewArticle';
892
893 $this->mCountAdjustment = $this->isCountable( $text );
894
895 $ns = $this->mTitle->getNamespace();
896 $ttl = $this->mTitle->getDBkey();
897 $text = $this->preSaveTransform( $text );
898 $isminor = ( $isminor && $wgUser->isLoggedIn() ) ? 1 : 0;
899
900 $dbw =& wfGetDB( DB_MASTER );
901
902 # Add the page record; stake our claim on this title!
903 $newid = $this->insertOn( $dbw );
904
905 # Save the revision text...
906 $revision = new Revision( array(
907 'page' => $newid,
908 'comment' => $summary,
909 'minor_edit' => $isminor,
910 'text' => $text
911 ) );
912 $revisionId = $revision->insertOn( $dbw );
913
914 $this->mTitle->resetArticleID( $newid );
915
916 # Update the page record with revision data
917 $this->updateRevisionOn( $dbw, $revision, 0 );
918
919 Article::onArticleCreate( $this->mTitle );
920 if(!$suppressRC) {
921 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary );
922 }
923
924 if ($watchthis) {
925 if(!$this->mTitle->userIsWatching()) $this->watch();
926 } else {
927 if ( $this->mTitle->userIsWatching() ) {
928 $this->unwatch();
929 }
930 }
931
932 # The talk page isn't in the regular link tables, so we need to update manually:
933 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
934 $dbw->update( 'page',
935 array( 'page_touched' => $dbw->timestamp($now) ),
936 array( 'page_namespace' => $talkns,
937 'page_title' => $ttl ),
938 $fname );
939
940 # standard deferred updates
941 $this->editUpdates( $text, $summary, $isminor, $now );
942
943 $oldid = 0; # new article
944 $this->showArticle( $text, wfMsg( 'newarticle' ), false, $isminor, $now, $summary, $oldid );
945 }
946
947 /**
948 * Fetch and uncompress the text for a given revision.
949 * Can ask by rev_id number or timestamp (set $field)
950 */
951 function fetchRevisionText( $revId = null, $field = 'rev_id' ) {
952 $fname = 'Article::fetchRevisionText';
953 $dbw =& wfGetDB( DB_MASTER );
954 if( $revId ) {
955 $rev = $dbw->addQuotes( $revId );
956 } else {
957 $rev = 'page_latest';
958 }
959 $result = $dbw->query(
960 sprintf( "SELECT old_text, old_flags
961 FROM %s,%s,%s
962 WHERE old_id=rev_id AND rev_page=page_id AND page_id=%d
963 AND %s=%s",
964 $dbw->tableName( 'page' ),
965 $dbw->tableName( 'revision' ),
966 $dbw->tableName( 'text' ),
967 IntVal( $this->mTitle->getArticleId() ),
968 $field,
969 $rev ),
970 $fname );
971 $obj = $dbw->fetchObject( $result );
972 $dbw->freeResult( $result );
973 $oldtext = Revision::getRevisionText( $obj );
974 return $oldtext;
975 }
976
977 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = '', $edittime = NULL) {
978 $fname = 'Article::getTextOfLastEditWithSectionReplacedOrAdded';
979 if( is_null( $edittime ) ) {
980 $oldtext = $this->fetchRevisionText();
981 } else {
982 $oldtext = $this->fetchRevisionText( $edittime, 'rev_timestamp' );
983 }
984 if ($section != '') {
985 if($section=='new') {
986 if($summary) $subject="== {$summary} ==\n\n";
987 $text=$oldtext."\n\n".$subject.$text;
988 } else {
989
990 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
991 # comments to be stripped as well)
992 $striparray=array();
993 $parser=new Parser();
994 $parser->mOutputType=OT_WIKI;
995 $oldtext=$parser->strip($oldtext, $striparray, true);
996
997 # now that we can be sure that no pseudo-sections are in the source,
998 # split it up
999 # Unfortunately we can't simply do a preg_replace because that might
1000 # replace the wrong section, so we have to use the section counter instead
1001 $secs=preg_split('/(^=+.+?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)(?!\S)/mi',
1002 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
1003 $secs[$section*2]=$text."\n\n"; // replace with edited
1004
1005 # section 0 is top (intro) section
1006 if($section!=0) {
1007
1008 # headline of old section - we need to go through this section
1009 # to determine if there are any subsections that now need to
1010 # be erased, as the mother section has been replaced with
1011 # the text of all subsections.
1012 $headline=$secs[$section*2-1];
1013 preg_match( '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$headline,$matches);
1014 $hlevel=$matches[1];
1015
1016 # determine headline level for wikimarkup headings
1017 if(strpos($hlevel,'=')!==false) {
1018 $hlevel=strlen($hlevel);
1019 }
1020
1021 $secs[$section*2-1]=''; // erase old headline
1022 $count=$section+1;
1023 $break=false;
1024 while(!empty($secs[$count*2-1]) && !$break) {
1025
1026 $subheadline=$secs[$count*2-1];
1027 preg_match(
1028 '/^(=+).+?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>(?!\S)/mi',$subheadline,$matches);
1029 $subhlevel=$matches[1];
1030 if(strpos($subhlevel,'=')!==false) {
1031 $subhlevel=strlen($subhlevel);
1032 }
1033 if($subhlevel > $hlevel) {
1034 // erase old subsections
1035 $secs[$count*2-1]='';
1036 $secs[$count*2]='';
1037 }
1038 if($subhlevel <= $hlevel) {
1039 $break=true;
1040 }
1041 $count++;
1042
1043 }
1044
1045 }
1046 $text=join('',$secs);
1047 # reinsert the stuff that we stripped out earlier
1048 $text=$parser->unstrip($text,$striparray);
1049 $text=$parser->unstripNoWiki($text,$striparray);
1050 }
1051
1052 }
1053 return $text;
1054 }
1055
1056 /**
1057 * Change an existing article. Puts the previous version back into the old table, updates RC
1058 * and all necessary caches, mostly via the deferred update array.
1059 *
1060 * It is possible to call this function from a command-line script, but note that you should
1061 * first set $wgUser, and clean up $wgDeferredUpdates after each edit.
1062 */
1063 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' ) {
1064 global $wgOut, $wgUser;
1065 global $wgDBtransactions, $wgMwRedir;
1066 global $wgUseSquid, $wgInternalServer, $wgPostCommitUpdateList;
1067
1068 $fname = 'Article::updateArticle';
1069 $good = true;
1070
1071 $isminor = ( $minor && $wgUser->isLoggedIn() );
1072 if ( $this->isRedirect( $text ) ) {
1073 # Remove all content but redirect
1074 # This could be done by reconstructing the redirect from a title given by
1075 # Title::newFromRedirect(), but then we wouldn't know which synonym the user
1076 # wants to see
1077 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
1078 $redir = 1;
1079 $text = $m[1] . "\n";
1080 }
1081 }
1082 else { $redir = 0; }
1083
1084 $text = $this->preSaveTransform( $text );
1085 $dbw =& wfGetDB( DB_MASTER );
1086
1087 # Update article, but only if changed.
1088
1089 # It's important that we either rollback or complete, otherwise an attacker could
1090 # overwrite cur entries by sending precisely timed user aborts. Random bored users
1091 # could conceivably have the same effect, especially if cur is locked for long periods.
1092 if( !$wgDBtransactions ) {
1093 $userAbort = ignore_user_abort( true );
1094 }
1095
1096 $oldtext = $this->getContent( true );
1097
1098 if ( 0 != strcmp( $text, $oldtext ) ) {
1099 $this->mCountAdjustment = $this->isCountable( $text )
1100 - $this->isCountable( $oldtext );
1101 $now = wfTimestampNow();
1102
1103 $lastRevision = $dbw->selectField(
1104 'page', 'page_latest', array( 'page_id' => $this->getId() ) );
1105
1106 $revision = new Revision( array(
1107 'page' => $this->getId(),
1108 'comment' => $summary,
1109 'minor_edit' => $isminor,
1110 'text' => $text
1111 ) );
1112 $revisionId = $revision->insertOn( $dbw );
1113
1114 # Update page
1115 $ok = $this->updateRevisionOn( $dbw, $revision, $lastRevision );
1116
1117 if( !$ok ) {
1118 /* Belated edit conflict! Run away!! */
1119 $good = false;
1120 } else {
1121 # Update recentchanges and purge cache and whatnot
1122 $bot = (int)($wgUser->isBot() || $forceBot);
1123 RecentChange::notifyEdit( $now, $this->mTitle, $me2, $wgUser, $summary,
1124 $lastRevision, $this->getTimestamp(), $bot );
1125 Article::onArticleEdit( $this->mTitle );
1126 }
1127 }
1128
1129 if( !$wgDBtransactions ) {
1130 ignore_user_abort( $userAbort );
1131 }
1132
1133 if ( $good ) {
1134 if ($watchthis) {
1135 if (!$this->mTitle->userIsWatching()) $this->watch();
1136 } else {
1137 if ( $this->mTitle->userIsWatching() ) {
1138 $this->unwatch();
1139 }
1140 }
1141 # standard deferred updates
1142 $this->editUpdates( $text, $summary, $minor, $now );
1143
1144
1145 $urls = array();
1146 # Template namespace
1147 # Purge all articles linking here
1148 if ( $this->mTitle->getNamespace() == NS_TEMPLATE) {
1149 $titles = $this->mTitle->getLinksTo();
1150 Title::touchArray( $titles );
1151 if ( $wgUseSquid ) {
1152 foreach ( $titles as $title ) {
1153 $urls[] = $title->getInternalURL();
1154 }
1155 }
1156 }
1157
1158 # Squid updates
1159 if ( $wgUseSquid ) {
1160 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
1161 $u = new SquidUpdate( $urls );
1162 array_push( $wgPostCommitUpdateList, $u );
1163 }
1164
1165 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor, $me2, $now, $summary, $lastRevision );
1166 }
1167 return $good;
1168 }
1169
1170 /**
1171 * After we've either updated or inserted the article, update
1172 * the link tables and redirect to the new page.
1173 */
1174 function showArticle( $text, $subtitle , $sectionanchor = '', $me2, $now, $summary, $oldid ) {
1175 global $wgOut, $wgUser, $wgLinkCache, $wgEnotif;
1176
1177 $wgLinkCache = new LinkCache();
1178 # Select for update
1179 $wgLinkCache->forUpdate( true );
1180
1181 # Get old version of link table to allow incremental link updates
1182 $wgLinkCache->preFill( $this->mTitle );
1183 $wgLinkCache->clear();
1184
1185 # Parse the text and replace links with placeholders
1186 $wgOut = new OutputPage();
1187 $wgOut->addWikiText( $text );
1188
1189 # Look up the links in the DB and add them to the link cache
1190 $wgOut->transformBuffer( RLH_FOR_UPDATE );
1191
1192 if( $this->isRedirect( $text ) )
1193 $r = 'redirect=no';
1194 else
1195 $r = '';
1196 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1197
1198 # this call would better fit into RecentChange::notifyEdit and RecentChange::notifyNew .
1199 # this will be improved later (to-do)
1200
1201 include_once( "UserMailer.php" );
1202 $wgEnotif = new EmailNotification ();
1203 $wgEnotif->NotifyOnPageChange( $wgUser->getID(), $this->mTitle->getDBkey(), $this->mTitle->getNamespace(),$now, $summary, $me2, $oldid );
1204 }
1205
1206 /**
1207 * Mark this particular edit as patrolled
1208 */
1209 function markpatrolled() {
1210 global $wgOut, $wgRequest, $wgOnlySysopsCanPatrol, $wgUseRCPatrol, $wgUser;
1211 $wgOut->setRobotpolicy( 'noindex,follow' );
1212
1213 if ( !$wgUseRCPatrol )
1214 {
1215 $wgOut->errorpage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
1216 return;
1217 }
1218 if ( $wgUser->isAnon() )
1219 {
1220 $wgOut->loginToUse();
1221 return;
1222 }
1223 if ( $wgOnlySysopsCanPatrol && !$wgUser->isAllowed('patrol') )
1224 {
1225 $wgOut->sysopRequired();
1226 return;
1227 }
1228 $rcid = $wgRequest->getVal( 'rcid' );
1229 if ( !is_null ( $rcid ) )
1230 {
1231 RecentChange::markPatrolled( $rcid );
1232 $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
1233 $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
1234
1235 $rcTitle = Title::makeTitle( NS_SPECIAL, 'Recentchanges' );
1236 $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
1237 }
1238 else
1239 {
1240 $wgOut->errorpage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
1241 }
1242 }
1243
1244 /**
1245 * Validate function
1246 */
1247 function validate() {
1248 global $wgOut, $wgUser, $wgRequest, $wgUseValidation;
1249
1250 if ( !$wgUseValidation ) # Are we using article validation at all?
1251 {
1252 $wgOut->errorpage( "nosuchspecialpage", "nospecialpagetext" );
1253 return ;
1254 }
1255
1256 $wgOut->setRobotpolicy( 'noindex,follow' );
1257 $revision = $wgRequest->getVal( 'revision' );
1258
1259 include_once ( "SpecialValidate.php" ) ; # The "Validation" class
1260
1261 $v = new Validation ;
1262 if ( $wgRequest->getVal ( "mode" , "" ) == "list" )
1263 $t = $v->showList ( $this ) ;
1264 else
1265 $t = $v->validatePageForm ( $this , $revision ) ;
1266
1267 $wgOut->addHTML ( $t ) ;
1268 }
1269
1270 /**
1271 * Add this page to $wgUser's watchlist
1272 */
1273
1274 function watch() {
1275
1276 global $wgUser, $wgOut;
1277
1278 if ( $wgUser->isAnon() ) {
1279 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1280 return;
1281 }
1282 if ( wfReadOnly() ) {
1283 $wgOut->readOnlyPage();
1284 return;
1285 }
1286
1287 if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
1288
1289 $wgUser->addWatch( $this->mTitle );
1290 $wgUser->saveSettings();
1291
1292 wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
1293
1294 $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
1295 $wgOut->setRobotpolicy( 'noindex,follow' );
1296
1297 $link = $this->mTitle->getPrefixedText();
1298 $text = wfMsg( 'addedwatchtext', $link );
1299 $wgOut->addWikiText( $text );
1300 }
1301
1302 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1303 }
1304
1305 /**
1306 * Stop watching a page
1307 */
1308
1309 function unwatch() {
1310
1311 global $wgUser, $wgOut;
1312
1313 if ( $wgUser->isAnon() ) {
1314 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1315 return;
1316 }
1317 if ( wfReadOnly() ) {
1318 $wgOut->readOnlyPage();
1319 return;
1320 }
1321
1322 if (wfRunHooks('UnwatchArticle', array(&$wgUser, &$this))) {
1323
1324 $wgUser->removeWatch( $this->mTitle );
1325 $wgUser->saveSettings();
1326
1327 wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
1328
1329 $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
1330 $wgOut->setRobotpolicy( 'noindex,follow' );
1331
1332 $link = $this->mTitle->getPrefixedText();
1333 $text = wfMsg( 'removedwatchtext', $link );
1334 $wgOut->addWikiText( $text );
1335 }
1336
1337 $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
1338 }
1339
1340 /**
1341 * protect a page
1342 */
1343 function protect( $limit = 'sysop' ) {
1344 global $wgUser, $wgOut, $wgRequest;
1345
1346 if ( ! $wgUser->isAllowed('protect') ) {
1347 $wgOut->sysopRequired();
1348 return;
1349 }
1350 if ( wfReadOnly() ) {
1351 $wgOut->readOnlyPage();
1352 return;
1353 }
1354 $id = $this->mTitle->getArticleID();
1355 if ( 0 == $id ) {
1356 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1357 return;
1358 }
1359
1360 $confirm = $wgRequest->wasPosted() &&
1361 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1362 $moveonly = $wgRequest->getBool( 'wpMoveOnly' );
1363 $reason = $wgRequest->getText( 'wpReasonProtect' );
1364
1365 if ( $confirm ) {
1366 $dbw =& wfGetDB( DB_MASTER );
1367 $dbw->update( 'page',
1368 array( /* SET */
1369 'page_touched' => $dbw->timestamp(),
1370 'page_restrictions' => (string)$limit
1371 ), array( /* WHERE */
1372 'page_id' => $id
1373 ), 'Article::protect'
1374 );
1375
1376 $restrictions = "move=" . $limit;
1377 if( !$moveonly ) {
1378 $restrictions .= ":edit=" . $limit;
1379 }
1380 if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly))) {
1381
1382 $dbw =& wfGetDB( DB_MASTER );
1383 $dbw->update( 'page',
1384 array( /* SET */
1385 'page_touched' => $dbw->timestamp(),
1386 'page_restrictions' => $restrictions
1387 ), array( /* WHERE */
1388 'page_id' => $id
1389 ), 'Article::protect'
1390 );
1391
1392 wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit == 'sysop', $reason, $moveonly));
1393
1394 $log = new LogPage( 'protect' );
1395 if ( $limit === '' ) {
1396 $log->addEntry( 'unprotect', $this->mTitle, $reason );
1397 } else {
1398 $log->addEntry( 'protect', $this->mTitle, $reason );
1399 }
1400 $wgOut->redirect( $this->mTitle->getFullURL() );
1401 }
1402 return;
1403 } else {
1404 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1405 return $this->confirmProtect( '', $reason, $limit );
1406 }
1407 }
1408
1409 /**
1410 * Output protection confirmation dialog
1411 */
1412 function confirmProtect( $par, $reason, $limit = 'sysop' ) {
1413 global $wgOut, $wgUser;
1414
1415 wfDebug( "Article::confirmProtect\n" );
1416
1417 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1418 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1419
1420 $check = '';
1421 $protcom = '';
1422 $moveonly = '';
1423
1424 if ( $limit === '' ) {
1425 $wgOut->setPageTitle( wfMsg( 'confirmunprotect' ) );
1426 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1427 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1428 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1429 $formaction = $this->mTitle->escapeLocalURL( 'action=unprotect' . $par );
1430 } else {
1431 $wgOut->setPageTitle( wfMsg( 'confirmprotect' ) );
1432 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1433 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1434 $moveonly = htmlspecialchars( wfMsg( 'protectmoveonly' ) );
1435 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1436 $formaction = $this->mTitle->escapeLocalURL( 'action=protect' . $par );
1437 }
1438
1439 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1440 $token = htmlspecialchars( $wgUser->editToken() );
1441
1442 $wgOut->addHTML( "
1443 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1444 <table border='0'>
1445 <tr>
1446 <td align='right'>
1447 <label for='wpReasonProtect'>{$protcom}:</label>
1448 </td>
1449 <td align='left'>
1450 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1451 </td>
1452 </tr>" );
1453 if($moveonly != '') {
1454 $wgOut->AddHTML( "
1455 <tr>
1456 <td align='right'>
1457 <input type='checkbox' name='wpMoveOnly' value='1' id='wpMoveOnly' />
1458 </td>
1459 <td align='left'>
1460 <label for='wpMoveOnly'>{$moveonly}</label>
1461 </td>
1462 </tr> " );
1463 }
1464 $wgOut->addHTML( "
1465 <tr>
1466 <td>&nbsp;</td>
1467 <td>
1468 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1469 </td>
1470 </tr>
1471 </table>
1472 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1473 </form>" );
1474
1475 $wgOut->returnToMain( false );
1476 }
1477
1478 /**
1479 * Unprotect the pages
1480 */
1481 function unprotect() {
1482 return $this->protect( '' );
1483 }
1484
1485 /*
1486 * UI entry point for page deletion
1487 */
1488 function delete() {
1489 global $wgUser, $wgOut, $wgMessageCache, $wgRequest;
1490 $fname = 'Article::delete';
1491 $confirm = $wgRequest->wasPosted() &&
1492 $wgUser->matchEditToken( $wgRequest->getVal( 'wpEditToken' ) );
1493 $reason = $wgRequest->getText( 'wpReason' );
1494
1495 # This code desperately needs to be totally rewritten
1496
1497 # Check permissions
1498 if ( ( ! $wgUser->isAllowed('delete') ) ) {
1499 $wgOut->sysopRequired();
1500 return;
1501 }
1502 if ( wfReadOnly() ) {
1503 $wgOut->readOnlyPage();
1504 return;
1505 }
1506
1507 # Better double-check that it hasn't been deleted yet!
1508 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1509 if ( ( '' == trim( $this->mTitle->getText() ) )
1510 or ( $this->mTitle->getArticleId() == 0 ) ) {
1511 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1512 return;
1513 }
1514
1515 if ( $confirm ) {
1516 $this->doDelete( $reason );
1517 return;
1518 }
1519
1520 # determine whether this page has earlier revisions
1521 # and insert a warning if it does
1522 # we select the text because it might be useful below
1523 $dbr =& $this->getDB();
1524 $ns = $this->mTitle->getNamespace();
1525 $title = $this->mTitle->getDBkey();
1526 $revisions = $dbr->select( array( 'page', 'revision' ),
1527 array( 'rev_id' ),
1528 array(
1529 'page_namespace' => $ns,
1530 'page_title' => $title,
1531 'rev_page = page_id'
1532 ), $fname, $this->getSelectOptions( array( 'ORDER BY' => 'rev_timestamp DESC' ) )
1533 );
1534
1535 if( $dbr->numRows( $revisions ) > 1 && !$confirm ) {
1536 $skin=$wgUser->getSkin();
1537 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1538 $wgOut->addHTML( $skin->historyLink() .'</b>');
1539 }
1540
1541 # Fetch cur_text
1542 $s = $dbr->selectRow( array( 'page', 'text' ),
1543 array( 'old_text' ),
1544 array(
1545 'page_namespace' => $ns,
1546 'page_title' => $title,
1547 'page_latest = old_id'
1548 ), $fname, $this->getSelectOptions()
1549 );
1550
1551 if( $s !== false ) {
1552 # if this is a mini-text, we can paste part of it into the deletion reason
1553
1554 #if this is empty, an earlier revision may contain "useful" text
1555 $blanked = false;
1556 if($s->old_text != '') {
1557 $text=$s->old_text;
1558 } else {
1559 if($old) { # TODO
1560 $text = Revision::getRevisionText( $old );
1561 $blanked = true;
1562 }
1563
1564 }
1565
1566 $length=strlen($text);
1567
1568 # this should not happen, since it is not possible to store an empty, new
1569 # page. Let's insert a standard text in case it does, though
1570 if($length == 0 && $reason === '') {
1571 $reason = wfMsg('exblank');
1572 }
1573
1574 if($length < 500 && $reason === '') {
1575
1576 # comment field=255, let's grep the first 150 to have some user
1577 # space left
1578 $text=substr($text,0,150);
1579 # let's strip out newlines and HTML tags
1580 $text=preg_replace('/\"/',"'",$text);
1581 $text=preg_replace('/\</','&lt;',$text);
1582 $text=preg_replace('/\>/','&gt;',$text);
1583 $text=preg_replace("/[\n\r]/",'',$text);
1584 if(!$blanked) {
1585 $reason=wfMsg('excontent'). " '".$text;
1586 } else {
1587 $reason=wfMsg('exbeforeblank') . " '".$text;
1588 }
1589 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1590 $reason.="'";
1591 }
1592 }
1593
1594 return $this->confirmDelete( '', $reason );
1595 }
1596
1597 /**
1598 * Output deletion confirmation dialog
1599 */
1600 function confirmDelete( $par, $reason ) {
1601 global $wgOut, $wgUser;
1602
1603 wfDebug( "Article::confirmDelete\n" );
1604
1605 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1606 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1607 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1608 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1609
1610 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1611
1612 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1613 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1614 $token = htmlspecialchars( $wgUser->editToken() );
1615
1616 $wgOut->addHTML( "
1617 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1618 <table border='0'>
1619 <tr>
1620 <td align='right'>
1621 <label for='wpReason'>{$delcom}:</label>
1622 </td>
1623 <td align='left'>
1624 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1625 </td>
1626 </tr>
1627 <tr>
1628 <td>&nbsp;</td>
1629 <td>
1630 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1631 </td>
1632 </tr>
1633 </table>
1634 <input type='hidden' name='wpEditToken' value=\"{$token}\" />
1635 </form>\n" );
1636
1637 $wgOut->returnToMain( false );
1638 }
1639
1640
1641 /**
1642 * Perform a deletion and output success or failure messages
1643 */
1644 function doDelete( $reason ) {
1645 global $wgOut, $wgUser, $wgContLang;
1646 $fname = 'Article::doDelete';
1647 wfDebug( $fname."\n" );
1648
1649 if (wfRunHooks('ArticleDelete', array(&$this, &$wgUser, &$reason))) {
1650 if ( $this->doDeleteArticle( $reason ) ) {
1651 $deleted = $this->mTitle->getPrefixedText();
1652
1653 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1654 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1655
1656 $sk = $wgUser->getSkin();
1657 $loglink = $sk->makeKnownLink( $wgContLang->getNsText( NS_PROJECT ) .
1658 ':' . wfMsgForContent( 'dellogpage' ),
1659 wfMsg( 'deletionlog' ) );
1660
1661 $text = wfMsg( 'deletedtext', $deleted, $loglink );
1662
1663 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1664 $wgOut->returnToMain( false );
1665 wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason));
1666 } else {
1667 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1668 }
1669 }
1670 }
1671
1672 /**
1673 * Back-end article deletion
1674 * Deletes the article with database consistency, writes logs, purges caches
1675 * Returns success
1676 */
1677 function doDeleteArticle( $reason ) {
1678 global $wgUser;
1679 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgPostCommitUpdateList;
1680
1681 $fname = 'Article::doDeleteArticle';
1682 wfDebug( $fname."\n" );
1683
1684 $dbw =& wfGetDB( DB_MASTER );
1685 $ns = $this->mTitle->getNamespace();
1686 $t = $this->mTitle->getDBkey();
1687 $id = $this->mTitle->getArticleID();
1688
1689 if ( $t == '' || $id == 0 ) {
1690 return false;
1691 }
1692
1693 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1694 array_push( $wgDeferredUpdateList, $u );
1695
1696 $linksTo = $this->mTitle->getLinksTo();
1697
1698 # Squid purging
1699 if ( $wgUseSquid ) {
1700 $urls = array(
1701 $this->mTitle->getInternalURL(),
1702 $this->mTitle->getInternalURL( 'history' )
1703 );
1704 foreach ( $linksTo as $linkTo ) {
1705 $urls[] = $linkTo->getInternalURL();
1706 }
1707
1708 $u = new SquidUpdate( $urls );
1709 array_push( $wgPostCommitUpdateList, $u );
1710
1711 }
1712
1713 # Client and file cache invalidation
1714 Title::touchArray( $linksTo );
1715
1716 # Move article and history to the "archive" table
1717
1718 $dbw->insertSelect( 'archive', array( 'page','revision', 'text' ),
1719 array(
1720 'ar_namespace' => 'page_namespace',
1721 'ar_title' => 'page_title',
1722 'ar_text' => 'old_text',
1723 'ar_comment' => 'rev_comment',
1724 'ar_user' => 'rev_user',
1725 'ar_user_text' => 'rev_user_text',
1726 'ar_timestamp' => 'rev_timestamp',
1727 'ar_minor_edit' => 'rev_minor_edit',
1728 'ar_flags' => 'old_flags',
1729 'ar_rev_id' => 'rev_id',
1730 ), array(
1731 'page_namespace' => $ns,
1732 'page_title' => $t,
1733 'page_id = rev_page AND old_id = rev_id'
1734 ), $fname
1735 );
1736
1737 # Now that it's safely backed up, delete it
1738
1739 $dbw->deleteJoin( 'text', 'revision', 'old_id', 'rev_id', array( "rev_page = {$id}" ), $fname );
1740 $dbw->delete( 'revision', array( 'rev_page' => $id ), $fname );
1741 $dbw->delete( 'page', array( 'page_id' => $id ), $fname);
1742
1743 $dbw->delete( 'recentchanges', array( 'rc_namespace' => $ns, 'rc_title' => $t ), $fname );
1744
1745 # Finally, clean up the link tables
1746 $t = $this->mTitle->getPrefixedDBkey();
1747
1748 Article::onArticleDelete( $this->mTitle );
1749
1750 # Insert broken links
1751 $brokenLinks = array();
1752 foreach ( $linksTo as $titleObj ) {
1753 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1754 $linkID = $titleObj->getArticleID();
1755 $brokenLinks[] = array( 'bl_from' => $linkID, 'bl_to' => $t );
1756 }
1757 $dbw->insert( 'brokenlinks', $brokenLinks, $fname, 'IGNORE' );
1758
1759 # Delete live links
1760 $dbw->delete( 'links', array( 'l_to' => $id ) );
1761 $dbw->delete( 'links', array( 'l_from' => $id ) );
1762 $dbw->delete( 'imagelinks', array( 'il_from' => $id ) );
1763 $dbw->delete( 'brokenlinks', array( 'bl_from' => $id ) );
1764 $dbw->delete( 'categorylinks', array( 'cl_from' => $id ) );
1765
1766 # Log the deletion
1767 $log = new LogPage( 'delete' );
1768 $log->addEntry( 'delete', $this->mTitle, $reason );
1769
1770 # Clear the cached article id so the interface doesn't act like we exist
1771 $this->mTitle->resetArticleID( 0 );
1772 $this->mTitle->mArticleID = 0;
1773 return true;
1774 }
1775
1776 /**
1777 * Revert a modification
1778 */
1779 function rollback() {
1780 global $wgUser, $wgOut, $wgRequest;
1781 $fname = 'Article::rollback';
1782
1783 if ( ! $wgUser->isAllowed('rollback') ) {
1784 $wgOut->sysopRequired();
1785 return;
1786 }
1787 if ( wfReadOnly() ) {
1788 $wgOut->readOnlyPage( $this->getContent( true ) );
1789 return;
1790 }
1791 if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
1792 array( $this->mTitle->getPrefixedText(),
1793 $wgRequest->getVal( 'from' ) ) ) ) {
1794 $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
1795 $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
1796 return;
1797 }
1798 $dbw =& wfGetDB( DB_MASTER );
1799
1800 # Enhanced rollback, marks edits rc_bot=1
1801 $bot = $wgRequest->getBool( 'bot' );
1802
1803 # Replace all this user's current edits with the next one down
1804 $tt = $this->mTitle->getDBKey();
1805 $n = $this->mTitle->getNamespace();
1806
1807 # Get the last editor, lock table exclusively
1808 $dbw->begin();
1809 $current = Revision::newFromTitle( $this->mTitle );
1810 if( is_null( $current ) ) {
1811 # Something wrong... no page?
1812 $dbw->rollback();
1813 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1814 return;
1815 }
1816
1817 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1818 if( $from != $current->getUserText() ) {
1819 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1820 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1821 htmlspecialchars( $this->mTitle->getPrefixedText()),
1822 htmlspecialchars( $from ),
1823 htmlspecialchars( $current->getUserText() ) ) );
1824 if( $current->getComment() != '') {
1825 $wgOut->addHTML(
1826 wfMsg( 'editcomment',
1827 htmlspecialchars( $current->getComment() ) ) );
1828 }
1829 return;
1830 }
1831
1832 # Get the last edit not by this guy
1833 $user = IntVal( $current->getUser() );
1834 $user_text = $dbw->addQuotes( $current->getUserText() );
1835 $s = $dbw->selectRow( 'revision',
1836 array( 'rev_id', 'rev_timestamp' ),
1837 array(
1838 'rev_page' => $current->getPage(),
1839 "rev_user <> {$user} OR rev_user_text <> {$user_text}"
1840 ), $fname,
1841 array(
1842 'USE INDEX' => 'page_timestamp',
1843 'ORDER BY' => 'rev_timestamp DESC' )
1844 );
1845 if( $s === false ) {
1846 # Something wrong
1847 $dbw->rollback();
1848 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1849 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1850 return;
1851 }
1852
1853 if ( $bot ) {
1854 # Mark all reverted edits as bot
1855 $dbw->update( 'recentchanges',
1856 array( /* SET */
1857 'rc_bot' => 1
1858 ), array( /* WHERE */
1859 'rc_cur_id' => $current->getPage(),
1860 'rc_user_text' => $current->getUserText(),
1861 "rc_timestamp > '{$s->rev_timestamp}'",
1862 ), $fname
1863 );
1864 }
1865
1866 # Save it!
1867 $target = Revision::newFromId( $s->rev_id );
1868 $newcomment = wfMsg( 'revertpage', $target->getUserText(), $from );
1869
1870 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1871 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1872 $wgOut->addHTML( '<h2>' . htmlspecialchars( $newcomment ) . "</h2>\n<hr />\n" );
1873
1874 $this->updateArticle( $target->getText(), $newcomment, 1, $this->mTitle->userIsWatching(), $bot );
1875 Article::onArticleEdit( $this->mTitle );
1876
1877 $dbw->commit();
1878 $wgOut->returnToMain( false );
1879 }
1880
1881
1882 /**
1883 * Do standard deferred updates after page view
1884 * @private
1885 */
1886 function viewUpdates() {
1887 global $wgDeferredUpdateList;
1888
1889 if ( 0 != $this->getID() ) {
1890 global $wgDisableCounters;
1891 if( !$wgDisableCounters ) {
1892 Article::incViewCount( $this->getID() );
1893 $u = new SiteStatsUpdate( 1, 0, 0 );
1894 array_push( $wgDeferredUpdateList, $u );
1895 }
1896 }
1897
1898 # Update newtalk status if user is reading their own
1899 # talk page
1900
1901 global $wgUser;
1902 if ($this->mTitle->getNamespace() == NS_USER_TALK &&
1903 $this->mTitle->getText() == $wgUser->getName()) {
1904 require_once( 'UserTalkUpdate.php' );
1905 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(), $this->mTitle->getDBkey(), false, false, false );
1906 } else {
1907 $wgUser->clearNotification( $this->mTitle );
1908 }
1909
1910 }
1911
1912 /**
1913 * Do standard deferred updates after page edit.
1914 * Every 1000th edit, prune the recent changes table.
1915 * @private
1916 * @param string $text
1917 */
1918 function editUpdates( $text, $summary, $minoredit, $timestamp_of_pagechange) {
1919 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1920 global $wgMessageCache, $wgUser;
1921
1922 wfSeedRandom();
1923 if ( 0 == mt_rand( 0, 999 ) ) {
1924 # Periodically flush old entries from the recentchanges table.
1925 global $wgRCMaxAge;
1926 $dbw =& wfGetDB( DB_MASTER );
1927 $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
1928 $recentchanges = $dbw->tableName( 'recentchanges' );
1929 $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
1930 $dbw->query( $sql );
1931 }
1932 $id = $this->getID();
1933 $title = $this->mTitle->getPrefixedDBkey();
1934 $shortTitle = $this->mTitle->getDBkey();
1935
1936 $adj = $this->mCountAdjustment;
1937
1938 if ( 0 != $id ) {
1939 $u = new LinksUpdate( $id, $title );
1940 array_push( $wgDeferredUpdateList, $u );
1941 $u = new SiteStatsUpdate( 0, 1, $adj );
1942 array_push( $wgDeferredUpdateList, $u );
1943 $u = new SearchUpdate( $id, $title, $text );
1944 array_push( $wgDeferredUpdateList, $u );
1945
1946 # If this is another user's talk page,
1947 # create a watchlist entry for this page
1948
1949 if ($this->mTitle->getNamespace() == NS_USER_TALK &&
1950 $shortTitle != $wgUser->getName()) {
1951 require_once( 'UserTalkUpdate.php' );
1952 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle, $summary, $minoredit, $timestamp_of_pagechange);
1953 }
1954
1955 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1956 $wgMessageCache->replace( $shortTitle, $text );
1957 }
1958 }
1959 }
1960
1961 /**
1962 * @todo document this function
1963 * @private
1964 * @param string $oldid Revision ID of this article revision
1965 */
1966 function setOldSubtitle( $oldid=0 ) {
1967 global $wgLang, $wgOut, $wgUser;
1968
1969 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1970 $sk = $wgUser->getSkin();
1971 $lnk = $sk->makeKnownLinkObj ( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
1972 $prevlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid );
1973 $nextlink = $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
1974 $r = wfMsg( 'revisionasofwithlink', $td, $lnk, $prevlink, $nextlink );
1975 $wgOut->setSubtitle( $r );
1976 }
1977
1978 /**
1979 * This function is called right before saving the wikitext,
1980 * so we can do things like signatures and links-in-context.
1981 *
1982 * @param string $text
1983 */
1984 function preSaveTransform( $text ) {
1985 global $wgParser, $wgUser;
1986 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
1987 }
1988
1989 /* Caching functions */
1990
1991 /**
1992 * checkLastModified returns true if it has taken care of all
1993 * output to the client that is necessary for this request.
1994 * (that is, it has sent a cached version of the page)
1995 */
1996 function tryFileCache() {
1997 static $called = false;
1998 if( $called ) {
1999 wfDebug( " tryFileCache() -- called twice!?\n" );
2000 return;
2001 }
2002 $called = true;
2003 if($this->isFileCacheable()) {
2004 $touched = $this->mTouched;
2005 $cache = new CacheManager( $this->mTitle );
2006 if($cache->isFileCacheGood( $touched )) {
2007 global $wgOut;
2008 wfDebug( " tryFileCache() - about to load\n" );
2009 $cache->loadFromFileCache();
2010 return true;
2011 } else {
2012 wfDebug( " tryFileCache() - starting buffer\n" );
2013 ob_start( array(&$cache, 'saveToFileCache' ) );
2014 }
2015 } else {
2016 wfDebug( " tryFileCache() - not cacheable\n" );
2017 }
2018 }
2019
2020 /**
2021 * Check if the page can be cached
2022 * @return bool
2023 */
2024 function isFileCacheable() {
2025 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
2026 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
2027
2028 return $wgUseFileCache
2029 and (!$wgShowIPinHeader)
2030 and ($this->getID() != 0)
2031 and ($wgUser->isAnon())
2032 and (!$wgUser->getNewtalk())
2033 and ($this->mTitle->getNamespace() != NS_SPECIAL )
2034 and (empty( $action ) || $action == 'view')
2035 and (!isset($oldid))
2036 and (!isset($diff))
2037 and (!isset($redirect))
2038 and (!isset($printable))
2039 and (!$this->mRedirectedFrom);
2040 }
2041
2042 /**
2043 * Loads cur_touched and returns a value indicating if it should be used
2044 *
2045 */
2046 function checkTouched() {
2047 $fname = 'Article::checkTouched';
2048 if( !$this->mDataLoaded ) {
2049 $dbr =& $this->getDB();
2050 $data = $this->pageDataFromId( $dbr, $this->getId() );
2051 if( $data ) {
2052 $this->loadPageData( $data );
2053 }
2054 }
2055 return !$this->mIsRedirect;
2056 }
2057
2058 /**
2059 * Edit an article without doing all that other stuff
2060 * The article must already exist; link tables etc
2061 * are not updated, caches are not flushed.
2062 *
2063 * @param string $text text submitted
2064 * @param string $comment comment submitted
2065 * @param bool $minor whereas it's a minor modification
2066 */
2067 function quickEdit( $text, $comment = '', $minor = 0 ) {
2068 $fname = 'Article::quickEdit';
2069 wfProfileIn( $fname );
2070
2071 $dbw =& wfGetDB( DB_MASTER );
2072 $dbw->begin();
2073 $revision = new Revision( array(
2074 'page' => $this->getId(),
2075 'text' => $text,
2076 'comment' => $comment,
2077 'minor_edit' => $minor ? 1 : 0,
2078 ) );
2079 $revisionId = $revision->insertOn( $dbw );
2080 $this->updateRevisionOn( $dbw, $revision );
2081 $dbw->commit();
2082
2083 wfProfileOut( $fname );
2084 }
2085
2086 /**
2087 * Used to increment the view counter
2088 *
2089 * @static
2090 * @param integer $id article id
2091 */
2092 function incViewCount( $id ) {
2093 $id = intval( $id );
2094 global $wgHitcounterUpdateFreq;
2095
2096 $dbw =& wfGetDB( DB_MASTER );
2097 $pageTable = $dbw->tableName( 'page' );
2098 $hitcounterTable = $dbw->tableName( 'hitcounter' );
2099 $acchitsTable = $dbw->tableName( 'acchits' );
2100
2101 if( $wgHitcounterUpdateFreq <= 1 ){ //
2102 $dbw->query( "UPDATE $pageTable SET page_counter = page_counter + 1 WHERE page_id = $id" );
2103 return;
2104 }
2105
2106 # Not important enough to warrant an error page in case of failure
2107 $oldignore = $dbw->ignoreErrors( true );
2108
2109 $dbw->query( "INSERT INTO $hitcounterTable (hc_id) VALUES ({$id})" );
2110
2111 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
2112 if( (rand() % $checkfreq != 0) or ($dbw->lastErrno() != 0) ){
2113 # Most of the time (or on SQL errors), skip row count check
2114 $dbw->ignoreErrors( $oldignore );
2115 return;
2116 }
2117
2118 $res = $dbw->query("SELECT COUNT(*) as n FROM $hitcounterTable");
2119 $row = $dbw->fetchObject( $res );
2120 $rown = intval( $row->n );
2121 if( $rown >= $wgHitcounterUpdateFreq ){
2122 wfProfileIn( 'Article::incViewCount-collect' );
2123 $old_user_abort = ignore_user_abort( true );
2124
2125 $dbw->query("LOCK TABLES $hitcounterTable WRITE");
2126 $dbw->query("CREATE TEMPORARY TABLE $acchitsTable TYPE=HEAP ".
2127 "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
2128 'GROUP BY hc_id');
2129 $dbw->query("DELETE FROM $hitcounterTable");
2130 $dbw->query('UNLOCK TABLES');
2131 $dbw->query("UPDATE $curTable,$acchitsTable SET cur_counter=cur_counter + hc_n ".
2132 'WHERE cur_id = hc_id');
2133 $dbw->query("DROP TABLE $acchitsTable");
2134
2135 ignore_user_abort( $old_user_abort );
2136 wfProfileOut( 'Article::incViewCount-collect' );
2137 }
2138 $dbw->ignoreErrors( $oldignore );
2139 }
2140
2141 /**#@+
2142 * The onArticle*() functions are supposed to be a kind of hooks
2143 * which should be called whenever any of the specified actions
2144 * are done.
2145 *
2146 * This is a good place to put code to clear caches, for instance.
2147 *
2148 * This is called on page move and undelete, as well as edit
2149 * @static
2150 * @param $title_obj a title object
2151 */
2152
2153 function onArticleCreate($title_obj) {
2154 global $wgUseSquid, $wgPostCommitUpdateList;
2155
2156 $titles = $title_obj->getBrokenLinksTo();
2157
2158 # Purge squid
2159 if ( $wgUseSquid ) {
2160 $urls = $title_obj->getSquidURLs();
2161 foreach ( $titles as $linkTitle ) {
2162 $urls[] = $linkTitle->getInternalURL();
2163 }
2164 $u = new SquidUpdate( $urls );
2165 array_push( $wgPostCommitUpdateList, $u );
2166 }
2167
2168 # Clear persistent link cache
2169 LinkCache::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
2170 }
2171
2172 function onArticleDelete($title_obj) {
2173 LinkCache::linksccClearLinksTo( $title_obj->getArticleID() );
2174 }
2175 function onArticleEdit($title_obj) {
2176 LinkCache::linksccClearPage( $title_obj->getArticleID() );
2177 }
2178 /**#@-*/
2179
2180 /**
2181 * Info about this page
2182 * Called for ?action=info when $wgAllowPageInfo is on.
2183 *
2184 * @access public
2185 */
2186 function info() {
2187 global $wgLang, $wgOut, $wgAllowPageInfo;
2188 $fname = 'Article::info';
2189
2190 if ( !$wgAllowPageInfo ) {
2191 $wgOut->errorpage( 'nosuchaction', 'nosuchactiontext' );
2192 return;
2193 }
2194
2195 $page = $this->mTitle->getSubjectPage();
2196
2197 $wgOut->setPagetitle( $page->getPrefixedText() );
2198 $wgOut->setSubtitle( wfMsg( 'infosubtitle' ));
2199
2200 # first, see if the page exists at all.
2201 $exists = $page->getArticleId() != 0;
2202 if( !$exists ) {
2203 $wgOut->addHTML( wfMsg('noarticletext') );
2204 } else {
2205 $dbr =& $this->getDB( DB_SLAVE );
2206 $wl_clause = array(
2207 'wl_title' => $page->getDBkey(),
2208 'wl_namespace' => $page->getNamespace() );
2209 $numwatchers = $dbr->selectField(
2210 'watchlist',
2211 'COUNT(*)',
2212 $wl_clause,
2213 $fname,
2214 $this->getSelectOptions() );
2215
2216 $pageInfo = $this->pageCountInfo( $page );
2217 $talkInfo = $this->pageCountInfo( $page->getTalkPage() );
2218
2219 $wgOut->addHTML( "<ul><li>" . wfMsg("numwatchers", $wgLang->formatNum( $numwatchers ) ) . '</li>' );
2220 $wgOut->addHTML( "<li>" . wfMsg('numedits', $wgLang->formatNum( $pageInfo['edits'] ) ) . '</li>');
2221 if( $talkInfo ) {
2222 $wgOut->addHTML( '<li>' . wfMsg("numtalkedits", $wgLang->formatNum( $talkInfo['edits'] ) ) . '</li>');
2223 }
2224 $wgOut->addHTML( '<li>' . wfMsg("numauthors", $wgLang->formatNum( $pageInfo['authors'] ) ) . '</li>' );
2225 if( $talkInfo ) {
2226 $wgOut->addHTML( '<li>' . wfMsg('numtalkauthors', $wgLang->formatNum( $talkInfo['authors'] ) ) . '</li>' );
2227 }
2228 $wgOut->addHTML( '</ul>' );
2229
2230 }
2231 }
2232
2233 /**
2234 * Return the total number of edits and number of unique editors
2235 * on a given page. If page does not exist, returns false.
2236 *
2237 * @param Title $title
2238 * @return array
2239 * @access private
2240 */
2241 function pageCountInfo( $title ) {
2242 $id = $title->getArticleId();
2243 if( $id == 0 ) {
2244 return false;
2245 }
2246
2247 $dbr =& $this->getDB( DB_SLAVE );
2248
2249 $rev_clause = array( 'rev_page' => $id );
2250 $fname = 'Article::pageCountInfo';
2251
2252 $edits = $dbr->selectField(
2253 'revision',
2254 'COUNT(rev_page)',
2255 $rev_clause,
2256 $fname,
2257 $this->getSelectOptions() );
2258
2259 $authors = $dbr->selectField(
2260 'revision',
2261 'COUNT(DISTINCT rev_user_text)',
2262 $rev_clause,
2263 $fname,
2264 $this->getSelectOptions() );
2265
2266 return array( 'edits' => $edits, 'authors' => $authors );
2267 }
2268 }
2269
2270
2271 ?>