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