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