* Add 'charset' to Content-Type headers on various HTTP error responses
[lhc/web/wiklou.git] / includes / EditPage.php
1 <?php
2 /**
3 * Contain the EditPage class
4 */
5
6 /**
7 * Splitting edit page/HTML interface from Article...
8 * The actual database and text munging is still in Article,
9 * but it should get easier to call those from alternate
10 * interfaces.
11 *
12 */
13
14 class EditPage {
15 var $mArticle;
16 var $mTitle;
17 var $mMetaData = '';
18 var $isConflict = false;
19 var $isCssJsSubpage = false;
20 var $deletedSinceEdit = false;
21 var $formtype;
22 var $firsttime;
23 var $lastDelete;
24 var $mTokenOk = false;
25 var $mTriedSave = false;
26 var $tooBig = false;
27 var $kblength = false;
28 var $missingComment = false;
29 var $missingSummary = false;
30 var $allowBlankSummary = false;
31 var $autoSumm = '';
32 var $hookError = '';
33 var $mPreviewTemplates;
34
35 # Form values
36 var $save = false, $preview = false, $diff = false;
37 var $minoredit = false, $watchthis = false, $recreate = false;
38 var $textbox1 = '', $textbox2 = '', $summary = '';
39 var $edittime = '', $section = '', $starttime = '';
40 var $oldid = 0, $editintro = '', $scrolltop = null;
41
42 # Placeholders for text injection by hooks (must be HTML)
43 # extensions should take care to _append_ to the present value
44 public $editFormPageTop; // Before even the preview
45 public $editFormTextTop;
46 public $editFormTextAfterWarn;
47 public $editFormTextAfterTools;
48 public $editFormTextBottom;
49
50 /**
51 * @todo document
52 * @param $article
53 */
54 function EditPage( $article ) {
55 $this->mArticle =& $article;
56 global $wgTitle;
57 $this->mTitle =& $wgTitle;
58
59 # Placeholders for text injection by hooks (empty per default)
60 $this->editFormPageTop =
61 $this->editFormTextTop =
62 $this->editFormTextAfterWarn =
63 $this->editFormTextAfterTools =
64 $this->editFormTextBottom = "";
65 }
66
67 /**
68 * Fetch initial editing page content.
69 */
70 private function getContent() {
71 global $wgOut, $wgRequest, $wgParser;
72
73 # Get variables from query string :P
74 $section = $wgRequest->getVal( 'section' );
75 $preload = $wgRequest->getVal( 'preload' );
76 $undo = $wgRequest->getVal( 'undo' );
77
78 wfProfileIn( __METHOD__ );
79
80 $text = '';
81 if( !$this->mTitle->exists() ) {
82 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
83 # If this is a system message, get the default text.
84 $text = wfMsgWeirdKey ( $this->mTitle->getText() ) ;
85 } else {
86 # If requested, preload some text.
87 $text = $this->getPreloadedText( $preload );
88 }
89 # We used to put MediaWiki:Newarticletext here if
90 # $text was empty at this point.
91 # This is now shown above the edit box instead.
92 } else {
93 // FIXME: may be better to use Revision class directly
94 // But don't mess with it just yet. Article knows how to
95 // fetch the page record from the high-priority server,
96 // which is needed to guarantee we don't pick up lagged
97 // information.
98
99 $text = $this->mArticle->getContent();
100
101 if ( $undo > 0 ) {
102 #Undoing a specific edit overrides section editing; section-editing
103 # doesn't work with undoing.
104 $undorev = Revision::newFromId($undo);
105
106 #Sanity check, make sure it's the right page.
107 # Otherwise, $text will be left as-is.
108 if (!is_null($undorev) && $undorev->getPage() == $this->mArticle->getID()) {
109 $oldrev = $undorev->getPrevious();
110 $undorev_text = $undorev->getText();
111 $oldrev_text = $oldrev->getText();
112 $currev_text = $text;
113
114 #No use doing a merge if it's just a straight revert.
115 if ($currev_text != $undorev_text) {
116 $result = wfMerge($undorev_text, $oldrev_text, $currev_text, $text);
117 } else {
118 $text = $oldrev_text;
119 $result = true;
120 }
121
122 if( $result ) {
123 # Inform the user of our success and set an automatic edit summary
124 $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
125 $this->summary = wfMsgForContent( 'undo-summary', $undo, $undorev->getUserText() );
126 $this->formtype = 'diff';
127 } else {
128 # Warn the user that something went wrong
129 $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
130 }
131
132 }
133 }
134 else if( $section != '' ) {
135 if( $section == 'new' ) {
136 $text = $this->getPreloadedText( $preload );
137 } else {
138 $text = $wgParser->getSection( $text, $section );
139 }
140 }
141 }
142
143 wfProfileOut( __METHOD__ );
144 return $text;
145 }
146
147 /**
148 * Get the contents of a page from its title and remove includeonly tags
149 *
150 * @param $preload String: the title of the page.
151 * @return string The contents of the page.
152 */
153 private function getPreloadedText($preload) {
154 if ( $preload === '' )
155 return '';
156 else {
157 $preloadTitle = Title::newFromText( $preload );
158 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
159 $rev=Revision::newFromTitle($preloadTitle);
160 if ( is_object( $rev ) ) {
161 $text = $rev->getText();
162 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
163 // its own mini-parser! -ævar
164 $text = preg_replace( '~</?includeonly>~', '', $text );
165 return $text;
166 } else
167 return '';
168 }
169 }
170 }
171
172 /**
173 * This is the function that extracts metadata from the article body on the first view.
174 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
175 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
176 */
177 function extractMetaDataFromArticle () {
178 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
179 $this->mMetaData = '' ;
180 if ( !$wgUseMetadataEdit ) return ;
181 if ( $wgMetadataWhitelist == '' ) return ;
182 $s = '' ;
183 $t = $this->getContent();
184
185 # MISSING : <nowiki> filtering
186
187 # Categories and language links
188 $t = explode ( "\n" , $t ) ;
189 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY ) ) ;
190 $cat = $ll = array() ;
191 foreach ( $t AS $key => $x )
192 {
193 $y = trim ( strtolower ( $x ) ) ;
194 while ( substr ( $y , 0 , 2 ) == '[[' )
195 {
196 $y = explode ( ']]' , trim ( $x ) ) ;
197 $first = array_shift ( $y ) ;
198 $first = explode ( ':' , $first ) ;
199 $ns = array_shift ( $first ) ;
200 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
201 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
202 {
203 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
204 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
205 else $ll[] = $add ;
206 $x = implode ( ']]' , $y ) ;
207 $t[$key] = $x ;
208 $y = trim ( strtolower ( $x ) ) ;
209 }
210 }
211 }
212 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
213 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
214 $t = implode ( "\n" , $t ) ;
215
216 # Load whitelist
217 $sat = array () ; # stand-alone-templates; must be lowercase
218 $wl_title = Title::newFromText ( $wgMetadataWhitelist ) ;
219 $wl_article = new Article ( $wl_title ) ;
220 $wl = explode ( "\n" , $wl_article->getContent() ) ;
221 foreach ( $wl AS $x )
222 {
223 $isentry = false ;
224 $x = trim ( $x ) ;
225 while ( substr ( $x , 0 , 1 ) == '*' )
226 {
227 $isentry = true ;
228 $x = trim ( substr ( $x , 1 ) ) ;
229 }
230 if ( $isentry )
231 {
232 $sat[] = strtolower ( $x ) ;
233 }
234
235 }
236
237 # Templates, but only some
238 $t = explode ( '{{' , $t ) ;
239 $tl = array () ;
240 foreach ( $t AS $key => $x )
241 {
242 $y = explode ( '}}' , $x , 2 ) ;
243 if ( count ( $y ) == 2 )
244 {
245 $z = $y[0] ;
246 $z = explode ( '|' , $z ) ;
247 $tn = array_shift ( $z ) ;
248 if ( in_array ( strtolower ( $tn ) , $sat ) )
249 {
250 $tl[] = '{{' . $y[0] . '}}' ;
251 $t[$key] = $y[1] ;
252 $y = explode ( '}}' , $y[1] , 2 ) ;
253 }
254 else $t[$key] = '{{' . $x ;
255 }
256 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
257 else $t[$key] = $x ;
258 }
259 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
260 $t = implode ( '' , $t ) ;
261
262 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
263 $this->mArticle->mContent = $t ;
264 $this->mMetaData = $s ;
265 }
266
267 function submit() {
268 $this->edit();
269 }
270
271 /**
272 * This is the function that gets called for "action=edit". It
273 * sets up various member variables, then passes execution to
274 * another function, usually showEditForm()
275 *
276 * The edit form is self-submitting, so that when things like
277 * preview and edit conflicts occur, we get the same form back
278 * with the extra stuff added. Only when the final submission
279 * is made and all is well do we actually save and redirect to
280 * the newly-edited page.
281 */
282 function edit() {
283 global $wgOut, $wgUser, $wgRequest, $wgTitle;
284 global $wgEmailConfirmToEdit;
285
286 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
287 return;
288
289 $fname = 'EditPage::edit';
290 wfProfileIn( $fname );
291 wfDebug( "$fname: enter\n" );
292
293 // this is not an article
294 $wgOut->setArticleFlag(false);
295
296 $this->importFormData( $wgRequest );
297 $this->firsttime = false;
298
299 if( $this->live ) {
300 $this->livePreview();
301 wfProfileOut( $fname );
302 return;
303 }
304
305 if ( ! $this->mTitle->userCan( 'edit' ) ) {
306 wfDebug( "$fname: user can't edit\n" );
307 $wgOut->readOnlyPage( $this->getContent(), true );
308 wfProfileOut( $fname );
309 return;
310 }
311 wfDebug( "$fname: Checking blocks\n" );
312 if ( !$this->preview && !$this->diff && $wgUser->isBlockedFrom( $this->mTitle, !$this->save ) ) {
313 # When previewing, don't check blocked state - will get caught at save time.
314 # Also, check when starting edition is done against slave to improve performance.
315 wfDebug( "$fname: user is blocked\n" );
316 $this->blockedPage();
317 wfProfileOut( $fname );
318 return;
319 }
320 if ( !$wgUser->isAllowed('edit') ) {
321 if ( $wgUser->isAnon() ) {
322 wfDebug( "$fname: user must log in\n" );
323 $this->userNotLoggedInPage();
324 wfProfileOut( $fname );
325 return;
326 } else {
327 wfDebug( "$fname: read-only page\n" );
328 $wgOut->readOnlyPage( $this->getContent(), true );
329 wfProfileOut( $fname );
330 return;
331 }
332 }
333 if ($wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed()) {
334 wfDebug("$fname: user must confirm e-mail address\n");
335 $this->userNotConfirmedPage();
336 wfProfileOut($fname);
337 return;
338 }
339 if ( !$this->mTitle->userCan( 'create' ) && !$this->mTitle->exists() ) {
340 wfDebug( "$fname: no create permission\n" );
341 $this->noCreatePermission();
342 wfProfileOut( $fname );
343 return;
344 }
345 if ( wfReadOnly() ) {
346 wfDebug( "$fname: read-only mode is engaged\n" );
347 if( $this->save || $this->preview ) {
348 $this->formtype = 'preview';
349 } else if ( $this->diff ) {
350 $this->formtype = 'diff';
351 } else {
352 $wgOut->readOnlyPage( $this->getContent() );
353 wfProfileOut( $fname );
354 return;
355 }
356 } else {
357 if ( $this->save ) {
358 $this->formtype = 'save';
359 } else if ( $this->preview ) {
360 $this->formtype = 'preview';
361 } else if ( $this->diff ) {
362 $this->formtype = 'diff';
363 } else { # First time through
364 $this->firsttime = true;
365 if( $this->previewOnOpen() ) {
366 $this->formtype = 'preview';
367 } else {
368 $this->extractMetaDataFromArticle () ;
369 $this->formtype = 'initial';
370 }
371 }
372 }
373
374 wfProfileIn( "$fname-business-end" );
375
376 $this->isConflict = false;
377 // css / js subpages of user pages get a special treatment
378 $this->isCssJsSubpage = $wgTitle->isCssJsSubpage();
379 $this->isValidCssJsSubpage = $wgTitle->isValidCssJsSubpage();
380
381 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
382 * no matter it's current state
383 */
384 $this->deletedSinceEdit = false;
385 if ( $this->edittime != '' ) {
386 /* Note that we rely on logging table, which hasn't been always there,
387 * but that doesn't matter, because this only applies to brand new
388 * deletes. This is done on every preview and save request. Move it further down
389 * to only perform it on saves
390 */
391 if ( $this->mTitle->isDeleted() ) {
392 $this->lastDelete = $this->getLastDelete();
393 if ( !is_null($this->lastDelete) ) {
394 $deletetime = $this->lastDelete->log_timestamp;
395 if ( ($deletetime - $this->starttime) > 0 ) {
396 $this->deletedSinceEdit = true;
397 }
398 }
399 }
400 }
401
402 if(!$this->mTitle->getArticleID() && ('initial' == $this->formtype || $this->firsttime )) { # new article
403 $this->showIntro();
404 }
405 if( $this->mTitle->isTalkPage() ) {
406 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
407 }
408
409 # Attempt submission here. This will check for edit conflicts,
410 # and redundantly check for locked database, blocked IPs, etc.
411 # that edit() already checked just in case someone tries to sneak
412 # in the back door with a hand-edited submission URL.
413
414 if ( 'save' == $this->formtype ) {
415 if ( !$this->attemptSave() ) {
416 wfProfileOut( "$fname-business-end" );
417 wfProfileOut( $fname );
418 return;
419 }
420 }
421
422 # First time through: get contents, set time for conflict
423 # checking, etc.
424 if ( 'initial' == $this->formtype || $this->firsttime ) {
425 $this->initialiseForm();
426 if( !$this->mTitle->getArticleId() )
427 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
428 }
429
430 $this->showEditForm();
431 wfProfileOut( "$fname-business-end" );
432 wfProfileOut( $fname );
433 }
434
435 /**
436 * Return true if this page should be previewed when the edit form
437 * is initially opened.
438 * @return bool
439 * @private
440 */
441 function previewOnOpen() {
442 global $wgUser;
443 return $this->section != 'new' &&
444 ( ( $wgUser->getOption( 'previewonfirst' ) && $this->mTitle->exists() ) ||
445 ( $this->mTitle->getNamespace() == NS_CATEGORY &&
446 !$this->mTitle->exists() ) );
447 }
448
449 /**
450 * @todo document
451 * @param $request
452 */
453 function importFormData( &$request ) {
454 global $wgLang, $wgUser;
455 $fname = 'EditPage::importFormData';
456 wfProfileIn( $fname );
457
458 if( $request->wasPosted() ) {
459 # These fields need to be checked for encoding.
460 # Also remove trailing whitespace, but don't remove _initial_
461 # whitespace from the text boxes. This may be significant formatting.
462 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
463 $this->textbox2 = $this->safeUnicodeInput( $request, 'wpTextbox2' );
464 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
465 # Truncate for whole multibyte characters. +5 bytes for ellipsis
466 $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
467
468 $this->edittime = $request->getVal( 'wpEdittime' );
469 $this->starttime = $request->getVal( 'wpStarttime' );
470
471 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
472
473 if( is_null( $this->edittime ) ) {
474 # If the form is incomplete, force to preview.
475 wfDebug( "$fname: Form data appears to be incomplete\n" );
476 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
477 $this->preview = true;
478 } else {
479 /* Fallback for live preview */
480 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
481 $this->diff = $request->getCheck( 'wpDiff' );
482
483 // Remember whether a save was requested, so we can indicate
484 // if we forced preview due to session failure.
485 $this->mTriedSave = !$this->preview;
486
487 if ( $this->tokenOk( $request ) ) {
488 # Some browsers will not report any submit button
489 # if the user hits enter in the comment box.
490 # The unmarked state will be assumed to be a save,
491 # if the form seems otherwise complete.
492 wfDebug( "$fname: Passed token check.\n" );
493 } else if ( $this->diff ) {
494 # Failed token check, but only requested "Show Changes".
495 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
496 } else {
497 # Page might be a hack attempt posted from
498 # an external site. Preview instead of saving.
499 wfDebug( "$fname: Failed token check; forcing preview\n" );
500 $this->preview = true;
501 }
502 }
503 $this->save = ! ( $this->preview OR $this->diff );
504 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
505 $this->edittime = null;
506 }
507
508 if( !preg_match( '/^\d{14}$/', $this->starttime )) {
509 $this->starttime = null;
510 }
511
512 $this->recreate = $request->getCheck( 'wpRecreate' );
513
514 $this->minoredit = $request->getCheck( 'wpMinoredit' );
515 $this->watchthis = $request->getCheck( 'wpWatchthis' );
516
517 # Don't force edit summaries when a user is editing their own user or talk page
518 if( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK ) && $this->mTitle->getText() == $wgUser->getName() ) {
519 $this->allowBlankSummary = true;
520 } else {
521 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' );
522 }
523
524 $this->autoSumm = $request->getText( 'wpAutoSummary' );
525 } else {
526 # Not a posted form? Start with nothing.
527 wfDebug( "$fname: Not a posted form.\n" );
528 $this->textbox1 = '';
529 $this->textbox2 = '';
530 $this->mMetaData = '';
531 $this->summary = '';
532 $this->edittime = '';
533 $this->starttime = wfTimestampNow();
534 $this->preview = false;
535 $this->save = false;
536 $this->diff = false;
537 $this->minoredit = false;
538 $this->watchthis = false;
539 $this->recreate = false;
540 }
541
542 $this->oldid = $request->getInt( 'oldid' );
543
544 # Section edit can come from either the form or a link
545 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
546
547 $this->live = $request->getCheck( 'live' );
548 $this->editintro = $request->getText( 'editintro' );
549
550 wfProfileOut( $fname );
551 }
552
553 /**
554 * Make sure the form isn't faking a user's credentials.
555 *
556 * @param $request WebRequest
557 * @return bool
558 * @private
559 */
560 function tokenOk( &$request ) {
561 global $wgUser;
562 if( $wgUser->isAnon() ) {
563 # Anonymous users may not have a session
564 # open. Check for suffix anyway.
565 $this->mTokenOk = ( EDIT_TOKEN_SUFFIX == $request->getVal( 'wpEditToken' ) );
566 } else {
567 $this->mTokenOk = $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
568 }
569 return $this->mTokenOk;
570 }
571
572 /** */
573 function showIntro() {
574 global $wgOut, $wgUser;
575 $addstandardintro=true;
576 if($this->editintro) {
577 $introtitle=Title::newFromText($this->editintro);
578 if(isset($introtitle) && $introtitle->userCanRead()) {
579 $rev=Revision::newFromTitle($introtitle);
580 if($rev) {
581 $wgOut->addSecondaryWikiText($rev->getText());
582 $addstandardintro=false;
583 }
584 }
585 }
586 if($addstandardintro) {
587 if ( $wgUser->isLoggedIn() )
588 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
589 else
590 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
591 }
592 }
593
594 /**
595 * Attempt submission
596 * @return bool false if output is done, true if the rest of the form should be displayed
597 */
598 function attemptSave() {
599 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
600 global $wgMaxArticleSize;
601
602 $fname = 'EditPage::attemptSave';
603 wfProfileIn( $fname );
604 wfProfileIn( "$fname-checks" );
605
606 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
607 {
608 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
609 return false;
610 }
611
612 # Reintegrate metadata
613 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
614 $this->mMetaData = '' ;
615
616 # Check for spam
617 $matches = array();
618 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
619 $this->spamPage ( $matches[0] );
620 wfProfileOut( "$fname-checks" );
621 wfProfileOut( $fname );
622 return false;
623 }
624 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
625 # Error messages or other handling should be performed by the filter function
626 wfProfileOut( $fname );
627 wfProfileOut( "$fname-checks" );
628 return false;
629 }
630 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError ) ) ) {
631 # Error messages etc. could be handled within the hook...
632 wfProfileOut( $fname );
633 wfProfileOut( "$fname-checks" );
634 return false;
635 } elseif( $this->hookError != '' ) {
636 # ...or the hook could be expecting us to produce an error
637 wfProfileOut( "$fname-checks " );
638 wfProfileOut( $fname );
639 return true;
640 }
641 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
642 # Check block state against master, thus 'false'.
643 $this->blockedPage();
644 wfProfileOut( "$fname-checks" );
645 wfProfileOut( $fname );
646 return false;
647 }
648 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
649 if ( $this->kblength > $wgMaxArticleSize ) {
650 // Error will be displayed by showEditForm()
651 $this->tooBig = true;
652 wfProfileOut( "$fname-checks" );
653 wfProfileOut( $fname );
654 return true;
655 }
656
657 if ( !$wgUser->isAllowed('edit') ) {
658 if ( $wgUser->isAnon() ) {
659 $this->userNotLoggedInPage();
660 wfProfileOut( "$fname-checks" );
661 wfProfileOut( $fname );
662 return false;
663 }
664 else {
665 $wgOut->readOnlyPage();
666 wfProfileOut( "$fname-checks" );
667 wfProfileOut( $fname );
668 return false;
669 }
670 }
671
672 if ( wfReadOnly() ) {
673 $wgOut->readOnlyPage();
674 wfProfileOut( "$fname-checks" );
675 wfProfileOut( $fname );
676 return false;
677 }
678 if ( $wgUser->pingLimiter() ) {
679 $wgOut->rateLimited();
680 wfProfileOut( "$fname-checks" );
681 wfProfileOut( $fname );
682 return false;
683 }
684
685 # If the article has been deleted while editing, don't save it without
686 # confirmation
687 if ( $this->deletedSinceEdit && !$this->recreate ) {
688 wfProfileOut( "$fname-checks" );
689 wfProfileOut( $fname );
690 return true;
691 }
692
693 wfProfileOut( "$fname-checks" );
694
695 # If article is new, insert it.
696 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
697 if ( 0 == $aid ) {
698
699 // Late check for create permission, just in case *PARANOIA*
700 if ( !$this->mTitle->userCan( 'create' ) ) {
701 wfDebug( "$fname: no create permission\n" );
702 $this->noCreatePermission();
703 wfProfileOut( $fname );
704 return;
705 }
706
707 # Don't save a new article if it's blank.
708 if ( ( '' == $this->textbox1 ) ) {
709 $wgOut->redirect( $this->mTitle->getFullURL() );
710 wfProfileOut( $fname );
711 return false;
712 }
713
714 $isComment=($this->section=='new');
715 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
716 $this->minoredit, $this->watchthis, false, $isComment);
717
718 wfProfileOut( $fname );
719 return false;
720 }
721
722 # Article exists. Check for edit conflict.
723
724 $this->mArticle->clear(); # Force reload of dates, etc.
725 $this->mArticle->forUpdate( true ); # Lock the article
726
727 if( $this->mArticle->getTimestamp() != $this->edittime ) {
728 $this->isConflict = true;
729 if( $this->section == 'new' ) {
730 if( $this->mArticle->getUserText() == $wgUser->getName() &&
731 $this->mArticle->getComment() == $this->summary ) {
732 // Probably a duplicate submission of a new comment.
733 // This can happen when squid resends a request after
734 // a timeout but the first one actually went through.
735 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
736 } else {
737 // New comment; suppress conflict.
738 $this->isConflict = false;
739 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
740 }
741 }
742 }
743 $userid = $wgUser->getID();
744
745 if ( $this->isConflict) {
746 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
747 $this->mArticle->getTimestamp() . "'\n" );
748 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
749 }
750 else {
751 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
752 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
753 }
754 if( is_null( $text ) ) {
755 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
756 $this->isConflict = true;
757 $text = $this->textbox1;
758 }
759
760 # Suppress edit conflict with self, except for section edits where merging is required.
761 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
762 wfDebug( "Suppressing edit conflict, same user.\n" );
763 $this->isConflict = false;
764 } else {
765 # switch from section editing to normal editing in edit conflict
766 if($this->isConflict) {
767 # Attempt merge
768 if( $this->mergeChangesInto( $text ) ){
769 // Successful merge! Maybe we should tell the user the good news?
770 $this->isConflict = false;
771 wfDebug( "Suppressing edit conflict, successful merge.\n" );
772 } else {
773 $this->section = '';
774 $this->textbox1 = $text;
775 wfDebug( "Keeping edit conflict, failed merge.\n" );
776 }
777 }
778 }
779
780 if ( $this->isConflict ) {
781 wfProfileOut( $fname );
782 return true;
783 }
784
785 $oldtext = $this->mArticle->getContent();
786
787 # Handle the user preference to force summaries here, but not for null edits
788 if( $this->section != 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary')
789 && 0 != strcmp($oldtext, $text) && !Article::getRedirectAutosummary( $text )) {
790 if( md5( $this->summary ) == $this->autoSumm ) {
791 $this->missingSummary = true;
792 wfProfileOut( $fname );
793 return( true );
794 }
795 }
796
797 #And a similar thing for new sections
798 if( $this->section == 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary' ) ) {
799 if (trim($this->summary) == '') {
800 $this->missingSummary = true;
801 wfProfileOut( $fname );
802 return( true );
803 }
804 }
805
806 # All's well
807 wfProfileIn( "$fname-sectionanchor" );
808 $sectionanchor = '';
809 if( $this->section == 'new' ) {
810 if ( $this->textbox1 == '' ) {
811 $this->missingComment = true;
812 return true;
813 }
814 if( $this->summary != '' ) {
815 $sectionanchor = $this->sectionAnchor( $this->summary );
816 }
817 } elseif( $this->section != '' ) {
818 # Try to get a section anchor from the section source, redirect to edited section if header found
819 # XXX: might be better to integrate this into Article::replaceSection
820 # for duplicate heading checking and maybe parsing
821 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
822 # we can't deal with anchors, includes, html etc in the header for now,
823 # headline would need to be parsed to improve this
824 if($hasmatch and strlen($matches[2]) > 0) {
825 $sectionanchor = $this->sectionAnchor( $matches[2] );
826 }
827 }
828 wfProfileOut( "$fname-sectionanchor" );
829
830 // Save errors may fall down to the edit form, but we've now
831 // merged the section into full text. Clear the section field
832 // so that later submission of conflict forms won't try to
833 // replace that into a duplicated mess.
834 $this->textbox1 = $text;
835 $this->section = '';
836
837 // Check for length errors again now that the section is merged in
838 $this->kblength = (int)(strlen( $text ) / 1024);
839 if ( $this->kblength > $wgMaxArticleSize ) {
840 $this->tooBig = true;
841 wfProfileOut( $fname );
842 return true;
843 }
844
845 # update the article here
846 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
847 $this->watchthis, '', $sectionanchor ) ) {
848 wfProfileOut( $fname );
849 return false;
850 } else {
851 $this->isConflict = true;
852 }
853 wfProfileOut( $fname );
854 return true;
855 }
856
857 /**
858 * Initialise form fields in the object
859 * Called on the first invocation, e.g. when a user clicks an edit link
860 */
861 function initialiseForm() {
862 $this->edittime = $this->mArticle->getTimestamp();
863 $this->summary = '';
864 $this->textbox1 = $this->getContent();
865 if ( !$this->mArticle->exists() && $this->mArticle->mTitle->getNamespace() == NS_MEDIAWIKI )
866 $this->textbox1 = wfMsgWeirdKey( $this->mArticle->mTitle->getText() );
867 wfProxyCheck();
868 }
869
870 /**
871 * Send the edit form and related headers to $wgOut
872 * @param $formCallback Optional callable that takes an OutputPage
873 * parameter; will be called during form output
874 * near the top, for captchas and the like.
875 */
876 function showEditForm( $formCallback=null ) {
877 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
878
879 $fname = 'EditPage::showEditForm';
880 wfProfileIn( $fname );
881
882 $sk = $wgUser->getSkin();
883
884 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
885
886 $wgOut->setRobotpolicy( 'noindex,nofollow' );
887
888 # Enabled article-related sidebar, toplinks, etc.
889 $wgOut->setArticleRelated( true );
890
891 if ( $this->isConflict ) {
892 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
893 $wgOut->setPageTitle( $s );
894 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
895
896 $this->textbox2 = $this->textbox1;
897 $this->textbox1 = $this->getContent();
898 $this->edittime = $this->mArticle->getTimestamp();
899 } else {
900
901 if( $this->section != '' ) {
902 if( $this->section == 'new' ) {
903 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
904 } else {
905 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
906 $matches = array();
907 if( !$this->summary && !$this->preview && !$this->diff ) {
908 preg_match( "/^(=+)(.+)\\1/mi",
909 $this->textbox1,
910 $matches );
911 if( !empty( $matches[2] ) ) {
912 $this->summary = "/* ". trim($matches[2])." */ ";
913 }
914 }
915 }
916 } else {
917 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
918 }
919 $wgOut->setPageTitle( $s );
920
921 if ( $this->missingComment ) {
922 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
923 }
924
925 if( $this->missingSummary && $this->section != 'new' ) {
926 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
927 }
928
929 if( $this->missingSummary && $this->section == 'new' ) {
930 $wgOut->addWikiText( wfMsg( 'missingcommentheader' ) );
931 }
932
933 if( !$this->hookError == '' ) {
934 $wgOut->addWikiText( $this->hookError );
935 }
936
937 if ( !$this->checkUnicodeCompliantBrowser() ) {
938 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
939 }
940 if ( isset( $this->mArticle ) && isset( $this->mArticle->mRevision ) ) {
941 // Let sysop know that this will make private content public if saved
942 if( $this->mArticle->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
943 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
944 }
945 if( !$this->mArticle->mRevision->isCurrent() ) {
946 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
947 $wgOut->addWikiText( wfMsg( 'editingold' ) );
948 }
949 }
950 }
951
952 if( wfReadOnly() ) {
953 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
954 } elseif( $wgUser->isAnon() && $this->formtype != 'preview' ) {
955 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
956 } else {
957 if( $this->isCssJsSubpage && $this->formtype != 'preview' ) {
958 # Check the skin exists
959 if( $this->isValidCssJsSubpage ) {
960 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
961 } else {
962 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
963 }
964 }
965 }
966
967 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
968 # Show a warning if editing an interface message
969 $wgOut->addWikiText( wfMsg( 'editinginterface' ) );
970 } elseif( $this->mTitle->isProtected( 'edit' ) ) {
971 # Is the title semi-protected?
972 if( $this->mTitle->isSemiProtected() ) {
973 $notice = wfMsg( 'semiprotectedpagewarning' );
974 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) || $notice == '-' )
975 $notice = '';
976 } else {
977 # It's either cascading protection or regular protection; work out which
978 $cascadeSources = $this->mTitle->getCascadeProtectionSources();
979 if( $cascadeSources && count( $cascadeSources ) > 0 ) {
980 # Cascading protection; explain, and list the titles responsible
981 $notice = wfMsg( 'cascadeprotectedwarning' ) . "\n";
982 foreach( $cascadeSources as $source )
983 $notice .= '* [[:' . $source->getPrefixedText() . "]]\n";
984 } else {
985 # Regular protection
986 $notice = wfMsg( 'protectedpagewarning' );
987 }
988 }
989 $wgOut->addWikiText( $notice );
990 }
991
992 if ( $this->kblength === false ) {
993 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
994 }
995 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
996 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize ) );
997 } elseif( $this->kblength > 29 ) {
998 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ) );
999 }
1000
1001 #need to parse the preview early so that we know which templates are used,
1002 #otherwise users with "show preview after edit box" will get a blank list
1003 if ( $this->formtype == 'preview' ) {
1004 $previewOutput = $this->getPreviewText();
1005 }
1006
1007 $rows = $wgUser->getIntOption( 'rows' );
1008 $cols = $wgUser->getIntOption( 'cols' );
1009
1010 $ew = $wgUser->getOption( 'editwidth' );
1011 if ( $ew ) $ew = " style=\"width:100%\"";
1012 else $ew = '';
1013
1014 $q = 'action=submit';
1015 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1016 $action = $this->mTitle->escapeLocalURL( $q );
1017
1018 $summary = wfMsg('summary');
1019 $subject = wfMsg('subject');
1020
1021 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
1022 wfMsgExt('cancel', array('parseinline')) );
1023 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1024 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1025 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1026 htmlspecialchars( wfMsg( 'newwindow' ) );
1027
1028 global $wgRightsText;
1029 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1030 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
1031 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1032 $wgRightsText ) . "\n</div>";
1033
1034 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
1035 # prepare toolbar for edit buttons
1036 $toolbar = $this->getEditToolbar();
1037 } else {
1038 $toolbar = '';
1039 }
1040
1041 // activate checkboxes if user wants them to be always active
1042 if( !$this->preview && !$this->diff ) {
1043 # Sort out the "watch" checkbox
1044 if( $wgUser->getOption( 'watchdefault' ) ) {
1045 # Watch all edits
1046 $this->watchthis = true;
1047 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1048 # Watch creations
1049 $this->watchthis = true;
1050 } elseif( $this->mTitle->userIsWatching() ) {
1051 # Already watched
1052 $this->watchthis = true;
1053 }
1054
1055 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
1056 }
1057
1058 $wgOut->addHTML( $this->editFormPageTop );
1059
1060 if ( $wgUser->getOption( 'previewontop' ) ) {
1061
1062 if ( 'preview' == $this->formtype ) {
1063 $this->showPreview( $previewOutput );
1064 } else {
1065 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1066 }
1067
1068 if ( 'diff' == $this->formtype ) {
1069 $wgOut->addHTML( $this->getDiff() );
1070 }
1071 }
1072
1073
1074 $wgOut->addHTML( $this->editFormTextTop );
1075
1076 # if this is a comment, show a subject line at the top, which is also the edit summary.
1077 # Otherwise, show a summary field at the bottom
1078 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
1079 if( $this->section == 'new' ) {
1080 $commentsubject="<span id='wpSummaryLabel'><label for='wpSummary'>{$subject}:</label></span>\n<div class='editOptions'>\n<input tabindex='1' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
1081 $editsummary = '';
1082 $subjectpreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1083 $summarypreview = '';
1084 } else {
1085 $commentsubject = '';
1086 $editsummary="<span id='wpSummaryLabel'><label for='wpSummary'>{$summary}:</label></span>\n<div class='editOptions'>\n<input tabindex='2' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
1087 $summarypreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1088 $subjectpreview = '';
1089 }
1090
1091 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1092 if( !$this->preview && !$this->diff ) {
1093 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1094 }
1095 $templates = ($this->preview || $this->section) ? $this->mPreviewTemplates : $this->mArticle->getUsedTemplates();
1096 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != '');
1097
1098 global $wgUseMetadataEdit ;
1099 if ( $wgUseMetadataEdit ) {
1100 $metadata = $this->mMetaData ;
1101 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1102 $top = wfMsgWikiHtml( 'metadata_help' );
1103 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1104 }
1105 else $metadata = "" ;
1106
1107 $hidden = '';
1108 $recreate = '';
1109 if ($this->deletedSinceEdit) {
1110 if ( 'save' != $this->formtype ) {
1111 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1112 } else {
1113 // Hide the toolbar and edit area, use can click preview to get it back
1114 // Add an confirmation checkbox and explanation.
1115 $toolbar = '';
1116 $hidden = 'type="hidden" style="display:none;"';
1117 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
1118 $recreate .=
1119 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1120 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1121 }
1122 }
1123
1124 $tabindex = 2;
1125
1126 $checkboxes = self::getCheckboxes( $tabindex, $sk,
1127 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
1128
1129 $checkboxhtml = implode( $checkboxes, "\n" );
1130
1131 $buttons = $this->getEditButtons( $tabindex );
1132 $buttonshtml = implode( $buttons, "\n" );
1133
1134 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1135 ? '' : Xml::hidden( 'safemode', '1' );
1136
1137 $wgOut->addHTML( <<<END
1138 {$toolbar}
1139 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1140 END
1141 );
1142
1143 if( is_callable( $formCallback ) ) {
1144 call_user_func_array( $formCallback, array( &$wgOut ) );
1145 }
1146
1147 // Put these up at the top to ensure they aren't lost on early form submission
1148 $wgOut->addHTML( "
1149 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1150 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1151 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1152 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1153
1154 $wgOut->addHTML( <<<END
1155 $recreate
1156 {$commentsubject}
1157 {$subjectpreview}
1158 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1159 cols='{$cols}'{$ew} $hidden>
1160 END
1161 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
1162 "
1163 </textarea>
1164 " );
1165
1166 $wgOut->addWikiText( $copywarn );
1167 $wgOut->addHTML( $this->editFormTextAfterWarn );
1168 $wgOut->addHTML( "
1169 {$metadata}
1170 {$editsummary}
1171 {$summarypreview}
1172 {$checkboxhtml}
1173 {$safemodehtml}
1174 ");
1175
1176 $wgOut->addHTML(
1177 "<div class='editButtons'>
1178 {$buttonshtml}
1179 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1180 </div><!-- editButtons -->
1181 </div><!-- editOptions -->");
1182
1183 $wgOut->addHtml( '<div class="mw-editTools">' );
1184 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1185 $wgOut->addHtml( '</div>' );
1186
1187 $wgOut->addHTML( $this->editFormTextAfterTools );
1188
1189 $wgOut->addHTML( "
1190 <div class='templatesUsed'>
1191 {$formattedtemplates}
1192 </div>
1193 " );
1194
1195 /**
1196 * To make it harder for someone to slip a user a page
1197 * which submits an edit form to the wiki without their
1198 * knowledge, a random token is associated with the login
1199 * session. If it's not passed back with the submission,
1200 * we won't save the page, or render user JavaScript and
1201 * CSS previews.
1202 *
1203 * For anon editors, who may not have a session, we just
1204 * include the constant suffix to prevent editing from
1205 * broken text-mangling proxies.
1206 */
1207 if ( $wgUser->isLoggedIn() )
1208 $token = htmlspecialchars( $wgUser->editToken() );
1209 else
1210 $token = EDIT_TOKEN_SUFFIX;
1211 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1212
1213
1214 # If a blank edit summary was previously provided, and the appropriate
1215 # user preference is active, pass a hidden tag here. This will stop the
1216 # user being bounced back more than once in the event that a summary
1217 # is not required.
1218 if( $this->missingSummary ) {
1219 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1220 }
1221
1222 # For a bit more sophisticated detection of blank summaries, hash the
1223 # automatic one and pass that in a hidden field.
1224 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1225 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1226
1227 if ( $this->isConflict ) {
1228 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1229
1230 $de = new DifferenceEngine( $this->mTitle );
1231 $de->setText( $this->textbox2, $this->textbox1 );
1232 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1233
1234 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1235 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1236 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1237 }
1238 $wgOut->addHTML( $this->editFormTextBottom );
1239 $wgOut->addHTML( "</form>\n" );
1240 if ( !$wgUser->getOption( 'previewontop' ) ) {
1241
1242 if ( $this->formtype == 'preview') {
1243 $this->showPreview( $previewOutput );
1244 } else {
1245 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1246 }
1247
1248 if ( $this->formtype == 'diff') {
1249 $wgOut->addHTML( $this->getDiff() );
1250 }
1251
1252 }
1253
1254 wfProfileOut( $fname );
1255 }
1256
1257 /**
1258 * Append preview output to $wgOut.
1259 * Includes category rendering if this is a category page.
1260 *
1261 * @param string $text The HTML to be output for the preview.
1262 */
1263 private function showPreview( $text ) {
1264 global $wgOut;
1265
1266 $wgOut->addHTML( '<div id="wikiPreview">' );
1267 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1268 $this->mArticle->openShowCategory();
1269 }
1270 $wgOut->addHTML( $text );
1271 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1272 $this->mArticle->closeShowCategory();
1273 }
1274 $wgOut->addHTML( '</div>' );
1275 }
1276
1277 /**
1278 * Live Preview lets us fetch rendered preview page content and
1279 * add it to the page without refreshing the whole page.
1280 * If not supported by the browser it will fall through to the normal form
1281 * submission method.
1282 *
1283 * This function outputs a script tag to support live preview, and
1284 * returns an onclick handler which should be added to the attributes
1285 * of the preview button
1286 */
1287 function doLivePreviewScript() {
1288 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1289 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1290 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1291 '"></script>' . "\n" );
1292 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1293 return "return !livePreview(" .
1294 "getElementById('wikiPreview')," .
1295 "editform.wpTextbox1.value," .
1296 '"' . $liveAction . '"' . ")";
1297 }
1298
1299 function getLastDelete() {
1300 $dbr = wfGetDB( DB_SLAVE );
1301 $fname = 'EditPage::getLastDelete';
1302 $res = $dbr->select(
1303 array( 'logging', 'user' ),
1304 array( 'log_type',
1305 'log_action',
1306 'log_timestamp',
1307 'log_user',
1308 'log_namespace',
1309 'log_title',
1310 'log_comment',
1311 'log_params',
1312 'user_name', ),
1313 array( 'log_namespace' => $this->mTitle->getNamespace(),
1314 'log_title' => $this->mTitle->getDBkey(),
1315 'log_type' => 'delete',
1316 'log_action' => 'delete',
1317 'user_id=log_user' ),
1318 $fname,
1319 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1320
1321 if($dbr->numRows($res) == 1) {
1322 while ( $x = $dbr->fetchObject ( $res ) )
1323 $data = $x;
1324 $dbr->freeResult ( $res ) ;
1325 } else {
1326 $data = null;
1327 }
1328 return $data;
1329 }
1330
1331 /**
1332 * @todo document
1333 */
1334 function getPreviewText() {
1335 global $wgOut, $wgUser, $wgTitle, $wgParser;
1336
1337 $fname = 'EditPage::getPreviewText';
1338 wfProfileIn( $fname );
1339
1340 if ( $this->mTriedSave && !$this->mTokenOk ) {
1341 $msg = 'session_fail_preview';
1342 } else {
1343 $msg = 'previewnote';
1344 }
1345 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1346 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1347 if ( $this->isConflict ) {
1348 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1349 }
1350
1351 $parserOptions = ParserOptions::newFromUser( $wgUser );
1352 $parserOptions->setEditSection( false );
1353
1354 global $wgRawHtml;
1355 if( $wgRawHtml && !$this->mTokenOk ) {
1356 // Could be an offsite preview attempt. This is very unsafe if
1357 // HTML is enabled, as it could be an attack.
1358 return $wgOut->parse( "<div class='previewnote'>" .
1359 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1360 }
1361
1362 # don't parse user css/js, show message about preview
1363 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1364
1365 if ( $this->isCssJsSubpage ) {
1366 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1367 $previewtext = wfMsg('usercsspreview');
1368 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1369 $previewtext = wfMsg('userjspreview');
1370 }
1371 $parserOptions->setTidy(true);
1372 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1373 $wgOut->addHTML( $parserOutput->mText );
1374 wfProfileOut( $fname );
1375 return $previewhead;
1376 } else {
1377 $toparse = $this->textbox1;
1378
1379 # If we're adding a comment, we need to show the
1380 # summary as the headline
1381 if($this->section=="new" && $this->summary!="") {
1382 $toparse="== {$this->summary} ==\n\n".$toparse;
1383 }
1384
1385 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1386 $parserOptions->setTidy(true);
1387 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1388 $wgTitle, $parserOptions );
1389
1390 $previewHTML = $parserOutput->getText();
1391 $wgOut->addParserOutputNoText( $parserOutput );
1392
1393 foreach ( $parserOutput->getTemplates() as $ns => $template)
1394 foreach ( array_keys( $template ) as $dbk)
1395 $this->mPreviewTemplates[] = Title::makeTitle($ns, $dbk);
1396
1397 wfProfileOut( $fname );
1398 return $previewhead . $previewHTML;
1399 }
1400 }
1401
1402 /**
1403 * Call the stock "user is blocked" page
1404 */
1405 function blockedPage() {
1406 global $wgOut, $wgUser;
1407 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1408
1409 # If the user made changes, preserve them when showing the markup
1410 # (This happens when a user is blocked during edit, for instance)
1411 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
1412 if( $first ) {
1413 $source = $this->mTitle->exists() ? $this->getContent() : false;
1414 } else {
1415 $source = $this->textbox1;
1416 }
1417
1418 # Spit out the source or the user's modified version
1419 if( $source !== false ) {
1420 $rows = $wgUser->getOption( 'rows' );
1421 $cols = $wgUser->getOption( 'cols' );
1422 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1423 $wgOut->addHtml( '<hr />' );
1424 $wgOut->addWikiText( wfMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() ) );
1425 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1426 }
1427 }
1428
1429 /**
1430 * Produce the stock "please login to edit pages" page
1431 */
1432 function userNotLoggedInPage() {
1433 global $wgUser, $wgOut;
1434 $skin = $wgUser->getSkin();
1435
1436 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1437 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle->getPrefixedUrl() );
1438
1439 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1440 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1441 $wgOut->setArticleRelated( false );
1442
1443 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1444 $wgOut->returnToMain( false, $this->mTitle->getPrefixedUrl() );
1445 }
1446
1447 /**
1448 * Creates a basic error page which informs the user that
1449 * they have to validate their email address before being
1450 * allowed to edit.
1451 */
1452 function userNotConfirmedPage() {
1453 global $wgOut;
1454
1455 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1456 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1457 $wgOut->setArticleRelated( false );
1458
1459 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1460 $wgOut->returnToMain( false );
1461 }
1462
1463 /**
1464 * Produce the stock "your edit contains spam" page
1465 *
1466 * @param $match Text which triggered one or more filters
1467 */
1468 function spamPage( $match = false ) {
1469 global $wgOut;
1470
1471 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1472 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1473 $wgOut->setArticleRelated( false );
1474
1475 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1476 if ( $match )
1477 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1478
1479 $wgOut->returnToMain( false );
1480 }
1481
1482 /**
1483 * @private
1484 * @todo document
1485 */
1486 function mergeChangesInto( &$editText ){
1487 $fname = 'EditPage::mergeChangesInto';
1488 wfProfileIn( $fname );
1489
1490 $db = wfGetDB( DB_MASTER );
1491
1492 // This is the revision the editor started from
1493 $baseRevision = Revision::loadFromTimestamp(
1494 $db, $this->mArticle->mTitle, $this->edittime );
1495 if( is_null( $baseRevision ) ) {
1496 wfProfileOut( $fname );
1497 return false;
1498 }
1499 $baseText = $baseRevision->getText();
1500
1501 // The current state, we want to merge updates into it
1502 $currentRevision = Revision::loadFromTitle(
1503 $db, $this->mArticle->mTitle );
1504 if( is_null( $currentRevision ) ) {
1505 wfProfileOut( $fname );
1506 return false;
1507 }
1508 $currentText = $currentRevision->getText();
1509
1510 $result = '';
1511 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1512 $editText = $result;
1513 wfProfileOut( $fname );
1514 return true;
1515 } else {
1516 wfProfileOut( $fname );
1517 return false;
1518 }
1519 }
1520
1521 /**
1522 * Check if the browser is on a blacklist of user-agents known to
1523 * mangle UTF-8 data on form submission. Returns true if Unicode
1524 * should make it through, false if it's known to be a problem.
1525 * @return bool
1526 * @private
1527 */
1528 function checkUnicodeCompliantBrowser() {
1529 global $wgBrowserBlackList;
1530 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1531 // No User-Agent header sent? Trust it by default...
1532 return true;
1533 }
1534 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1535 foreach ( $wgBrowserBlackList as $browser ) {
1536 if ( preg_match($browser, $currentbrowser) ) {
1537 return false;
1538 }
1539 }
1540 return true;
1541 }
1542
1543 /**
1544 * Format an anchor fragment as it would appear for a given section name
1545 * @param string $text
1546 * @return string
1547 * @private
1548 */
1549 function sectionAnchor( $text ) {
1550 $headline = Sanitizer::decodeCharReferences( $text );
1551 # strip out HTML
1552 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1553 $headline = trim( $headline );
1554 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1555 $replacearray = array(
1556 '%3A' => ':',
1557 '%' => '.'
1558 );
1559 return str_replace(
1560 array_keys( $replacearray ),
1561 array_values( $replacearray ),
1562 $sectionanchor );
1563 }
1564
1565 /**
1566 * Shows a bulletin board style toolbar for common editing functions.
1567 * It can be disabled in the user preferences.
1568 * The necessary JavaScript code can be found in style/wikibits.js.
1569 */
1570 function getEditToolbar() {
1571 global $wgStylePath, $wgContLang, $wgJsMimeType;
1572
1573 /**
1574 * toolarray an array of arrays which each include the filename of
1575 * the button image (without path), the opening tag, the closing tag,
1576 * and optionally a sample text that is inserted between the two when no
1577 * selection is highlighted.
1578 * The tip text is shown when the user moves the mouse over the button.
1579 *
1580 * Already here are accesskeys (key), which are not used yet until someone
1581 * can figure out a way to make them work in IE. However, we should make
1582 * sure these keys are not defined on the edit page.
1583 */
1584 $toolarray = array(
1585 array( 'image' => 'button_bold.png',
1586 'id' => 'mw-editbutton-bold',
1587 'open' => '\\\'\\\'\\\'',
1588 'close' => '\\\'\\\'\\\'',
1589 'sample'=> wfMsg('bold_sample'),
1590 'tip' => wfMsg('bold_tip'),
1591 'key' => 'B'
1592 ),
1593 array( 'image' => 'button_italic.png',
1594 'id' => 'mw-editbutton-italic',
1595 'open' => '\\\'\\\'',
1596 'close' => '\\\'\\\'',
1597 'sample'=> wfMsg('italic_sample'),
1598 'tip' => wfMsg('italic_tip'),
1599 'key' => 'I'
1600 ),
1601 array( 'image' => 'button_link.png',
1602 'id' => 'mw-editbutton-link',
1603 'open' => '[[',
1604 'close' => ']]',
1605 'sample'=> wfMsg('link_sample'),
1606 'tip' => wfMsg('link_tip'),
1607 'key' => 'L'
1608 ),
1609 array( 'image' => 'button_extlink.png',
1610 'id' => 'mw-editbutton-extlink',
1611 'open' => '[',
1612 'close' => ']',
1613 'sample'=> wfMsg('extlink_sample'),
1614 'tip' => wfMsg('extlink_tip'),
1615 'key' => 'X'
1616 ),
1617 array( 'image' => 'button_headline.png',
1618 'id' => 'mw-editbutton-headline',
1619 'open' => "\\n== ",
1620 'close' => " ==\\n",
1621 'sample'=> wfMsg('headline_sample'),
1622 'tip' => wfMsg('headline_tip'),
1623 'key' => 'H'
1624 ),
1625 array( 'image' => 'button_image.png',
1626 'id' => 'mw-editbutton-image',
1627 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).":",
1628 'close' => ']]',
1629 'sample'=> wfMsg('image_sample'),
1630 'tip' => wfMsg('image_tip'),
1631 'key' => 'D'
1632 ),
1633 array( 'image' => 'button_media.png',
1634 'id' => 'mw-editbutton-media',
1635 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1636 'close' => ']]',
1637 'sample'=> wfMsg('media_sample'),
1638 'tip' => wfMsg('media_tip'),
1639 'key' => 'M'
1640 ),
1641 array( 'image' => 'button_math.png',
1642 'id' => 'mw-editbutton-math',
1643 'open' => "<math>",
1644 'close' => "<\\/math>",
1645 'sample'=> wfMsg('math_sample'),
1646 'tip' => wfMsg('math_tip'),
1647 'key' => 'C'
1648 ),
1649 array( 'image' => 'button_nowiki.png',
1650 'id' => 'mw-editbutton-nowiki',
1651 'open' => "<nowiki>",
1652 'close' => "<\\/nowiki>",
1653 'sample'=> wfMsg('nowiki_sample'),
1654 'tip' => wfMsg('nowiki_tip'),
1655 'key' => 'N'
1656 ),
1657 array( 'image' => 'button_sig.png',
1658 'id' => 'mw-editbutton-signature',
1659 'open' => '--~~~~',
1660 'close' => '',
1661 'sample'=> '',
1662 'tip' => wfMsg('sig_tip'),
1663 'key' => 'Y'
1664 ),
1665 array( 'image' => 'button_hr.png',
1666 'id' => 'mw-editbutton-hr',
1667 'open' => "\\n----\\n",
1668 'close' => '',
1669 'sample'=> '',
1670 'tip' => wfMsg('hr_tip'),
1671 'key' => 'R'
1672 )
1673 );
1674 $toolbar = "<div id='toolbar'>\n";
1675 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1676
1677 foreach($toolarray as $tool) {
1678
1679 $cssId = $tool['id'];
1680 $image=$wgStylePath.'/common/images/'.$tool['image'];
1681 $open=$tool['open'];
1682 $close=$tool['close'];
1683 $sample = wfEscapeJsString( $tool['sample'] );
1684
1685 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1686 // Older browsers show a "speedtip" type message only for ALT.
1687 // Ideally these should be different, realistically they
1688 // probably don't need to be.
1689 $tip = wfEscapeJsString( $tool['tip'] );
1690
1691 #$key = $tool["key"];
1692
1693 $toolbar.="addButton('$image','$tip','$open','$close','$sample','$cssId');\n";
1694 }
1695
1696 $toolbar.="/*]]>*/\n</script>";
1697 $toolbar.="\n</div>";
1698 return $toolbar;
1699 }
1700
1701 /**
1702 * Returns an array of html code of the following checkboxes:
1703 * minor and watch
1704 *
1705 * @param $tabindex Current tabindex
1706 * @param $skin Skin object
1707 * @param $checked Array of checkbox => bool, where bool indicates the checked
1708 * status of the checkbox
1709 *
1710 * @return array
1711 */
1712 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1713 global $wgUser;
1714
1715 $checkboxes = array();
1716
1717 $checkboxes['minor'] = '';
1718 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1719 if ( $wgUser->isAllowed('minoredit') ) {
1720 $attribs = array(
1721 'tabindex' => ++$tabindex,
1722 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1723 'id' => 'wpMinoredit',
1724 );
1725 $checkboxes['minor'] =
1726 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1727 "&nbsp;<label for='wpMinoredit'".$skin->tooltipAndAccesskey('minoredit').">{$minorLabel}</label>";
1728 }
1729
1730 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
1731 $checkboxes['watch'] = '';
1732 if ( $wgUser->isLoggedIn() ) {
1733 $attribs = array(
1734 'tabindex' => ++$tabindex,
1735 'accesskey' => wfMsg( 'accesskey-watch' ),
1736 'id' => 'wpWatchthis',
1737 );
1738 $checkboxes['watch'] =
1739 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
1740 "&nbsp;<label for='wpWatchthis'".$skin->tooltipAndAccesskey('watch').">{$watchLabel}</label>";
1741 }
1742 return $checkboxes;
1743 }
1744
1745 /**
1746 * Returns an array of html code of the following buttons:
1747 * save, diff, preview and live
1748 *
1749 * @param $tabindex Current tabindex
1750 *
1751 * @return array
1752 */
1753 public function getEditButtons(&$tabindex) {
1754 global $wgLivePreview, $wgUser;
1755
1756 $buttons = array();
1757
1758 $temp = array(
1759 'id' => 'wpSave',
1760 'name' => 'wpSave',
1761 'type' => 'submit',
1762 'tabindex' => ++$tabindex,
1763 'value' => wfMsg('savearticle'),
1764 'accesskey' => wfMsg('accesskey-save'),
1765 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1766 );
1767 $buttons['save'] = wfElement('input', $temp, '');
1768
1769 ++$tabindex; // use the same for preview and live preview
1770 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1771 $temp = array(
1772 'id' => 'wpPreview',
1773 'name' => 'wpPreview',
1774 'type' => 'submit',
1775 'tabindex' => $tabindex,
1776 'value' => wfMsg('showpreview'),
1777 'accesskey' => '',
1778 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1779 'style' => 'display: none;',
1780 );
1781 $buttons['preview'] = wfElement('input', $temp, '');
1782
1783 $temp = array(
1784 'id' => 'wpLivePreview',
1785 'name' => 'wpLivePreview',
1786 'type' => 'submit',
1787 'tabindex' => $tabindex,
1788 'value' => wfMsg('showlivepreview'),
1789 'accesskey' => wfMsg('accesskey-preview'),
1790 'title' => '',
1791 'onclick' => $this->doLivePreviewScript(),
1792 );
1793 $buttons['live'] = wfElement('input', $temp, '');
1794 } else {
1795 $temp = array(
1796 'id' => 'wpPreview',
1797 'name' => 'wpPreview',
1798 'type' => 'submit',
1799 'tabindex' => $tabindex,
1800 'value' => wfMsg('showpreview'),
1801 'accesskey' => wfMsg('accesskey-preview'),
1802 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1803 );
1804 $buttons['preview'] = wfElement('input', $temp, '');
1805 $buttons['live'] = '';
1806 }
1807
1808 $temp = array(
1809 'id' => 'wpDiff',
1810 'name' => 'wpDiff',
1811 'type' => 'submit',
1812 'tabindex' => ++$tabindex,
1813 'value' => wfMsg('showdiff'),
1814 'accesskey' => wfMsg('accesskey-diff'),
1815 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1816 );
1817 $buttons['diff'] = wfElement('input', $temp, '');
1818
1819 return $buttons;
1820 }
1821
1822 /**
1823 * Output preview text only. This can be sucked into the edit page
1824 * via JavaScript, and saves the server time rendering the skin as
1825 * well as theoretically being more robust on the client (doesn't
1826 * disturb the edit box's undo history, won't eat your text on
1827 * failure, etc).
1828 *
1829 * @todo This doesn't include category or interlanguage links.
1830 * Would need to enhance it a bit, <s>maybe wrap them in XML
1831 * or something...</s> that might also require more skin
1832 * initialization, so check whether that's a problem.
1833 */
1834 function livePreview() {
1835 global $wgOut;
1836 $wgOut->disable();
1837 header( 'Content-type: text/xml; charset=utf-8' );
1838 header( 'Cache-control: no-cache' );
1839
1840 $s =
1841 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
1842 Xml::openElement( 'livepreview' ) .
1843 Xml::element( 'preview', null, $this->getPreviewText() ) .
1844 Xml::element( 'br', array( 'style' => 'clear: both;' ) ) .
1845 Xml::closeElement( 'livepreview' );
1846 echo $s;
1847 }
1848
1849
1850 /**
1851 * Get a diff between the current contents of the edit box and the
1852 * version of the page we're editing from.
1853 *
1854 * If this is a section edit, we'll replace the section as for final
1855 * save and then make a comparison.
1856 *
1857 * @return string HTML
1858 */
1859 function getDiff() {
1860 $oldtext = $this->mArticle->fetchContent();
1861 $newtext = $this->mArticle->replaceSection(
1862 $this->section, $this->textbox1, $this->summary, $this->edittime );
1863 $newtext = $this->mArticle->preSaveTransform( $newtext );
1864 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1865 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1866 if ( $oldtext !== false || $newtext != '' ) {
1867 $de = new DifferenceEngine( $this->mTitle );
1868 $de->setText( $oldtext, $newtext );
1869 $difftext = $de->getDiff( $oldtitle, $newtitle );
1870 } else {
1871 $difftext = '';
1872 }
1873
1874 return '<div id="wikiDiff">' . $difftext . '</div>';
1875 }
1876
1877 /**
1878 * Filter an input field through a Unicode de-armoring process if it
1879 * came from an old browser with known broken Unicode editing issues.
1880 *
1881 * @param WebRequest $request
1882 * @param string $field
1883 * @return string
1884 * @private
1885 */
1886 function safeUnicodeInput( $request, $field ) {
1887 $text = rtrim( $request->getText( $field ) );
1888 return $request->getBool( 'safemode' )
1889 ? $this->unmakesafe( $text )
1890 : $text;
1891 }
1892
1893 /**
1894 * Filter an output field through a Unicode armoring process if it is
1895 * going to an old browser with known broken Unicode editing issues.
1896 *
1897 * @param string $text
1898 * @return string
1899 * @private
1900 */
1901 function safeUnicodeOutput( $text ) {
1902 global $wgContLang;
1903 $codedText = $wgContLang->recodeForEdit( $text );
1904 return $this->checkUnicodeCompliantBrowser()
1905 ? $codedText
1906 : $this->makesafe( $codedText );
1907 }
1908
1909 /**
1910 * A number of web browsers are known to corrupt non-ASCII characters
1911 * in a UTF-8 text editing environment. To protect against this,
1912 * detected browsers will be served an armored version of the text,
1913 * with non-ASCII chars converted to numeric HTML character references.
1914 *
1915 * Preexisting such character references will have a 0 added to them
1916 * to ensure that round-trips do not alter the original data.
1917 *
1918 * @param string $invalue
1919 * @return string
1920 * @private
1921 */
1922 function makesafe( $invalue ) {
1923 // Armor existing references for reversability.
1924 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1925
1926 $bytesleft = 0;
1927 $result = "";
1928 $working = 0;
1929 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1930 $bytevalue = ord( $invalue{$i} );
1931 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1932 $result .= chr( $bytevalue );
1933 $bytesleft = 0;
1934 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1935 $working = $working << 6;
1936 $working += ($bytevalue & 0x3F);
1937 $bytesleft--;
1938 if( $bytesleft <= 0 ) {
1939 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1940 }
1941 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1942 $working = $bytevalue & 0x1F;
1943 $bytesleft = 1;
1944 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1945 $working = $bytevalue & 0x0F;
1946 $bytesleft = 2;
1947 } else { //1111 0xxx
1948 $working = $bytevalue & 0x07;
1949 $bytesleft = 3;
1950 }
1951 }
1952 return $result;
1953 }
1954
1955 /**
1956 * Reverse the previously applied transliteration of non-ASCII characters
1957 * back to UTF-8. Used to protect data from corruption by broken web browsers
1958 * as listed in $wgBrowserBlackList.
1959 *
1960 * @param string $invalue
1961 * @return string
1962 * @private
1963 */
1964 function unmakesafe( $invalue ) {
1965 $result = "";
1966 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1967 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
1968 $i += 3;
1969 $hexstring = "";
1970 do {
1971 $hexstring .= $invalue{$i};
1972 $i++;
1973 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1974
1975 // Do some sanity checks. These aren't needed for reversability,
1976 // but should help keep the breakage down if the editor
1977 // breaks one of the entities whilst editing.
1978 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1979 $codepoint = hexdec($hexstring);
1980 $result .= codepointToUtf8( $codepoint );
1981 } else {
1982 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1983 }
1984 } else {
1985 $result .= substr( $invalue, $i, 1 );
1986 }
1987 }
1988 // reverse the transform that we made for reversability reasons.
1989 return strtr( $result, array( "&#x0" => "&#x" ) );
1990 }
1991
1992 function noCreatePermission() {
1993 global $wgOut;
1994 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
1995 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
1996 }
1997
1998 }
1999
2000 ?>