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