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