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