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