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