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