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