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