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