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