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