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