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