5bbc6d2a6fcce0a6eebd2d3f4d88f363c5424047
[lhc/web/wiklou.git] / includes / Article.php
1 <?php
2 # $Id$
3 #
4 # Class representing a Wikipedia article and history.
5 # See design.doc for an overview.
6
7 # Note: edit user interface and cache support functions have been
8 # moved to separate EditPage and CacheManager classes.
9
10 require_once( 'CacheManager.php' );
11
12 class Article {
13 /* private */ var $mContent, $mContentLoaded;
14 /* private */ var $mUser, $mTimestamp, $mUserText;
15 /* private */ var $mCounter, $mComment, $mCountAdjustment;
16 /* private */ var $mMinorEdit, $mRedirectedFrom;
17 /* private */ var $mTouched, $mFileCache, $mTitle;
18 /* private */ var $mId, $mTable;
19
20 function Article( &$title ) {
21 $this->mTitle =& $title;
22 $this->clear();
23 }
24
25 /* private */ function clear()
26 {
27 $this->mContentLoaded = false;
28 $this->mCurID = $this->mUser = $this->mCounter = -1; # Not loaded
29 $this->mRedirectedFrom = $this->mUserText =
30 $this->mTimestamp = $this->mComment = $this->mFileCache = '';
31 $this->mCountAdjustment = 0;
32 $this->mTouched = '19700101000000';
33 }
34
35 # Get revision text associated with an old or archive row
36 # $row is usually an object from wfFetchRow(), both the flags and the text field must be included
37 /* static */ function getRevisionText( $row, $prefix = 'old_' ) {
38 # Get data
39 $textField = $prefix . 'text';
40 $flagsField = $prefix . 'flags';
41
42 if ( isset( $row->$flagsField ) ) {
43 $flags = explode( ",", $row->$flagsField );
44 } else {
45 $flags = array();
46 }
47
48 if ( isset( $row->$textField ) ) {
49 $text = $row->$textField;
50 } else {
51 return false;
52 }
53
54 if ( in_array( 'link', $flags ) ) {
55 # Handle link type
56 $text = Article::followLink( $text );
57 } elseif ( in_array( 'gzip', $flags ) ) {
58 # Deal with optional compression of archived pages.
59 # This can be done periodically via maintenance/compressOld.php, and
60 # as pages are saved if $wgCompressRevisions is set.
61 return gzinflate( $text );
62 }
63 return $text;
64 }
65
66 /* static */ function compressRevisionText( &$text ) {
67 global $wgCompressRevisions;
68 if( !$wgCompressRevisions ) {
69 return '';
70 }
71 if( !function_exists( 'gzdeflate' ) ) {
72 wfDebug( "Article::compressRevisionText() -- no zlib support, not compressing\n" );
73 return '';
74 }
75 $text = gzdeflate( $text );
76 return 'gzip';
77 }
78
79 # Returns the text associated with a "link" type old table row
80 /* static */ function followLink( $link ) {
81 # Split the link into fields and values
82 $lines = explode( '\n', $link );
83 $hash = '';
84 $locations = array();
85 foreach ( $lines as $line ) {
86 # Comments
87 if ( $line{0} == '#' ) {
88 continue;
89 }
90 # Field/value pairs
91 if ( preg_match( '/^(.*?)\s*:\s*(.*)$/', $line, $matches ) ) {
92 $field = strtolower($matches[1]);
93 $value = $matches[2];
94 if ( $field == 'hash' ) {
95 $hash = $value;
96 } elseif ( $field == 'location' ) {
97 $locations[] = $value;
98 }
99 }
100 }
101
102 if ( $hash === '' ) {
103 return false;
104 }
105
106 # Look in each specified location for the text
107 $text = false;
108 foreach ( $locations as $location ) {
109 $text = Article::fetchFromLocation( $location, $hash );
110 if ( $text !== false ) {
111 break;
112 }
113 }
114
115 return $text;
116 }
117
118 /* static */ function fetchFromLocation( $location, $hash ) {
119 global $wgLoadBalancer;
120 $fname = 'fetchFromLocation';
121 wfProfileIn( $fname );
122
123 $p = strpos( $location, ':' );
124 if ( $p === false ) {
125 wfProfileOut( $fname );
126 return false;
127 }
128
129 $type = substr( $location, 0, $p );
130 $text = false;
131 switch ( $type ) {
132 case 'mysql':
133 # MySQL locations are specified by mysql://<machineID>/<dbname>/<tblname>/<index>
134 # Machine ID 0 is the current connection
135 if ( preg_match( '/^mysql:\/\/(\d+)\/([A-Za-z_]+)\/([A-Za-z_]+)\/([A-Za-z_]+)$/',
136 $location, $matches ) ) {
137 $machineID = $matches[1];
138 $dbName = $matches[2];
139 $tblName = $matches[3];
140 $index = $matches[4];
141 if ( $machineID == 0 ) {
142 # Current connection
143 $db =& wfGetDB();
144 } else {
145 # Alternate connection
146 $db =& $wgLoadBalancer->getConnection( $machineID );
147
148 if ( array_key_exists( $machineId, $wgKnownMysqlServers ) ) {
149 # Try to open, return false on failure
150 $params = $wgKnownDBServers[$machineId];
151 $db = Database::newFromParams( $params['server'], $params['user'], $params['password'],
152 $dbName, 1, false, true, true );
153 }
154 }
155 if ( $db->isOpen() ) {
156 $index = wfStrencode( $index );
157 $res = $db->query( "SELECT blob_data FROM $dbName.$tblName WHERE blob_index='$index'", $fname );
158 $row = $db->fetchObject( $res );
159 $text = $row->text_data;
160 }
161 }
162 break;
163 case 'file':
164 # File locations are of the form file://<filename>, relative to the current directory
165 if ( preg_match( '/^file:\/\/(.*)$', $location, $matches ) )
166 $filename = strstr( $location, 'file://' );
167 $text = @file_get_contents( $matches[1] );
168 }
169 if ( $text !== false ) {
170 # Got text, now we need to interpret it
171 # The first line contains information about how to do this
172 $p = strpos( $text, '\n' );
173 $type = substr( $text, 0, $p );
174 $text = substr( $text, $p + 1 );
175 switch ( $type ) {
176 case 'plain':
177 break;
178 case 'gzip':
179 $text = gzinflate( $text );
180 break;
181 case 'object':
182 $object = unserialize( $text );
183 $text = $object->getItem( $hash );
184 break;
185 default:
186 $text = false;
187 }
188 }
189 wfProfileOut( $fname );
190 return $text;
191 }
192
193 # Note that getContent/loadContent may follow redirects if
194 # not told otherwise, and so may cause a change to mTitle.
195
196 # Return the text of this revision
197 function getContent( $noredir )
198 {
199 global $wgRequest;
200
201 # Get variables from query string :P
202 $action = $wgRequest->getText( 'action', 'view' );
203 $section = $wgRequest->getText( 'section' );
204
205 $fname = 'Article::getContent';
206 wfProfileIn( $fname );
207
208 if ( 0 == $this->getID() ) {
209 if ( 'edit' == $action ) {
210 wfProfileOut( $fname );
211 return ''; # was "newarticletext", now moved above the box)
212 }
213 wfProfileOut( $fname );
214 return wfMsg( 'noarticletext' );
215 } else {
216 $this->loadContent( $noredir );
217
218 if(
219 # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page
220 ( $this->mTitle->getNamespace() == Namespace::getTalk( Namespace::getUser()) ) &&
221 preg_match('/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/',$this->mTitle->getText()) &&
222 $action=='view'
223 )
224 {
225 wfProfileOut( $fname );
226 return $this->mContent . "\n" .wfMsg('anontalkpagetext'); }
227 else {
228 if($action=='edit') {
229 if($section!='') {
230 if($section=='new') {
231 wfProfileOut( $fname );
232 return '';
233 }
234
235 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
236 # comments to be stripped as well)
237 $rv=$this->getSection($this->mContent,$section);
238 wfProfileOut( $fname );
239 return $rv;
240 }
241 }
242 wfProfileOut( $fname );
243 return $this->mContent;
244 }
245 }
246 }
247
248 # This function returns the text of a section, specified by a number ($section).
249 # A section is text under a heading like == Heading == or <h1>Heading</h1>, or
250 # the first section before any such heading (section 0).
251 #
252 # If a section contains subsections, these are also returned.
253 #
254 function getSection($text,$section) {
255
256 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
257 # comments to be stripped as well)
258 $striparray=array();
259 $parser=new Parser();
260 $parser->mOutputType=OT_WIKI;
261 $striptext=$parser->strip($text, $striparray, true);
262
263 # now that we can be sure that no pseudo-sections are in the source,
264 # split it up by section
265 $secs =
266 preg_split(
267 '/(^=+.*?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)/mi',
268 $striptext, -1,
269 PREG_SPLIT_DELIM_CAPTURE);
270 if($section==0) {
271 $rv=$secs[0];
272 } else {
273 $headline=$secs[$section*2-1];
274 preg_match( '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$headline,$matches);
275 $hlevel=$matches[1];
276
277 # translate wiki heading into level
278 if(strpos($hlevel,'=')!==false) {
279 $hlevel=strlen($hlevel);
280 }
281
282 $rv=$headline. $secs[$section*2];
283 $count=$section+1;
284
285 $break=false;
286 while(!empty($secs[$count*2-1]) && !$break) {
287
288 $subheadline=$secs[$count*2-1];
289 preg_match( '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$subheadline,$matches);
290 $subhlevel=$matches[1];
291 if(strpos($subhlevel,'=')!==false) {
292 $subhlevel=strlen($subhlevel);
293 }
294 if($subhlevel > $hlevel) {
295 $rv.=$subheadline.$secs[$count*2];
296 }
297 if($subhlevel <= $hlevel) {
298 $break=true;
299 }
300 $count++;
301
302 }
303 }
304 # reinsert stripped tags
305 $rv=$parser->unstrip($rv,$striparray);
306 $rv=$parser->unstripNoWiki($rv,$striparray);
307 $rv=trim($rv);
308 return $rv;
309
310 }
311
312
313 # Load the revision (including cur_text) into this object
314 function loadContent( $noredir = false )
315 {
316 global $wgOut, $wgMwRedir, $wgRequest, $wgIsPg;
317
318 # Query variables :P
319 $oldid = $wgRequest->getVal( 'oldid' );
320 $redirect = $wgRequest->getVal( 'redirect' );
321
322 if ( $this->mContentLoaded ) return;
323 $fname = 'Article::loadContent';
324
325 # Pre-fill content with error message so that if something
326 # fails we'll have something telling us what we intended.
327
328 $t = $this->mTitle->getPrefixedText();
329 if ( isset( $oldid ) ) {
330 $oldid = IntVal( $oldid );
331 $t .= ",oldid={$oldid}";
332 }
333 if ( isset( $redirect ) ) {
334 $redirect = ($redirect == 'no') ? 'no' : 'yes';
335 $t .= ",redirect={$redirect}";
336 }
337 $this->mContent = wfMsg( 'missingarticle', $t );
338
339 if ( ! $oldid ) { # Retrieve current version
340 $id = $this->getID();
341 if ( 0 == $id ) return;
342
343 $sql = 'SELECT ' .
344 'cur_text,cur_timestamp,cur_user,cur_user_text,cur_comment,cur_counter,cur_restrictions,cur_touched ' .
345 "FROM cur WHERE cur_id={$id}";
346 wfDebug( "$sql\n" );
347 $res = wfQuery( $sql, DB_READ, $fname );
348 if ( 0 == wfNumRows( $res ) ) {
349 return;
350 }
351
352 $s = wfFetchObject( $res );
353 # If we got a redirect, follow it (unless we've been told
354 # not to by either the function parameter or the query
355 if ( ( 'no' != $redirect ) && ( false == $noredir ) &&
356 ( $wgMwRedir->matchStart( $s->cur_text ) ) ) {
357 if ( preg_match( '/\\[\\[([^\\]\\|]+)[\\]\\|]/',
358 $s->cur_text, $m ) ) {
359 $rt = Title::newFromText( $m[1] );
360 if( $rt ) {
361 # Gotta hand redirects to special pages differently:
362 # Fill the HTTP response "Location" header and ignore
363 # the rest of the page we're on.
364
365 if ( $rt->getInterwiki() != '' ) {
366 $wgOut->redirect( $rt->getFullURL() ) ;
367 return;
368 }
369 if ( $rt->getNamespace() == Namespace::getSpecial() ) {
370 $wgOut->redirect( $rt->getFullURL() );
371 return;
372 }
373 $rid = $rt->getArticleID();
374 if ( 0 != $rid ) {
375 $sql = 'SELECT cur_text,cur_timestamp,cur_user,cur_user_text,cur_comment,' .
376 "cur_counter,cur_restrictions,cur_touched FROM cur WHERE cur_id={$rid}";
377 $res = wfQuery( $sql, DB_READ, $fname );
378
379 if ( 0 != wfNumRows( $res ) ) {
380 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
381 $this->mTitle = $rt;
382 $s = wfFetchObject( $res );
383 }
384 }
385 }
386 }
387 }
388
389 $this->mContent = $s->cur_text;
390 $this->mUser = $s->cur_user;
391 $this->mUserText = $s->cur_user_text;
392 $this->mComment = $s->cur_comment;
393 $this->mCounter = $s->cur_counter;
394 $this->mTimestamp = $s->cur_timestamp;
395 $this->mTouched = $s->cur_touched;
396 $this->mTitle->mRestrictions = explode( ',', trim( $s->cur_restrictions ) );
397 $this->mTitle->mRestrictionsLoaded = true;
398 wfFreeResult( $res );
399 } else { # oldid set, retrieve historical version
400 $oldtable=$wgIsPg?'"old"':'old';
401 $sql = "SELECT old_namespace,old_title,old_text,old_timestamp,".
402 "old_user,old_user_text,old_comment,old_flags FROM old ".
403 "WHERE old_id={$oldid}";
404 $res = wfQuery( $sql, DB_READ, $fname );
405 if ( 0 == wfNumRows( $res ) ) {
406 return;
407 }
408
409 $s = wfFetchObject( $res );
410 if( $this->mTitle->getNamespace() != $s->old_namespace ||
411 $this->mTitle->getDBkey() != $s->old_title ) {
412 $oldTitle = Title::makeTitle( $s->old_namesapce, $s->old_title );
413 $this->mTitle = $oldTitle;
414 $wgTitle = $oldTitle;
415 }
416 $this->mContent = Article::getRevisionText( $s );
417 $this->mUser = $s->old_user;
418 $this->mUserText = $s->old_user_text;
419 $this->mComment = $s->old_comment;
420 $this->mCounter = 0;
421 $this->mTimestamp = $s->old_timestamp;
422 wfFreeResult( $res );
423 }
424 $this->mContentLoaded = true;
425 return $this->mContent;
426 }
427
428 # Gets the article text without using so many damn globals
429 # Returns false on error
430 function getContentWithoutUsingSoManyDamnGlobals( $oldid = 0, $noredir = false ) {
431 global $wgMwRedir, $wgIsPg;
432
433 if ( $this->mContentLoaded ) {
434 return $this->mContent;
435 }
436 $this->mContent = false;
437
438 $fname = 'Article::loadContent';
439
440 if ( ! $oldid ) { # Retrieve current version
441 $id = $this->getID();
442 if ( 0 == $id ) {
443 return false;
444 }
445
446 $sql = 'SELECT ' .
447 'cur_text,cur_timestamp,cur_user,cur_counter,cur_restrictions,cur_touched ' .
448 "FROM cur WHERE cur_id={$id}";
449 $res = wfQuery( $sql, DB_READ, $fname );
450 if ( 0 == wfNumRows( $res ) ) {
451 return false;
452 }
453
454 $s = wfFetchObject( $res );
455 # If we got a redirect, follow it (unless we've been told
456 # not to by either the function parameter or the query
457 if ( !$noredir && $wgMwRedir->matchStart( $s->cur_text ) ) {
458 if ( preg_match( '/\\[\\[([^\\]\\|]+)[\\]\\|]/',
459 $s->cur_text, $m ) ) {
460 $rt = Title::newFromText( $m[1] );
461 if( $rt && $rt->getInterwiki() == '' && $rt->getNamespace() != Namespace::getSpecial() ) {
462 $rid = $rt->getArticleID();
463 if ( 0 != $rid ) {
464 $sql = 'SELECT cur_text,cur_timestamp,cur_user,' .
465 "cur_counter,cur_restrictions,cur_touched FROM cur WHERE cur_id={$rid}";
466 $res = wfQuery( $sql, DB_READ, $fname );
467
468 if ( 0 != wfNumRows( $res ) ) {
469 $this->mRedirectedFrom = $this->mTitle->getPrefixedText();
470 $this->mTitle = $rt;
471 $s = wfFetchObject( $res );
472 }
473 }
474 }
475 }
476 }
477
478 $this->mContent = $s->cur_text;
479 $this->mUser = $s->cur_user;
480 $this->mCounter = $s->cur_counter;
481 $this->mTimestamp = $s->cur_timestamp;
482 $this->mTouched = $s->cur_touched;
483 $this->mTitle->mRestrictions = explode( ",", trim( $s->cur_restrictions ) );
484 $this->mTitle->mRestrictionsLoaded = true;
485 wfFreeResult( $res );
486 } else { # oldid set, retrieve historical version
487 $oldtable=$wgIsPg?'"old"':'old';
488 $sql = "SELECT old_text,old_timestamp,old_user,old_flags FROM $oldtable " .
489 "WHERE old_id={$oldid}";
490 $res = wfQuery( $sql, DB_READ, $fname );
491 if ( 0 == wfNumRows( $res ) ) {
492 return false;
493 }
494
495 $s = wfFetchObject( $res );
496 $this->mContent = Article::getRevisionText( $s );
497 $this->mUser = $s->old_user;
498 $this->mCounter = 0;
499 $this->mTimestamp = $s->old_timestamp;
500 wfFreeResult( $res );
501 }
502 $this->mContentLoaded = true;
503 return $this->mContent;
504 }
505
506 function getID() {
507 if( $this->mTitle ) {
508 return $this->mTitle->getArticleID();
509 } else {
510 return 0;
511 }
512 }
513
514 function getCount()
515 {
516 if ( -1 == $this->mCounter ) {
517 $id = $this->getID();
518 $this->mCounter = wfGetSQL( 'cur', 'cur_counter', "cur_id={$id}" );
519 }
520 return $this->mCounter;
521 }
522
523 # Would the given text make this article a "good" article (i.e.,
524 # suitable for including in the article count)?
525
526 function isCountable( $text )
527 {
528 global $wgUseCommaCount, $wgMwRedir;
529
530 if ( 0 != $this->mTitle->getNamespace() ) { return 0; }
531 if ( $wgMwRedir->matchStart( $text ) ) { return 0; }
532 $token = ($wgUseCommaCount ? ',' : '[[' );
533 if ( false === strstr( $text, $token ) ) { return 0; }
534 return 1;
535 }
536
537 # Loads everything from cur except cur_text
538 # This isn't necessary for all uses, so it's only done if needed.
539
540 /* private */ function loadLastEdit()
541 {
542 global $wgOut;
543 if ( -1 != $this->mUser ) return;
544
545 $sql = 'SELECT cur_user,cur_user_text,cur_timestamp,' .
546 'cur_comment,cur_minor_edit FROM cur WHERE ' .
547 'cur_id=' . $this->getID();
548 $res = wfQuery( $sql, DB_READ, 'Article::loadLastEdit' );
549
550 if ( wfNumRows( $res ) > 0 ) {
551 $s = wfFetchObject( $res );
552 $this->mUser = $s->cur_user;
553 $this->mUserText = $s->cur_user_text;
554 $this->mTimestamp = $s->cur_timestamp;
555 $this->mComment = $s->cur_comment;
556 $this->mMinorEdit = $s->cur_minor_edit;
557 }
558 }
559
560 function getTimestamp()
561 {
562 $this->loadLastEdit();
563 return $this->mTimestamp;
564 }
565
566 function getUser()
567 {
568 $this->loadLastEdit();
569 return $this->mUser;
570 }
571
572 function getUserText()
573 {
574 $this->loadLastEdit();
575 return $this->mUserText;
576 }
577
578 function getComment()
579 {
580 $this->loadLastEdit();
581 return $this->mComment;
582 }
583
584 function getMinorEdit()
585 {
586 $this->loadLastEdit();
587 return $this->mMinorEdit;
588 }
589
590 function getContributors($limit = 0, $offset = 0)
591 {
592 $fname = 'Article::getContributors';
593
594 # XXX: this is expensive; cache this info somewhere.
595
596 $title = $this->mTitle;
597
598 $contribs = array();
599
600 $sql = 'SELECT old_user, old_user_text, ' .
601 ' user_real_name, MAX(old_timestamp) as timestamp' .
602 ' FROM old LEFT JOIN user ON old.old_user = user.user_id ' .
603 ' WHERE old.old_namespace = ' . $title->getNamespace() .
604 ' AND old.old_title = "' . $title->getDBkey() . '"' .
605 ' AND old.old_user != ' . $this->getUser() .
606 ' GROUP BY old.old_user ' .
607 ' ORDER BY timestamp DESC ';
608
609 if ($limit > 0) {
610 $sql .= ' LIMIT '.$limit;
611 }
612
613 $res = wfQuery($sql, DB_READ, $fname);
614
615 while ( $line = wfFetchObject( $res ) ) {
616 $contribs[] = array($line->old_user, $line->old_user_text, $line->user_real_name);
617 }
618
619 wfFreeResult($res);
620
621 return $contribs;
622 }
623
624 # This is the default action of the script: just view the page of
625 # the given title.
626
627 function view()
628 {
629 global $wgUser, $wgOut, $wgLang, $wgRequest;
630 global $wgLinkCache, $IP, $wgEnableParserCache;
631
632 $fname = 'Article::view';
633 wfProfileIn( $fname );
634
635 # Get variables from query string :P
636 $oldid = $wgRequest->getVal( 'oldid' );
637 $diff = $wgRequest->getVal( 'diff' );
638
639 $wgOut->setArticleFlag( true );
640 $wgOut->setRobotpolicy( 'index,follow' );
641
642 # If we got diff and oldid in the query, we want to see a
643 # diff page instead of the article.
644
645 if ( !is_null( $diff ) ) {
646 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
647 $de = new DifferenceEngine( intval($oldid), intval($diff) );
648 $de->showDiffPage();
649 wfProfileOut( $fname );
650 return;
651 }
652
653 if ( !is_null( $oldid ) and $this->checkTouched() ) {
654 if( $wgOut->checkLastModified( $this->mTouched ) ){
655 return;
656 } else if ( $this->tryFileCache() ) {
657 # tell wgOut that output is taken care of
658 $wgOut->disable();
659 $this->viewUpdates();
660 return;
661 }
662 }
663
664 # Should the parser cache be used?
665 if ( $wgEnableParserCache && intval($wgUser->getOption( 'stubthreshold' )) == 0 && empty( $oldid ) ) {
666 $pcache = true;
667 } else {
668 $pcache = false;
669 }
670
671 $outputDone = false;
672 if ( $pcache ) {
673 if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
674 $outputDone = true;
675 }
676 }
677
678 if ( !$outputDone ) {
679 $text = $this->getContent( false ); # May change mTitle by following a redirect
680
681 # Another whitelist check in case oldid or redirects are altering the title
682 if ( !$this->mTitle->userCanRead() ) {
683 $wgOut->loginToUse();
684 $wgOut->output();
685 exit;
686 }
687
688
689 # We're looking at an old revision
690
691 if ( !empty( $oldid ) ) {
692 $this->setOldSubtitle();
693 $wgOut->setRobotpolicy( 'noindex,follow' );
694 }
695 if ( '' != $this->mRedirectedFrom ) {
696 $sk = $wgUser->getSkin();
697 $redir = $sk->makeKnownLink( $this->mRedirectedFrom, '',
698 'redirect=no' );
699 $s = wfMsg( 'redirectedfrom', $redir );
700 $wgOut->setSubtitle( $s );
701
702 # Can't cache redirects
703 $pcache = false;
704 }
705
706 $wgLinkCache->preFill( $this->mTitle );
707
708 # wrap user css and user js in pre and don't parse
709 # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
710 if (
711 $this->mTitle->getNamespace() == Namespace::getUser() &&
712 preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
713 ) {
714 $wgOut->addWikiText( wfMsg('clearyourcache'));
715 $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
716 } else if ( $pcache ) {
717 $wgOut->addWikiText( $text, true, $this );
718 } else {
719 $wgOut->addWikiText( $text );
720 }
721 }
722 $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
723
724 # Add link titles as META keywords
725 $wgOut->addMetaTags() ;
726
727 $this->viewUpdates();
728 wfProfileOut( $fname );
729 }
730
731 # Theoretically we could defer these whole insert and update
732 # functions for after display, but that's taking a big leap
733 # of faith, and we want to be able to report database
734 # errors at some point.
735
736 /* private */ function insertNewArticle( $text, $summary, $isminor, $watchthis )
737 {
738 global $wgOut, $wgUser, $wgLinkCache, $wgMwRedir;
739 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer, $wgIsPg, $wgIsMySQL;
740
741 $fname = 'Article::insertNewArticle';
742
743 $this->mCountAdjustment = $this->isCountable( $text );
744
745 $ns = $this->mTitle->getNamespace();
746 $ttl = $this->mTitle->getDBkey();
747 $text = $this->preSaveTransform( $text );
748 if ( $wgMwRedir->matchStart( $text ) ) { $redir = 1; }
749 else { $redir = 0; }
750
751 $now = wfTimestampNow();
752 $won = wfInvertTimestamp( $now );
753 wfSeedRandom();
754 $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
755
756 if ($wgIsPg) {
757 $cur_id_column="cur_id,";
758 $cur_id=wfGetSQL(""," nextval('cur_cur_id_seq')");
759 $cur_id_value="{$cur_id},";
760 } else {
761 $cur_id_column="";
762 $cur_id="";
763 $cur_id_value="";
764 }
765
766 $isminor = ( $isminor && $wgUser->getID() ) ? 1 : 0;
767 $sql = "INSERT INTO cur ({$cur_id_column}cur_namespace,cur_title,cur_text," .
768 'cur_comment,cur_user,cur_timestamp,cur_minor_edit,cur_counter,' .
769 'cur_restrictions,cur_user_text,cur_is_redirect,' .
770 "cur_is_new,cur_random,cur_touched,inverse_timestamp) VALUES ({$cur_id_value}{$ns},'" . wfStrencode( $ttl ) . "', '" .
771 wfStrencode( $text ) . "', '" .
772 wfStrencode( $summary ) . "', '" .
773 $wgUser->getID() . "', '{$now}', " .
774 $isminor . ", 0, '', '" .
775 wfStrencode( $wgUser->getName() ) . "', $redir, 1, $rand, '{$now}', '{$won}')";
776 $res = wfQuery( $sql, DB_WRITE, $fname );
777
778 $newid = $wgIsPg?$cur_id:wfInsertId();
779 $this->mTitle->resetArticleID( $newid );
780
781 Article::onArticleCreate( $this->mTitle );
782 RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary );
783
784 if ($watchthis) {
785 if(!$this->mTitle->userIsWatching()) $this->watch();
786 } else {
787 if ( $this->mTitle->userIsWatching() ) {
788 $this->unwatch();
789 }
790 }
791
792 # The talk page isn't in the regular link tables, so we need to update manually:
793 $talkns = $ns ^ 1; # talk -> normal; normal -> talk
794 $sql = "UPDATE cur set cur_touched='$now' WHERE cur_namespace=$talkns AND cur_title='" . wfStrencode( $ttl ) . "'";
795 wfQuery( $sql, DB_WRITE );
796
797 # standard deferred updates
798 $this->editUpdates( $text );
799
800 $this->showArticle( $text, wfMsg( 'newarticle' ) );
801 }
802
803
804 /* Side effects: loads last edit */
805 function getTextOfLastEditWithSectionReplacedOrAdded($section, $text, $summary = ''){
806 $this->loadLastEdit();
807 $oldtext = $this->getContent( true );
808 if ($section != '') {
809 if($section=='new') {
810 if($summary) $subject="== {$summary} ==\n\n";
811 $text=$oldtext."\n\n".$subject.$text;
812 } else {
813
814 # strip NOWIKI etc. to avoid confusion (true-parameter causes HTML
815 # comments to be stripped as well)
816 $striparray=array();
817 $parser=new Parser();
818 $parser->mOutputType=OT_WIKI;
819 $oldtext=$parser->strip($oldtext, $striparray, true);
820
821 # now that we can be sure that no pseudo-sections are in the source,
822 # split it up
823 # Unfortunately we can't simply do a preg_replace because that might
824 # replace the wrong section, so we have to use the section counter instead
825 $secs=preg_split('/(^=+.*?=+|^<h[1-6].*?' . '>.*?<\/h[1-6].*?' . '>)/mi',
826 $oldtext,-1,PREG_SPLIT_DELIM_CAPTURE);
827 $secs[$section*2]=$text."\n\n"; // replace with edited
828
829 # section 0 is top (intro) section
830 if($section!=0) {
831
832 # headline of old section - we need to go through this section
833 # to determine if there are any subsections that now need to
834 # be erased, as the mother section has been replaced with
835 # the text of all subsections.
836 $headline=$secs[$section*2-1];
837 preg_match( '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$headline,$matches);
838 $hlevel=$matches[1];
839
840 # determine headline level for wikimarkup headings
841 if(strpos($hlevel,'=')!==false) {
842 $hlevel=strlen($hlevel);
843 }
844
845 $secs[$section*2-1]=''; // erase old headline
846 $count=$section+1;
847 $break=false;
848 while(!empty($secs[$count*2-1]) && !$break) {
849
850 $subheadline=$secs[$count*2-1];
851 preg_match(
852 '/^(=+).*?=+|^<h([1-6]).*?' . '>.*?<\/h[1-6].*?' . '>/mi',$subheadline,$matches);
853 $subhlevel=$matches[1];
854 if(strpos($subhlevel,'=')!==false) {
855 $subhlevel=strlen($subhlevel);
856 }
857 if($subhlevel > $hlevel) {
858 // erase old subsections
859 $secs[$count*2-1]='';
860 $secs[$count*2]='';
861 }
862 if($subhlevel <= $hlevel) {
863 $break=true;
864 }
865 $count++;
866
867 }
868
869 }
870 $text=join('',$secs);
871 # reinsert the stuff that we stripped out earlier
872 $text=$parser->unstrip($text,$striparray);
873 $text=$parser->unstripNoWiki($text,$striparray);
874 }
875
876 }
877 return $text;
878 }
879
880 function updateArticle( $text, $summary, $minor, $watchthis, $forceBot = false, $sectionanchor = '' )
881 {
882 global $wgOut, $wgUser, $wgLinkCache;
883 global $wgDBtransactions, $wgMwRedir;
884 global $wgUseSquid, $wgInternalServer;
885 global $wgIsPg;
886 $fname = 'Article::updateArticle';
887
888 if ( $this->mMinorEdit ) { $me1 = 1; } else { $me1 = 0; }
889 if ( $minor && $wgUser->getID() ) { $me2 = 1; } else { $me2 = 0; }
890 if ( preg_match( "/^((" . $wgMwRedir->getBaseRegex() . ')[^\\n]+)/i', $text, $m ) ) {
891 $redir = 1;
892 $text = $m[1] . "\n"; # Remove all content but redirect
893 }
894 else { $redir = 0; }
895
896 $text = $this->preSaveTransform( $text );
897
898 # Update article, but only if changed.
899
900 if( $wgDBtransactions ) {
901 $sql = 'BEGIN';
902 wfQuery( $sql, DB_WRITE );
903 }
904 $oldtext = $this->getContent( true );
905
906 if ( 0 != strcmp( $text, $oldtext ) ) {
907 $this->mCountAdjustment = $this->isCountable( $text )
908 - $this->isCountable( $oldtext );
909
910 $now = wfTimestampNow();
911 $won = wfInvertTimestamp( $now );
912 $sql = "UPDATE cur SET cur_text='" . wfStrencode( $text ) .
913 "',cur_comment='" . wfStrencode( $summary ) .
914 "',cur_minor_edit={$me2}, cur_user=" . $wgUser->getID() .
915 ",cur_timestamp='{$now}',cur_user_text='" .
916 wfStrencode( $wgUser->getName() ) .
917 "',cur_is_redirect={$redir}, cur_is_new=0, cur_touched='{$now}', inverse_timestamp='{$won}' " .
918 "WHERE cur_id=" . $this->getID() .
919 " AND cur_timestamp='" . $this->getTimestamp() . "'";
920 $res = wfQuery( $sql, DB_WRITE, $fname );
921
922 if( wfAffectedRows() == 0 ) {
923 /* Belated edit conflict! Run away!! */
924 return false;
925 }
926
927 # This overwrites $oldtext if revision compression is on
928 $flags = Article::compressRevisionText( $oldtext );
929
930 $oldtable=$wgIsPg?'"old"':'old';
931 if ($wgIsPg) {
932 $oldtable='"old"';
933 $old_id_column='old_id,';
934 $old_id=wfGetSQL(""," nextval('old_old_id_seq')");
935 $old_id_value=$old_id.',';
936 } else {
937 $oldtable='old';
938 $old_id_column='';
939 $old_id_value='';
940 }
941
942 $sql = "INSERT INTO $oldtable ({$old_id_column}old_namespace,old_title,old_text," .
943 'old_comment,old_user,old_user_text,old_timestamp,' .
944 'old_minor_edit,inverse_timestamp,old_flags) VALUES (' .
945 $old_id_value.
946 $this->mTitle->getNamespace() . ", '" .
947 wfStrencode( $this->mTitle->getDBkey() ) . "', '" .
948 wfStrencode( $oldtext ) . "', '" .
949 wfStrencode( $this->getComment() ) . "', " .
950 $this->getUser() . ", '" .
951 wfStrencode( $this->getUserText() ) . "', '" .
952 $this->getTimestamp() . "', " . $me1 . ", '" .
953 wfInvertTimestamp( $this->getTimestamp() ) . "','$flags')";
954 $res = wfQuery( $sql, DB_WRITE, $fname );
955
956 $oldid = $wgIsPg?$old_id:wfInsertId( $res );
957
958 $bot = (int)($wgUser->isBot() || $forceBot);
959 RecentChange::notifyEdit( $now, $this->mTitle, $me2, $wgUser, $summary,
960 $oldid, $this->getTimestamp(), $bot );
961 Article::onArticleEdit( $this->mTitle );
962 }
963
964 if( $wgDBtransactions ) {
965 $sql = 'COMMIT';
966 wfQuery( $sql, DB_WRITE );
967 }
968
969 if ($watchthis) {
970 if (!$this->mTitle->userIsWatching()) $this->watch();
971 } else {
972 if ( $this->mTitle->userIsWatching() ) {
973 $this->unwatch();
974 }
975 }
976 # standard deferred updates
977 $this->editUpdates( $text );
978
979
980 $urls = array();
981 # Template namespace
982 # Purge all articles linking here
983 if ( $this->mTitle->getNamespace() == NS_TEMPLATE) {
984 $titles = $this->mTitle->getLinksTo();
985 Title::touchArray( $titles );
986 if ( $wgUseSquid ) {
987 foreach ( $titles as $title ) {
988 $urls[] = $title->getInternalURL();
989 }
990 }
991 }
992
993 # Squid updates
994 if ( $wgUseSquid ) {
995 $urls = array_merge( $urls, $this->mTitle->getSquidURLs() );
996 $u = new SquidUpdate( $urls );
997 $u->doUpdate();
998 }
999
1000 $this->showArticle( $text, wfMsg( 'updated' ), $sectionanchor );
1001 return true;
1002 }
1003
1004 # After we've either updated or inserted the article, update
1005 # the link tables and redirect to the new page.
1006
1007 function showArticle( $text, $subtitle , $sectionanchor = '' )
1008 {
1009 global $wgOut, $wgUser, $wgLinkCache;
1010 global $wgMwRedir;
1011
1012 $wgLinkCache = new LinkCache();
1013
1014 # Get old version of link table to allow incremental link updates
1015 $wgLinkCache->preFill( $this->mTitle );
1016 $wgLinkCache->clear();
1017
1018 # Now update the link cache by parsing the text
1019 $wgOut = new OutputPage();
1020 $wgOut->addWikiText( $text );
1021
1022 if( $wgMwRedir->matchStart( $text ) )
1023 $r = 'redirect=no';
1024 else
1025 $r = '';
1026 $wgOut->redirect( $this->mTitle->getFullURL( $r ).$sectionanchor );
1027 }
1028
1029 # Add this page to my watchlist
1030
1031 function watch( $add = true )
1032 {
1033 global $wgUser, $wgOut, $wgLang;
1034 global $wgDeferredUpdateList;
1035
1036 if ( 0 == $wgUser->getID() ) {
1037 $wgOut->errorpage( 'watchnologin', 'watchnologintext' );
1038 return;
1039 }
1040 if ( wfReadOnly() ) {
1041 $wgOut->readOnlyPage();
1042 return;
1043 }
1044 if( $add )
1045 $wgUser->addWatch( $this->mTitle );
1046 else
1047 $wgUser->removeWatch( $this->mTitle );
1048
1049 $wgOut->setPagetitle( wfMsg( $add ? 'addedwatch' : 'removedwatch' ) );
1050 $wgOut->setRobotpolicy( 'noindex,follow' );
1051
1052 $sk = $wgUser->getSkin() ;
1053 $link = $this->mTitle->getPrefixedText();
1054
1055 if($add)
1056 $text = wfMsg( 'addedwatchtext', $link );
1057 else
1058 $text = wfMsg( 'removedwatchtext', $link );
1059 $wgOut->addWikiText( $text );
1060
1061 $up = new UserUpdate();
1062 array_push( $wgDeferredUpdateList, $up );
1063
1064 $wgOut->returnToMain( false );
1065 }
1066
1067 function unwatch()
1068 {
1069 $this->watch( false );
1070 }
1071
1072 function protect( $limit = 'sysop' )
1073 {
1074 global $wgUser, $wgOut, $wgRequest;
1075
1076 if ( ! $wgUser->isSysop() ) {
1077 $wgOut->sysopRequired();
1078 return;
1079 }
1080 if ( wfReadOnly() ) {
1081 $wgOut->readOnlyPage();
1082 return;
1083 }
1084 $id = $this->mTitle->getArticleID();
1085 if ( 0 == $id ) {
1086 $wgOut->fatalError( wfMsg( 'badarticleerror' ) );
1087 return;
1088 }
1089
1090 $confirm = $wgRequest->getBool( 'wpConfirmProtect' ) && $wgRequest->wasPosted();
1091 $reason = $wgRequest->getText( 'wpReasonProtect' );
1092
1093 if ( $confirm ) {
1094
1095 $sql = "UPDATE cur SET cur_touched='" . wfTimestampNow() . "'," .
1096 "cur_restrictions='{$limit}' WHERE cur_id={$id}";
1097 wfQuery( $sql, DB_WRITE, 'Article::protect' );
1098
1099 $log = new LogPage( wfMsg( 'protectlogpage' ), wfMsg( 'protectlogtext' ) );
1100 if ( $limit === "" ) {
1101 $log->addEntry( wfMsg( 'unprotectedarticle', $this->mTitle->getPrefixedText() ), $reason );
1102 } else {
1103 $log->addEntry( wfMsg( 'protectedarticle', $this->mTitle->getPrefixedText() ), $reason );
1104 }
1105 $wgOut->redirect( $this->mTitle->getFullURL() );
1106 return;
1107 } else {
1108 $reason = htmlspecialchars( wfMsg( 'protectreason' ) );
1109 return $this->confirmProtect( '', $reason, $limit );
1110 }
1111 }
1112
1113 # Output protection confirmation dialog
1114 function confirmProtect( $par, $reason, $limit = 'sysop' )
1115 {
1116 global $wgOut;
1117
1118 wfDebug( "Article::confirmProtect\n" );
1119
1120 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1121 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1122
1123 $check = '';
1124 $protcom = '';
1125
1126 if ( $limit === '' ) {
1127 $wgOut->setSubtitle( wfMsg( 'unprotectsub', $sub ) );
1128 $wgOut->addWikiText( wfMsg( 'confirmunprotecttext' ) );
1129 $check = htmlspecialchars( wfMsg( 'confirmunprotect' ) );
1130 $protcom = htmlspecialchars( wfMsg( 'unprotectcomment' ) );
1131 $formaction = $this->mTitle->escapeLocalURL( 'action=unprotect' . $par );
1132 } else {
1133 $wgOut->setSubtitle( wfMsg( 'protectsub', $sub ) );
1134 $wgOut->addWikiText( wfMsg( 'confirmprotecttext' ) );
1135 $check = htmlspecialchars( wfMsg( 'confirmprotect' ) );
1136 $protcom = htmlspecialchars( wfMsg( 'protectcomment' ) );
1137 $formaction = $this->mTitle->escapeLocalURL( 'action=protect' . $par );
1138 }
1139
1140 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1141
1142 $wgOut->addHTML( "
1143 <form id='protectconfirm' method='post' action=\"{$formaction}\">
1144 <table border='0'>
1145 <tr>
1146 <td align='right'>
1147 <label for='wpReasonProtect'>{$protcom}:</label>
1148 </td>
1149 <td align='left'>
1150 <input type='text' size='60' name='wpReasonProtect' id='wpReasonProtect' value=\"" . htmlspecialchars( $reason ) . "\" />
1151 </td>
1152 </tr>
1153 <tr>
1154 <td>&nbsp;</td>
1155 </tr>
1156 <tr>
1157 <td align='right'>
1158 <input type='checkbox' name='wpConfirmProtect' value='1' id='wpConfirmProtect' />
1159 </td>
1160 <td>
1161 <label for='wpConfirmProtect'>{$check}</label>
1162 </td>
1163 </tr>
1164 <tr>
1165 <td>&nbsp;</td>
1166 <td>
1167 <input type='submit' name='wpConfirmProtectB' value=\"{$confirm}\" />
1168 </td>
1169 </tr>
1170 </table>
1171 </form>\n" );
1172
1173 $wgOut->returnToMain( false );
1174 }
1175
1176 function unprotect()
1177 {
1178 return $this->protect( '' );
1179 }
1180
1181 # UI entry point for page deletion
1182 function delete()
1183 {
1184 global $wgUser, $wgOut, $wgMessageCache, $wgRequest, $wgIsPg;
1185 $fname = 'Article::delete';
1186 $confirm = $wgRequest->getBool( 'wpConfirm' ) && $wgRequest->wasPosted();
1187 $reason = $wgRequest->getText( 'wpReason' );
1188
1189 # This code desperately needs to be totally rewritten
1190
1191 # Check permissions
1192 if ( ( ! $wgUser->isSysop() ) ) {
1193 $wgOut->sysopRequired();
1194 return;
1195 }
1196 if ( wfReadOnly() ) {
1197 $wgOut->readOnlyPage();
1198 return;
1199 }
1200
1201 # Better double-check that it hasn't been deleted yet!
1202 $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
1203 if ( ( '' == trim( $this->mTitle->getText() ) )
1204 or ( $this->mTitle->getArticleId() == 0 ) ) {
1205 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1206 return;
1207 }
1208
1209 if ( $confirm ) {
1210 $this->doDelete( $reason );
1211 return;
1212 }
1213
1214 # determine whether this page has earlier revisions
1215 # and insert a warning if it does
1216 # we select the text because it might be useful below
1217 $ns = $this->mTitle->getNamespace();
1218 $title = $this->mTitle->getDBkey();
1219 $etitle = wfStrencode( $title );
1220 $oldtable=$wgIsPg?'"old"':'old';
1221 $sql = "SELECT old_text,old_flags FROM $oldtable WHERE old_namespace=$ns and old_title='$etitle' ORDER BY inverse_timestamp LIMIT 1";
1222 $res = wfQuery( $sql, DB_READ, $fname );
1223 if( ($old=wfFetchObject($res)) && !$confirm ) {
1224 $skin=$wgUser->getSkin();
1225 $wgOut->addHTML('<b>'.wfMsg('historywarning'));
1226 $wgOut->addHTML( $skin->historyLink() .'</b>');
1227 }
1228
1229 $sql="SELECT cur_text FROM cur WHERE cur_namespace=$ns and cur_title='$etitle'";
1230 $res=wfQuery($sql, DB_READ, $fname);
1231 if( ($s=wfFetchObject($res))) {
1232
1233 # if this is a mini-text, we can paste part of it into the deletion reason
1234
1235 #if this is empty, an earlier revision may contain "useful" text
1236 $blanked = false;
1237 if($s->cur_text!="") {
1238 $text=$s->cur_text;
1239 } else {
1240 if($old) {
1241 $text = Article::getRevisionText( $old );
1242 $blanked = true;
1243 }
1244
1245 }
1246
1247 $length=strlen($text);
1248
1249 # this should not happen, since it is not possible to store an empty, new
1250 # page. Let's insert a standard text in case it does, though
1251 if($length == 0 && $reason === '') {
1252 $reason = wfMsg('exblank');
1253 }
1254
1255 if($length < 500 && $reason === '') {
1256
1257 # comment field=255, let's grep the first 150 to have some user
1258 # space left
1259 $text=substr($text,0,150);
1260 # let's strip out newlines and HTML tags
1261 $text=preg_replace('/\"/',"'",$text);
1262 $text=preg_replace('/\</','&lt;',$text);
1263 $text=preg_replace('/\>/','&gt;',$text);
1264 $text=preg_replace("/[\n\r]/",'',$text);
1265 if(!$blanked) {
1266 $reason=wfMsg('excontent'). " '".$text;
1267 } else {
1268 $reason=wfMsg('exbeforeblank') . " '".$text;
1269 }
1270 if($length>150) { $reason .= '...'; } # we've only pasted part of the text
1271 $reason.="'";
1272 }
1273 }
1274
1275 return $this->confirmDelete( '', $reason );
1276 }
1277
1278 # Output deletion confirmation dialog
1279 function confirmDelete( $par, $reason )
1280 {
1281 global $wgOut;
1282
1283 wfDebug( "Article::confirmDelete\n" );
1284
1285 $sub = htmlspecialchars( $this->mTitle->getPrefixedText() );
1286 $wgOut->setSubtitle( wfMsg( 'deletesub', $sub ) );
1287 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1288 $wgOut->addWikiText( wfMsg( 'confirmdeletetext' ) );
1289
1290 $formaction = $this->mTitle->escapeLocalURL( 'action=delete' . $par );
1291
1292 $confirm = htmlspecialchars( wfMsg( 'confirm' ) );
1293 $check = htmlspecialchars( wfMsg( 'confirmcheck' ) );
1294 $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
1295
1296 $wgOut->addHTML( "
1297 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
1298 <table border='0'>
1299 <tr>
1300 <td align='right'>
1301 <label for='wpReason'>{$delcom}:</label>
1302 </td>
1303 <td align='left'>
1304 <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
1305 </td>
1306 </tr>
1307 <tr>
1308 <td>&nbsp;</td>
1309 </tr>
1310 <tr>
1311 <td align='right'>
1312 <input type='checkbox' name='wpConfirm' value='1' id='wpConfirm' />
1313 </td>
1314 <td>
1315 <label for='wpConfirm'>{$check}</label>
1316 </td>
1317 </tr>
1318 <tr>
1319 <td>&nbsp;</td>
1320 <td>
1321 <input type='submit' name='wpConfirmB' value=\"{$confirm}\" />
1322 </td>
1323 </tr>
1324 </table>
1325 </form>\n" );
1326
1327 $wgOut->returnToMain( false );
1328 }
1329
1330 # Perform a deletion and output success or failure messages
1331 function doDelete( $reason )
1332 {
1333 global $wgOut, $wgUser, $wgLang;
1334 $fname = 'Article::doDelete';
1335 wfDebug( "$fname\n" );
1336
1337 if ( $this->doDeleteArticle( $reason ) ) {
1338 $deleted = $this->mTitle->getPrefixedText();
1339
1340 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1341 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1342
1343 $sk = $wgUser->getSkin();
1344 $loglink = $sk->makeKnownLink( $wgLang->getNsText(
1345 Namespace::getWikipedia() ) .
1346 ':' . wfMsg( 'dellogpage' ), wfMsg( 'deletionlog' ) );
1347
1348 $text = wfMsg( "deletedtext", $deleted, $loglink );
1349
1350 $wgOut->addHTML( '<p>' . $text . "</p>\n" );
1351 $wgOut->returnToMain( false );
1352 } else {
1353 $wgOut->fatalError( wfMsg( 'cannotdelete' ) );
1354 }
1355 }
1356
1357 # Back-end article deletion
1358 # Deletes the article with database consistency, writes logs, purges caches
1359 # Returns success
1360 function doDeleteArticle( $reason )
1361 {
1362 global $wgUser, $wgLang;
1363 global $wgUseSquid, $wgDeferredUpdateList, $wgInternalServer;
1364
1365 $fname = 'Article::doDeleteArticle';
1366 wfDebug( $fname."\n" );
1367
1368 $ns = $this->mTitle->getNamespace();
1369 $t = wfStrencode( $this->mTitle->getDBkey() );
1370 $id = $this->mTitle->getArticleID();
1371
1372 if ( '' == $t || $id == 0 ) {
1373 return false;
1374 }
1375
1376 $u = new SiteStatsUpdate( 0, 1, -$this->isCountable( $this->getContent( true ) ) );
1377 array_push( $wgDeferredUpdateList, $u );
1378
1379 $linksTo = $this->mTitle->getLinksTo();
1380
1381 # Squid purging
1382 if ( $wgUseSquid ) {
1383 $urls = array(
1384 $this->mTitle->getInternalURL(),
1385 $this->mTitle->getInternalURL( 'history' )
1386 );
1387 foreach ( $linksTo as $linkTo ) {
1388 $urls[] = $linkTo->getInternalURL();
1389 }
1390
1391 $u = new SquidUpdate( $urls );
1392 array_push( $wgDeferredUpdateList, $u );
1393
1394 }
1395
1396 # Client and file cache invalidation
1397 Title::touchArray( $linksTo );
1398
1399 # Move article and history to the "archive" table
1400 $sql = 'INSERT INTO archive (ar_namespace,ar_title,ar_text,' .
1401 'ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit,' .
1402 'ar_flags) SELECT cur_namespace,cur_title,cur_text,cur_comment,' .
1403 'cur_user,cur_user_text,cur_timestamp,cur_minor_edit,0 FROM cur ' .
1404 "WHERE cur_namespace={$ns} AND cur_title='{$t}'";
1405 wfQuery( $sql, DB_WRITE, $fname );
1406
1407 $sql = 'INSERT INTO archive (ar_namespace,ar_title,ar_text,' .
1408 'ar_comment,ar_user,ar_user_text,ar_timestamp,ar_minor_edit,' .
1409 'ar_flags) SELECT old_namespace,old_title,old_text,old_comment,' .
1410 'old_user,old_user_text,old_timestamp,old_minor_edit,old_flags ' .
1411 "FROM old WHERE old_namespace={$ns} AND old_title='{$t}'";
1412 wfQuery( $sql, DB_WRITE, $fname );
1413
1414 # Now that it's safely backed up, delete it
1415
1416 $sql = "DELETE FROM cur WHERE cur_namespace={$ns} AND " .
1417 "cur_title='{$t}'";
1418 wfQuery( $sql, DB_WRITE, $fname );
1419
1420 $sql = "DELETE FROM old WHERE old_namespace={$ns} AND " .
1421 "old_title='{$t}'";
1422 wfQuery( $sql, DB_WRITE, $fname );
1423
1424 $sql = "DELETE FROM recentchanges WHERE rc_namespace={$ns} AND " .
1425 "rc_title='{$t}'";
1426 wfQuery( $sql, DB_WRITE, $fname );
1427
1428 # Finally, clean up the link tables
1429 $t = wfStrencode( $this->mTitle->getPrefixedDBkey() );
1430
1431 Article::onArticleDelete( $this->mTitle );
1432
1433 $sql = 'INSERT INTO brokenlinks (bl_from,bl_to) VALUES ';
1434 $first = true;
1435
1436 foreach ( $linksTo as $titleObj ) {
1437 if ( ! $first ) { $sql .= ','; }
1438 $first = false;
1439 # Get article ID. Efficient because it was loaded into the cache by getLinksTo().
1440 $linkID = $titleObj->getArticleID();
1441 $sql .= "({$linkID},'{$t}')";
1442 }
1443 if ( ! $first ) {
1444 wfQuery( $sql, DB_WRITE, $fname );
1445 }
1446
1447 $sql = "DELETE FROM links WHERE l_to={$id}";
1448 wfQuery( $sql, DB_WRITE, $fname );
1449
1450 $sql = "DELETE FROM links WHERE l_from={$id}";
1451 wfQuery( $sql, DB_WRITE, $fname );
1452
1453 $sql = "DELETE FROM imagelinks WHERE il_from={$id}";
1454 wfQuery( $sql, DB_WRITE, $fname );
1455
1456 $sql = "DELETE FROM brokenlinks WHERE bl_from={$id}";
1457 wfQuery( $sql, DB_WRITE, $fname );
1458
1459 $sql = "DELETE FROM categorylinks WHERE cl_from={$id}";
1460 wfQuery( $sql, DB_WRITE, $fname );
1461
1462 $log = new LogPage( wfMsg( 'dellogpage' ), wfMsg( 'dellogpagetext' ) );
1463 $art = $this->mTitle->getPrefixedText();
1464 $log->addEntry( wfMsg( 'deletedarticle', $art ), $reason );
1465
1466 # Clear the cached article id so the interface doesn't act like we exist
1467 $this->mTitle->resetArticleID( 0 );
1468 $this->mTitle->mArticleID = 0;
1469 return true;
1470 }
1471
1472 function rollback()
1473 {
1474 global $wgUser, $wgLang, $wgOut, $wgRequest, $wgIsMySQL, $wgIsPg;
1475
1476 if ( ! $wgUser->isSysop() ) {
1477 $wgOut->sysopRequired();
1478 return;
1479 }
1480 if ( wfReadOnly() ) {
1481 $wgOut->readOnlyPage( $this->getContent( true ) );
1482 return;
1483 }
1484
1485 # Enhanced rollback, marks edits rc_bot=1
1486 $bot = $wgRequest->getBool( 'bot' );
1487
1488 # Replace all this user's current edits with the next one down
1489 $tt = wfStrencode( $this->mTitle->getDBKey() );
1490 $n = $this->mTitle->getNamespace();
1491
1492 # Get the last editor
1493 $sql = 'SELECT cur_id,cur_user,cur_user_text,cur_comment ' .
1494 "FROM cur WHERE cur_title='{$tt}' AND cur_namespace={$n}";
1495 $res = wfQuery( $sql, DB_READ );
1496 if( ($x = wfNumRows( $res )) != 1 ) {
1497 # Something wrong
1498 $wgOut->addHTML( wfMsg( 'notanarticle' ) );
1499 return;
1500 }
1501 $s = wfFetchObject( $res );
1502 $ut = wfStrencode( $s->cur_user_text );
1503 $uid = $s->cur_user;
1504 $pid = $s->cur_id;
1505
1506 $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
1507 if( $from != $s->cur_user_text ) {
1508 $wgOut->setPageTitle(wfmsg('rollbackfailed'));
1509 $wgOut->addWikiText( wfMsg( 'alreadyrolled',
1510 htmlspecialchars( $this->mTitle->getPrefixedText()),
1511 htmlspecialchars( $from ),
1512 htmlspecialchars( $s->cur_user_text ) ) );
1513 if($s->cur_comment != '') {
1514 $wgOut->addHTML(
1515 wfMsg('editcomment',
1516 htmlspecialchars( $s->cur_comment ) ) );
1517 }
1518 return;
1519 }
1520
1521 # Get the last edit not by this guy
1522
1523 $use_index=$wgIsMySQL?"USE INDEX (name_title_timestamp)":"";
1524 $oldtable=$wgIsPg?'"old"':'old';
1525 $sql = 'SELECT old_text,old_user,old_user_text,old_timestamp,old_flags ' .
1526 "FROM $oldtable {$use_index} " .
1527 "WHERE old_namespace={$n} AND old_title='{$tt}' " .
1528 "AND (old_user <> {$uid} OR old_user_text <> '{$ut}') " .
1529 'ORDER BY inverse_timestamp LIMIT 1';
1530 $res = wfQuery( $sql, DB_READ );
1531 if( wfNumRows( $res ) != 1 ) {
1532 # Something wrong
1533 $wgOut->setPageTitle(wfMsg('rollbackfailed'));
1534 $wgOut->addHTML( wfMsg( 'cantrollback' ) );
1535 return;
1536 }
1537 $s = wfFetchObject( $res );
1538
1539 if ( $bot ) {
1540 # Mark all reverted edits as bot
1541 $sql = 'UPDATE recentchanges SET rc_bot=1 WHERE ' .
1542 "rc_cur_id=$pid AND rc_user=$uid AND rc_timestamp > '{$s->old_timestamp}'";
1543 wfQuery( $sql, DB_WRITE, $fname );
1544 }
1545
1546 # Save it!
1547 $newcomment = wfMsg( 'revertpage', $s->old_user_text, $from );
1548 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
1549 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1550 $wgOut->addHTML( '<h2>' . $newcomment . "</h2>\n<hr />\n" );
1551 $this->updateArticle( Article::getRevisionText( $s ), $newcomment, 1, $this->mTitle->userIsWatching(), $bot );
1552 Article::onArticleEdit( $this->mTitle );
1553 $wgOut->returnToMain( false );
1554 }
1555
1556
1557 # Do standard deferred updates after page view
1558
1559 /* private */ function viewUpdates()
1560 {
1561 global $wgDeferredUpdateList;
1562 if ( 0 != $this->getID() ) {
1563 global $wgDisableCounters;
1564 if( !$wgDisableCounters ) {
1565 Article::incViewCount( $this->getID() );
1566 $u = new SiteStatsUpdate( 1, 0, 0 );
1567 array_push( $wgDeferredUpdateList, $u );
1568 }
1569 $u = new UserTalkUpdate( 0, $this->mTitle->getNamespace(),
1570 $this->mTitle->getDBkey() );
1571 array_push( $wgDeferredUpdateList, $u );
1572 }
1573 }
1574
1575 # Do standard deferred updates after page edit.
1576 # Every 1000th edit, prune the recent changes table.
1577
1578 /* private */ function editUpdates( $text )
1579 {
1580 global $wgDeferredUpdateList, $wgDBname, $wgMemc;
1581 global $wgMessageCache;
1582
1583 wfSeedRandom();
1584 if ( 0 == mt_rand( 0, 999 ) ) {
1585 $cutoff = wfUnix2Timestamp( time() - ( 7 * 86400 ) );
1586 $sql = "DELETE FROM recentchanges WHERE rc_timestamp < '{$cutoff}'";
1587 wfQuery( $sql, DB_WRITE );
1588 }
1589 $id = $this->getID();
1590 $title = $this->mTitle->getPrefixedDBkey();
1591 $shortTitle = $this->mTitle->getDBkey();
1592
1593 $adj = $this->mCountAdjustment;
1594
1595 if ( 0 != $id ) {
1596 $u = new LinksUpdate( $id, $title );
1597 array_push( $wgDeferredUpdateList, $u );
1598 $u = new SiteStatsUpdate( 0, 1, $adj );
1599 array_push( $wgDeferredUpdateList, $u );
1600 $u = new SearchUpdate( $id, $title, $text );
1601 array_push( $wgDeferredUpdateList, $u );
1602
1603 $u = new UserTalkUpdate( 1, $this->mTitle->getNamespace(), $shortTitle );
1604 array_push( $wgDeferredUpdateList, $u );
1605
1606 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1607 $wgMessageCache->replace( $shortTitle, $text );
1608 }
1609 }
1610 }
1611
1612 /* private */ function setOldSubtitle()
1613 {
1614 global $wgLang, $wgOut;
1615
1616 $td = $wgLang->timeanddate( $this->mTimestamp, true );
1617 $r = wfMsg( 'revisionasof', $td );
1618 $wgOut->setSubtitle( "({$r})" );
1619 }
1620
1621 # This function is called right before saving the wikitext,
1622 # so we can do things like signatures and links-in-context.
1623
1624 function preSaveTransform( $text )
1625 {
1626 global $wgParser, $wgUser;
1627 return $wgParser->preSaveTransform( $text, $this->mTitle, $wgUser, ParserOptions::newFromUser( $wgUser ) );
1628 }
1629
1630 /* Caching functions */
1631
1632 # checkLastModified returns true if it has taken care of all
1633 # output to the client that is necessary for this request.
1634 # (that is, it has sent a cached version of the page)
1635 function tryFileCache() {
1636 static $called = false;
1637 if( $called ) {
1638 wfDebug( " tryFileCache() -- called twice!?\n" );
1639 return;
1640 }
1641 $called = true;
1642 if($this->isFileCacheable()) {
1643 $touched = $this->mTouched;
1644 if( $this->mTitle->getPrefixedDBkey() == wfMsg( 'mainpage' ) ) {
1645 # Expire the main page quicker
1646 $expire = wfUnix2Timestamp( time() - 3600 );
1647 $touched = max( $expire, $touched );
1648 }
1649 $cache = new CacheManager( $this->mTitle );
1650 if($cache->isFileCacheGood( $touched )) {
1651 global $wgOut;
1652 wfDebug( " tryFileCache() - about to load\n" );
1653 $cache->loadFromFileCache();
1654 return true;
1655 } else {
1656 wfDebug( " tryFileCache() - starting buffer\n" );
1657 ob_start( array(&$cache, 'saveToFileCache' ) );
1658 }
1659 } else {
1660 wfDebug( " tryFileCache() - not cacheable\n" );
1661 }
1662 }
1663
1664 function isFileCacheable() {
1665 global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
1666 extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
1667
1668 return $wgUseFileCache
1669 and (!$wgShowIPinHeader)
1670 and ($this->getID() != 0)
1671 and ($wgUser->getId() == 0)
1672 and (!$wgUser->getNewtalk())
1673 and ($this->mTitle->getNamespace() != Namespace::getSpecial())
1674 and ($action == 'view')
1675 and (!isset($oldid))
1676 and (!isset($diff))
1677 and (!isset($redirect))
1678 and (!isset($printable))
1679 and (!$this->mRedirectedFrom);
1680 }
1681
1682 # Loads cur_touched and returns a value indicating if it should be used
1683 function checkTouched() {
1684 $id = $this->getID();
1685 $sql = 'SELECT cur_touched,cur_is_redirect FROM cur WHERE cur_id='.$id;
1686 $res = wfQuery( $sql, DB_READ, 'Article::checkTouched' );
1687 if( $s = wfFetchObject( $res ) ) {
1688 $this->mTouched = $s->cur_touched;
1689 return !$s->cur_is_redirect;
1690 } else {
1691 return false;
1692 }
1693 }
1694
1695 # Edit an article without doing all that other stuff
1696 function quickEdit( $text, $comment = '', $minor = 0 ) {
1697 global $wgUser, $wgMwRedir, $wgIsPg;
1698 $fname = 'Article::quickEdit';
1699 wfProfileIn( $fname );
1700
1701 $ns = $this->mTitle->getNamespace();
1702 $dbkey = $this->mTitle->getDBkey();
1703 $encDbKey = wfStrencode( $dbkey );
1704 $timestamp = wfTimestampNow();
1705
1706 # Save to history
1707 $oldtable=$wgIsPg?'"old"':'old';
1708 $sql = "INSERT INTO $oldtable (old_namespace,old_title,old_text,old_comment,old_user,old_user_text,old_timestamp,inverse_timestamp)
1709 SELECT cur_namespace,cur_title,cur_text,cur_comment,cur_user,cur_user_text,cur_timestamp,99999999999999-cur_timestamp
1710 FROM cur WHERE cur_namespace=$ns AND cur_title='$encDbKey'";
1711 wfQuery( $sql, DB_WRITE );
1712
1713 # Use the affected row count to determine if the article is new
1714 $numRows = wfAffectedRows();
1715
1716 # Make an array of fields to be inserted
1717 $fields = array(
1718 'cur_text' => $text,
1719 'cur_timestamp' => $timestamp,
1720 'cur_user' => $wgUser->getID(),
1721 'cur_user_text' => $wgUser->getName(),
1722 'inverse_timestamp' => wfInvertTimestamp( $timestamp ),
1723 'cur_comment' => $comment,
1724 'cur_is_redirect' => $wgMwRedir->matchStart( $text ) ? 1 : 0,
1725 'cur_minor_edit' => intval($minor),
1726 'cur_touched' => $timestamp,
1727 );
1728
1729 if ( $numRows ) {
1730 # Update article
1731 $fields['cur_is_new'] = 0;
1732 wfUpdateArray( 'cur', $fields, array( 'cur_namespace' => $ns, 'cur_title' => $dbkey ), $fname );
1733 } else {
1734 # Insert new article
1735 $fields['cur_is_new'] = 1;
1736 $fields['cur_namespace'] = $ns;
1737 $fields['cur_title'] = $dbkey;
1738 $fields['cur_random'] = $rand = number_format( mt_rand() / mt_getrandmax(), 12, '.', '' );
1739 wfInsertArray( 'cur', $fields, $fname );
1740 }
1741 wfProfileOut( $fname );
1742 }
1743
1744 /* static */ function incViewCount( $id )
1745 {
1746 $id = intval( $id );
1747 global $wgHitcounterUpdateFreq;
1748
1749 if( $wgHitcounterUpdateFreq <= 1 ){ //
1750 wfQuery('UPDATE cur SET cur_counter = cur_counter + 1 ' .
1751 'WHERE cur_id = '.$id, DB_WRITE);
1752 return;
1753 }
1754
1755 # Not important enough to warrant an error page in case of failure
1756 $oldignore = wfIgnoreSQLErrors( true );
1757
1758 wfQuery("INSERT INTO hitcounter (hc_id) VALUES ({$id})", DB_WRITE);
1759
1760 $checkfreq = intval( $wgHitcounterUpdateFreq/25 + 1 );
1761 if( (rand() % $checkfreq != 0) or (wfLastErrno() != 0) ){
1762 # Most of the time (or on SQL errors), skip row count check
1763 wfIgnoreSQLErrors( $oldignore );
1764 return;
1765 }
1766
1767 $res = wfQuery('SELECT COUNT(*) as n FROM hitcounter', DB_WRITE);
1768 $row = wfFetchObject( $res );
1769 $rown = intval( $row->n );
1770 if( $rown >= $wgHitcounterUpdateFreq ){
1771 wfProfileIn( 'Article::incViewCount-collect' );
1772 $old_user_abort = ignore_user_abort( true );
1773
1774 wfQuery('LOCK TABLES hitcounter WRITE', DB_WRITE);
1775 wfQuery('CREATE TEMPORARY TABLE acchits TYPE=HEAP '.
1776 'SELECT hc_id,COUNT(*) AS hc_n FROM hitcounter '.
1777 'GROUP BY hc_id', DB_WRITE);
1778 wfQuery('DELETE FROM hitcounter', DB_WRITE);
1779 wfQuery('UNLOCK TABLES', DB_WRITE);
1780 wfQuery('UPDATE cur,acchits SET cur_counter=cur_counter + hc_n '.
1781 'WHERE cur_id = hc_id', DB_WRITE);
1782 wfQuery('DROP TABLE acchits', DB_WRITE);
1783
1784 ignore_user_abort( $old_user_abort );
1785 wfProfileOut( 'Article::incViewCount-collect' );
1786 }
1787 wfIgnoreSQLErrors( $oldignore );
1788 }
1789
1790 # The onArticle*() functions are supposed to be a kind of hooks
1791 # which should be called whenever any of the specified actions
1792 # are done.
1793 #
1794 # This is a good place to put code to clear caches, for instance.
1795
1796 # This is called on page move and undelete, as well as edit
1797 /* static */ function onArticleCreate($title_obj){
1798 global $wgUseSquid, $wgDeferredUpdateList;
1799
1800 $titles = $title_obj->getBrokenLinksTo();
1801
1802 # Purge squid
1803 if ( $wgUseSquid ) {
1804 $urls = $title_obj->getSquidURLs();
1805 foreach ( $titles as $linkTitle ) {
1806 $urls[] = $linkTitle->getInternalURL();
1807 }
1808 $u = new SquidUpdate( $urls );
1809 array_push( $wgDeferredUpdateList, $u );
1810 }
1811
1812 # Clear persistent link cache
1813 LinkCache::linksccClearBrokenLinksTo( $title_obj->getPrefixedDBkey() );
1814 }
1815
1816 /* static */ function onArticleDelete($title_obj){
1817 LinkCache::linksccClearLinksTo( $title_obj->getArticleID() );
1818 }
1819
1820 /* static */ function onArticleEdit($title_obj){
1821 LinkCache::linksccClearPage( $title_obj->getArticleID() );
1822 }
1823 }
1824
1825 ?>