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