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