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