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