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