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