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