Optional feature : 'Ajax show editors' based on an idea by Tim Starling
[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 )
941 && isset( $this->mArticle->mRevision )
942 && !$this->mArticle->mRevision->isCurrent() ) {
943 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
944 $wgOut->addWikiText( wfMsg( 'editingold' ) );
945 }
946 }
947
948 if( wfReadOnly() ) {
949 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
950 } elseif( $wgUser->isAnon() && $this->formtype != 'preview' ) {
951 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
952 } else {
953 if( $this->isCssJsSubpage && $this->formtype != 'preview' ) {
954 # Check the skin exists
955 if( $this->isValidCssJsSubpage ) {
956 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
957 } else {
958 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
959 }
960 }
961 }
962
963 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
964 # Show a warning if editing an interface message
965 $wgOut->addWikiText( wfMsg( 'editinginterface' ) );
966 } elseif( $this->mTitle->isProtected( 'edit' ) ) {
967 # Is the title semi-protected?
968 if( $this->mTitle->isSemiProtected() ) {
969 $notice = wfMsg( 'semiprotectedpagewarning' );
970 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) || $notice == '-' )
971 $notice = '';
972 } else {
973 # It's either cascading protection or regular protection; work out which
974 $cascadeSources = $this->mTitle->getCascadeProtectionSources();
975 if( $cascadeSources && count( $cascadeSources ) > 0 ) {
976 # Cascading protection; explain, and list the titles responsible
977 $notice = wfMsg( 'cascadeprotectedwarning' ) . "\n";
978 foreach( $cascadeSources as $source )
979 $notice .= '* [[:' . $source->getPrefixedText() . "]]\n";
980 } else {
981 # Regular protection
982 $notice = wfMsg( 'protectedpagewarning' );
983 }
984 }
985 $wgOut->addWikiText( $notice );
986 }
987
988 if ( $this->kblength === false ) {
989 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
990 }
991 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
992 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize ) );
993 } elseif( $this->kblength > 29 ) {
994 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ) );
995 }
996
997 #need to parse the preview early so that we know which templates are used,
998 #otherwise users with "show preview after edit box" will get a blank list
999 if ( $this->formtype == 'preview' ) {
1000 $previewOutput = $this->getPreviewText();
1001 }
1002
1003 $rows = $wgUser->getIntOption( 'rows' );
1004 $cols = $wgUser->getIntOption( 'cols' );
1005
1006 $ew = $wgUser->getOption( 'editwidth' );
1007 if ( $ew ) $ew = " style=\"width:100%\"";
1008 else $ew = '';
1009
1010 $q = 'action=submit';
1011 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1012 $action = $this->mTitle->escapeLocalURL( $q );
1013
1014 $summary = wfMsg('summary');
1015 $subject = wfMsg('subject');
1016 $minor = wfMsgExt('minoredit', array('parseinline'));
1017 $watchthis = wfMsgExt('watchthis', array('parseinline'));
1018
1019 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
1020 wfMsgExt('cancel', array('parseinline')) );
1021 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1022 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1023 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1024 htmlspecialchars( wfMsg( 'newwindow' ) );
1025
1026 global $wgRightsText;
1027 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1028 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
1029 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1030 $wgRightsText ) . "\n</div>";
1031
1032 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
1033 # prepare toolbar for edit buttons
1034 $toolbar = $this->getEditToolbar();
1035 } else {
1036 $toolbar = '';
1037 }
1038
1039 // activate checkboxes if user wants them to be always active
1040 if( !$this->preview && !$this->diff ) {
1041 # Sort out the "watch" checkbox
1042 if( $wgUser->getOption( 'watchdefault' ) ) {
1043 # Watch all edits
1044 $this->watchthis = true;
1045 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1046 # Watch creations
1047 $this->watchthis = true;
1048 } elseif( $this->mTitle->userIsWatching() ) {
1049 # Already watched
1050 $this->watchthis = true;
1051 }
1052
1053 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
1054 }
1055
1056 $minoredithtml = '';
1057
1058 if ( $wgUser->isAllowed('minoredit') ) {
1059 $minoredithtml =
1060 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
1061 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />\n".
1062 "<label for='wpMinoredit'".$sk->tooltipAndAccesskey('minoredit').">{$minor}</label>\n";
1063 }
1064
1065 $watchhtml = '';
1066
1067 if ( $wgUser->isLoggedIn() ) {
1068 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
1069 ($this->watchthis?" checked='checked'":"").
1070 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />\n".
1071 "<label for='wpWatchthis'".$sk->tooltipAndAccesskey('watch').">{$watchthis}</label>\n";
1072 }
1073
1074 $checkboxhtml = $minoredithtml . $watchhtml;
1075
1076 $wgOut->addHTML( $this->editFormPageTop );
1077
1078 if ( $wgUser->getOption( 'previewontop' ) ) {
1079
1080 if ( 'preview' == $this->formtype ) {
1081 $this->showPreview( $previewOutput );
1082 } else {
1083 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1084 }
1085
1086 if ( 'diff' == $this->formtype ) {
1087 $wgOut->addHTML( $this->getDiff() );
1088 }
1089 }
1090
1091
1092 $wgOut->addHTML( $this->editFormTextTop );
1093
1094 # if this is a comment, show a subject line at the top, which is also the edit summary.
1095 # Otherwise, show a summary field at the bottom
1096 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
1097 if( $this->section == 'new' ) {
1098 $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 />";
1099 $editsummary = '';
1100 $subjectpreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1101 $summarypreview = '';
1102 } else {
1103 $commentsubject = '';
1104 $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 />";
1105 $summarypreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1106 $subjectpreview = '';
1107 }
1108
1109 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1110 if( !$this->preview && !$this->diff ) {
1111 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1112 }
1113 $templates = ($this->preview || $this->section) ? $this->mPreviewTemplates : $this->mArticle->getUsedTemplates();
1114 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != '');
1115
1116
1117 global $wgAjaxShowEditors ;
1118 if ( $wgAjaxShowEditors && isset( $this->mArticle )
1119 && isset( $this->mArticle->mRevision ) ) {
1120 global $wgJsMimeType, $wgStylePath, $wgStyleVersion;
1121 $wgOut->addScript( "<script type=\"{$wgJsMimeType}\" src=\"{$wgStylePath}/common/ajaxshoweditors.js?$wgStyleVersion\"></script>\n" );
1122 $wgOut->addWikiText(
1123 '<div id="ajax-se"><p id="ajax-se-title">'.wfMsg('ajax-se-title').'</p>'
1124 . '<p id="ajax-se-editors">'. wfMsg('ajax-se-pending') . '</p>'
1125 . '</div>'
1126 );
1127 }
1128
1129 global $wgUseMetadataEdit ;
1130 if ( $wgUseMetadataEdit ) {
1131 $metadata = $this->mMetaData ;
1132 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1133 $top = wfMsgWikiHtml( 'metadata_help' );
1134 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1135 }
1136 else $metadata = "" ;
1137
1138 $hidden = '';
1139 $recreate = '';
1140 if ($this->deletedSinceEdit) {
1141 if ( 'save' != $this->formtype ) {
1142 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1143 } else {
1144 // Hide the toolbar and edit area, use can click preview to get it back
1145 // Add an confirmation checkbox and explanation.
1146 $toolbar = '';
1147 $hidden = 'type="hidden" style="display:none;"';
1148 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
1149 $recreate .=
1150 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1151 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1152 }
1153 }
1154
1155 $temp = array(
1156 'id' => 'wpSave',
1157 'name' => 'wpSave',
1158 'type' => 'submit',
1159 'tabindex' => '5',
1160 'value' => wfMsg('savearticle'),
1161 'accesskey' => wfMsg('accesskey-save'),
1162 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1163 );
1164 $buttons['save'] = wfElement('input', $temp, '');
1165 $temp = array(
1166 'id' => 'wpDiff',
1167 'name' => 'wpDiff',
1168 'type' => 'submit',
1169 'tabindex' => '7',
1170 'value' => wfMsg('showdiff'),
1171 'accesskey' => wfMsg('accesskey-diff'),
1172 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1173 );
1174 $buttons['diff'] = wfElement('input', $temp, '');
1175
1176 global $wgLivePreview;
1177 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1178 $temp = array(
1179 'id' => 'wpPreview',
1180 'name' => 'wpPreview',
1181 'type' => 'submit',
1182 'tabindex' => '6',
1183 'value' => wfMsg('showpreview'),
1184 'accesskey' => '',
1185 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1186 'style' => 'display: none;',
1187 );
1188 $buttons['preview'] = wfElement('input', $temp, '');
1189 $temp = array(
1190 'id' => 'wpLivePreview',
1191 'name' => 'wpLivePreview',
1192 'type' => 'submit',
1193 'tabindex' => '6',
1194 'value' => wfMsg('showlivepreview'),
1195 'accesskey' => wfMsg('accesskey-preview'),
1196 'title' => '',
1197 'onclick' => $this->doLivePreviewScript(),
1198 );
1199 $buttons['live'] = wfElement('input', $temp, '');
1200 } else {
1201 $temp = array(
1202 'id' => 'wpPreview',
1203 'name' => 'wpPreview',
1204 'type' => 'submit',
1205 'tabindex' => '6',
1206 'value' => wfMsg('showpreview'),
1207 'accesskey' => wfMsg('accesskey-preview'),
1208 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1209 );
1210 $buttons['preview'] = wfElement('input', $temp, '');
1211 $buttons['live'] = '';
1212 }
1213
1214 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1215 ? ""
1216 : "<input type='hidden' name=\"safemode\" value='1' />\n";
1217
1218 $wgOut->addHTML( <<<END
1219 {$toolbar}
1220 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1221 END
1222 );
1223
1224 if( is_callable( $formCallback ) ) {
1225 call_user_func_array( $formCallback, array( &$wgOut ) );
1226 }
1227
1228 // Put these up at the top to ensure they aren't lost on early form submission
1229 $wgOut->addHTML( "
1230 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1231 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1232 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1233 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1234
1235 $wgOut->addHTML( <<<END
1236 $recreate
1237 {$commentsubject}
1238 {$subjectpreview}
1239 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1240 cols='{$cols}'{$ew} $hidden>
1241 END
1242 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
1243 "
1244 </textarea>
1245 " );
1246
1247 $wgOut->addWikiText( $copywarn );
1248 $wgOut->addHTML( $this->editFormTextAfterWarn );
1249 $wgOut->addHTML( "
1250 {$metadata}
1251 {$editsummary}
1252 {$summarypreview}
1253 {$checkboxhtml}
1254 {$safemodehtml}
1255 ");
1256
1257 $wgOut->addHTML(
1258 "<div class='editButtons'>
1259 {$buttons['save']}
1260 {$buttons['preview']}
1261 {$buttons['live']}
1262 {$buttons['diff']}
1263 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1264 </div><!-- editButtons -->
1265 </div><!-- editOptions -->");
1266
1267 $wgOut->addHtml( '<div class="mw-editTools">' );
1268 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1269 $wgOut->addHtml( '</div>' );
1270
1271 $wgOut->addHTML( $this->editFormTextAfterTools );
1272
1273 $wgOut->addHTML( "
1274 <div class='templatesUsed'>
1275 {$formattedtemplates}
1276 </div>
1277 " );
1278
1279 /**
1280 * To make it harder for someone to slip a user a page
1281 * which submits an edit form to the wiki without their
1282 * knowledge, a random token is associated with the login
1283 * session. If it's not passed back with the submission,
1284 * we won't save the page, or render user JavaScript and
1285 * CSS previews.
1286 *
1287 * For anon editors, who may not have a session, we just
1288 * include the constant suffix to prevent editing from
1289 * broken text-mangling proxies.
1290 */
1291 if ( $wgUser->isLoggedIn() )
1292 $token = htmlspecialchars( $wgUser->editToken() );
1293 else
1294 $token = EDIT_TOKEN_SUFFIX;
1295 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1296
1297
1298 # If a blank edit summary was previously provided, and the appropriate
1299 # user preference is active, pass a hidden tag here. This will stop the
1300 # user being bounced back more than once in the event that a summary
1301 # is not required.
1302 if( $this->missingSummary ) {
1303 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1304 }
1305
1306 # For a bit more sophisticated detection of blank summaries, hash the
1307 # automatic one and pass that in a hidden field.
1308 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1309 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1310
1311 if ( $this->isConflict ) {
1312 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1313
1314 $de = new DifferenceEngine( $this->mTitle );
1315 $de->setText( $this->textbox2, $this->textbox1 );
1316 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1317
1318 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1319 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1320 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1321 }
1322 $wgOut->addHTML( $this->editFormTextBottom );
1323 $wgOut->addHTML( "</form>\n" );
1324 if ( !$wgUser->getOption( 'previewontop' ) ) {
1325
1326 if ( $this->formtype == 'preview') {
1327 $this->showPreview( $previewOutput );
1328 } else {
1329 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1330 }
1331
1332 if ( $this->formtype == 'diff') {
1333 $wgOut->addHTML( $this->getDiff() );
1334 }
1335
1336 }
1337
1338 wfProfileOut( $fname );
1339 }
1340
1341 /**
1342 * Append preview output to $wgOut.
1343 * Includes category rendering if this is a category page.
1344 *
1345 * @param string $text The HTML to be output for the preview.
1346 */
1347 private function showPreview( $text ) {
1348 global $wgOut;
1349
1350 $wgOut->addHTML( '<div id="wikiPreview">' );
1351 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1352 $this->mArticle->openShowCategory();
1353 }
1354 $wgOut->addHTML( $text );
1355 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1356 $this->mArticle->closeShowCategory();
1357 }
1358 $wgOut->addHTML( '</div>' );
1359 }
1360
1361 /**
1362 * Live Preview lets us fetch rendered preview page content and
1363 * add it to the page without refreshing the whole page.
1364 * If not supported by the browser it will fall through to the normal form
1365 * submission method.
1366 *
1367 * This function outputs a script tag to support live preview, and
1368 * returns an onclick handler which should be added to the attributes
1369 * of the preview button
1370 */
1371 function doLivePreviewScript() {
1372 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1373 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1374 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1375 '"></script>' . "\n" );
1376 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1377 return "return !livePreview(" .
1378 "getElementById('wikiPreview')," .
1379 "editform.wpTextbox1.value," .
1380 '"' . $liveAction . '"' . ")";
1381 }
1382
1383 function getLastDelete() {
1384 $dbr =& wfGetDB( DB_SLAVE );
1385 $fname = 'EditPage::getLastDelete';
1386 $res = $dbr->select(
1387 array( 'logging', 'user' ),
1388 array( 'log_type',
1389 'log_action',
1390 'log_timestamp',
1391 'log_user',
1392 'log_namespace',
1393 'log_title',
1394 'log_comment',
1395 'log_params',
1396 'user_name', ),
1397 array( 'log_namespace' => $this->mTitle->getNamespace(),
1398 'log_title' => $this->mTitle->getDBkey(),
1399 'log_type' => 'delete',
1400 'log_action' => 'delete',
1401 'user_id=log_user' ),
1402 $fname,
1403 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1404
1405 if($dbr->numRows($res) == 1) {
1406 while ( $x = $dbr->fetchObject ( $res ) )
1407 $data = $x;
1408 $dbr->freeResult ( $res ) ;
1409 } else {
1410 $data = null;
1411 }
1412 return $data;
1413 }
1414
1415 /**
1416 * @todo document
1417 */
1418 function getPreviewText() {
1419 global $wgOut, $wgUser, $wgTitle, $wgParser;
1420
1421 $fname = 'EditPage::getPreviewText';
1422 wfProfileIn( $fname );
1423
1424 if ( $this->mTriedSave && !$this->mTokenOk ) {
1425 $msg = 'session_fail_preview';
1426 } else {
1427 $msg = 'previewnote';
1428 }
1429 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1430 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1431 if ( $this->isConflict ) {
1432 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1433 }
1434
1435 $parserOptions = ParserOptions::newFromUser( $wgUser );
1436 $parserOptions->setEditSection( false );
1437
1438 global $wgRawHtml;
1439 if( $wgRawHtml && !$this->mTokenOk ) {
1440 // Could be an offsite preview attempt. This is very unsafe if
1441 // HTML is enabled, as it could be an attack.
1442 return $wgOut->parse( "<div class='previewnote'>" .
1443 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1444 }
1445
1446 # don't parse user css/js, show message about preview
1447 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1448
1449 if ( $this->isCssJsSubpage ) {
1450 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1451 $previewtext = wfMsg('usercsspreview');
1452 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1453 $previewtext = wfMsg('userjspreview');
1454 }
1455 $parserOptions->setTidy(true);
1456 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1457 $wgOut->addHTML( $parserOutput->mText );
1458 wfProfileOut( $fname );
1459 return $previewhead;
1460 } else {
1461 $toparse = $this->textbox1;
1462
1463 # If we're adding a comment, we need to show the
1464 # summary as the headline
1465 if($this->section=="new" && $this->summary!="") {
1466 $toparse="== {$this->summary} ==\n\n".$toparse;
1467 }
1468
1469 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1470 $parserOptions->setTidy(true);
1471 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1472 $wgTitle, $parserOptions );
1473
1474 $previewHTML = $parserOutput->getText();
1475 $wgOut->addParserOutputNoText( $parserOutput );
1476
1477 foreach ( $parserOutput->getTemplates() as $ns => $template)
1478 foreach ( array_keys( $template ) as $dbk)
1479 $this->mPreviewTemplates[] = Title::makeTitle($ns, $dbk);
1480
1481 wfProfileOut( $fname );
1482 return $previewhead . $previewHTML;
1483 }
1484 }
1485
1486 /**
1487 * Call the stock "user is blocked" page
1488 */
1489 function blockedPage() {
1490 global $wgOut, $wgUser;
1491 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1492
1493 # If the user made changes, preserve them when showing the markup
1494 # (This happens when a user is blocked during edit, for instance)
1495 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
1496 if( $first ) {
1497 $source = $this->mTitle->exists() ? $this->getContent() : false;
1498 } else {
1499 $source = $this->textbox1;
1500 }
1501
1502 # Spit out the source or the user's modified version
1503 if( $source !== false ) {
1504 $rows = $wgUser->getOption( 'rows' );
1505 $cols = $wgUser->getOption( 'cols' );
1506 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1507 $wgOut->addHtml( '<hr />' );
1508 $wgOut->addWikiText( wfMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() ) );
1509 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1510 }
1511 }
1512
1513 /**
1514 * Produce the stock "please login to edit pages" page
1515 */
1516 function userNotLoggedInPage() {
1517 global $wgUser, $wgOut;
1518 $skin = $wgUser->getSkin();
1519
1520 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1521 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle->getPrefixedUrl() );
1522
1523 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1524 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1525 $wgOut->setArticleRelated( false );
1526
1527 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1528 $wgOut->returnToMain( false, $this->mTitle->getPrefixedUrl() );
1529 }
1530
1531 /**
1532 * Creates a basic error page which informs the user that
1533 * they have to validate their email address before being
1534 * allowed to edit.
1535 */
1536 function userNotConfirmedPage() {
1537 global $wgOut;
1538
1539 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1540 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1541 $wgOut->setArticleRelated( false );
1542
1543 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1544 $wgOut->returnToMain( false );
1545 }
1546
1547 /**
1548 * Produce the stock "your edit contains spam" page
1549 *
1550 * @param $match Text which triggered one or more filters
1551 */
1552 function spamPage( $match = false ) {
1553 global $wgOut;
1554
1555 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1556 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1557 $wgOut->setArticleRelated( false );
1558
1559 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1560 if ( $match )
1561 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1562
1563 $wgOut->returnToMain( false );
1564 }
1565
1566 /**
1567 * @private
1568 * @todo document
1569 */
1570 function mergeChangesInto( &$editText ){
1571 $fname = 'EditPage::mergeChangesInto';
1572 wfProfileIn( $fname );
1573
1574 $db =& wfGetDB( DB_MASTER );
1575
1576 // This is the revision the editor started from
1577 $baseRevision = Revision::loadFromTimestamp(
1578 $db, $this->mArticle->mTitle, $this->edittime );
1579 if( is_null( $baseRevision ) ) {
1580 wfProfileOut( $fname );
1581 return false;
1582 }
1583 $baseText = $baseRevision->getText();
1584
1585 // The current state, we want to merge updates into it
1586 $currentRevision = Revision::loadFromTitle(
1587 $db, $this->mArticle->mTitle );
1588 if( is_null( $currentRevision ) ) {
1589 wfProfileOut( $fname );
1590 return false;
1591 }
1592 $currentText = $currentRevision->getText();
1593
1594 $result = '';
1595 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1596 $editText = $result;
1597 wfProfileOut( $fname );
1598 return true;
1599 } else {
1600 wfProfileOut( $fname );
1601 return false;
1602 }
1603 }
1604
1605 /**
1606 * Check if the browser is on a blacklist of user-agents known to
1607 * mangle UTF-8 data on form submission. Returns true if Unicode
1608 * should make it through, false if it's known to be a problem.
1609 * @return bool
1610 * @private
1611 */
1612 function checkUnicodeCompliantBrowser() {
1613 global $wgBrowserBlackList;
1614 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1615 // No User-Agent header sent? Trust it by default...
1616 return true;
1617 }
1618 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1619 foreach ( $wgBrowserBlackList as $browser ) {
1620 if ( preg_match($browser, $currentbrowser) ) {
1621 return false;
1622 }
1623 }
1624 return true;
1625 }
1626
1627 /**
1628 * Format an anchor fragment as it would appear for a given section name
1629 * @param string $text
1630 * @return string
1631 * @private
1632 */
1633 function sectionAnchor( $text ) {
1634 $headline = Sanitizer::decodeCharReferences( $text );
1635 # strip out HTML
1636 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1637 $headline = trim( $headline );
1638 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1639 $replacearray = array(
1640 '%3A' => ':',
1641 '%' => '.'
1642 );
1643 return str_replace(
1644 array_keys( $replacearray ),
1645 array_values( $replacearray ),
1646 $sectionanchor );
1647 }
1648
1649 /**
1650 * Shows a bulletin board style toolbar for common editing functions.
1651 * It can be disabled in the user preferences.
1652 * The necessary JavaScript code can be found in style/wikibits.js.
1653 */
1654 function getEditToolbar() {
1655 global $wgStylePath, $wgContLang, $wgJsMimeType;
1656
1657 /**
1658 * toolarray an array of arrays which each include the filename of
1659 * the button image (without path), the opening tag, the closing tag,
1660 * and optionally a sample text that is inserted between the two when no
1661 * selection is highlighted.
1662 * The tip text is shown when the user moves the mouse over the button.
1663 *
1664 * Already here are accesskeys (key), which are not used yet until someone
1665 * can figure out a way to make them work in IE. However, we should make
1666 * sure these keys are not defined on the edit page.
1667 */
1668 $toolarray=array(
1669 array( 'image'=>'button_bold.png',
1670 'open' => '\\\'\\\'\\\'',
1671 'close' => '\\\'\\\'\\\'',
1672 'sample'=> wfMsg('bold_sample'),
1673 'tip' => wfMsg('bold_tip'),
1674 'key' => 'B'
1675 ),
1676 array( 'image'=>'button_italic.png',
1677 'open' => '\\\'\\\'',
1678 'close' => '\\\'\\\'',
1679 'sample'=> wfMsg('italic_sample'),
1680 'tip' => wfMsg('italic_tip'),
1681 'key' => 'I'
1682 ),
1683 array( 'image'=>'button_link.png',
1684 'open' => '[[',
1685 'close' => ']]',
1686 'sample'=> wfMsg('link_sample'),
1687 'tip' => wfMsg('link_tip'),
1688 'key' => 'L'
1689 ),
1690 array( 'image'=>'button_extlink.png',
1691 'open' => '[',
1692 'close' => ']',
1693 'sample'=> wfMsg('extlink_sample'),
1694 'tip' => wfMsg('extlink_tip'),
1695 'key' => 'X'
1696 ),
1697 array( 'image'=>'button_headline.png',
1698 'open' => "\\n== ",
1699 'close' => " ==\\n",
1700 'sample'=> wfMsg('headline_sample'),
1701 'tip' => wfMsg('headline_tip'),
1702 'key' => 'H'
1703 ),
1704 array( 'image'=>'button_image.png',
1705 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).":",
1706 'close' => ']]',
1707 'sample'=> wfMsg('image_sample'),
1708 'tip' => wfMsg('image_tip'),
1709 'key' => 'D'
1710 ),
1711 array( 'image' =>'button_media.png',
1712 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1713 'close' => ']]',
1714 'sample'=> wfMsg('media_sample'),
1715 'tip' => wfMsg('media_tip'),
1716 'key' => 'M'
1717 ),
1718 array( 'image' =>'button_math.png',
1719 'open' => "<math>",
1720 'close' => "<\\/math>",
1721 'sample'=> wfMsg('math_sample'),
1722 'tip' => wfMsg('math_tip'),
1723 'key' => 'C'
1724 ),
1725 array( 'image' =>'button_nowiki.png',
1726 'open' => "<nowiki>",
1727 'close' => "<\\/nowiki>",
1728 'sample'=> wfMsg('nowiki_sample'),
1729 'tip' => wfMsg('nowiki_tip'),
1730 'key' => 'N'
1731 ),
1732 array( 'image' =>'button_sig.png',
1733 'open' => '--~~~~',
1734 'close' => '',
1735 'sample'=> '',
1736 'tip' => wfMsg('sig_tip'),
1737 'key' => 'Y'
1738 ),
1739 array( 'image' =>'button_hr.png',
1740 'open' => "\\n----\\n",
1741 'close' => '',
1742 'sample'=> '',
1743 'tip' => wfMsg('hr_tip'),
1744 'key' => 'R'
1745 )
1746 );
1747 $toolbar = "<div id='toolbar'>\n";
1748 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1749
1750 foreach($toolarray as $tool) {
1751
1752 $image=$wgStylePath.'/common/images/'.$tool['image'];
1753 $open=$tool['open'];
1754 $close=$tool['close'];
1755 $sample = wfEscapeJsString( $tool['sample'] );
1756
1757 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1758 // Older browsers show a "speedtip" type message only for ALT.
1759 // Ideally these should be different, realistically they
1760 // probably don't need to be.
1761 $tip = wfEscapeJsString( $tool['tip'] );
1762
1763 #$key = $tool["key"];
1764
1765 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1766 }
1767
1768 $toolbar.="/*]]>*/\n</script>";
1769 $toolbar.="\n</div>";
1770 return $toolbar;
1771 }
1772
1773 /**
1774 * Output preview text only. This can be sucked into the edit page
1775 * via JavaScript, and saves the server time rendering the skin as
1776 * well as theoretically being more robust on the client (doesn't
1777 * disturb the edit box's undo history, won't eat your text on
1778 * failure, etc).
1779 *
1780 * @todo This doesn't include category or interlanguage links.
1781 * Would need to enhance it a bit, maybe wrap them in XML
1782 * or something... that might also require more skin
1783 * initialization, so check whether that's a problem.
1784 */
1785 function livePreview() {
1786 global $wgOut;
1787 $wgOut->disable();
1788 header( 'Content-type: text/xml' );
1789 header( 'Cache-control: no-cache' );
1790 # FIXME
1791 echo $this->getPreviewText( );
1792 /* To not shake screen up and down between preview and live-preview */
1793 echo "<br style=\"clear:both;\" />\n";
1794 }
1795
1796
1797 /**
1798 * Get a diff between the current contents of the edit box and the
1799 * version of the page we're editing from.
1800 *
1801 * If this is a section edit, we'll replace the section as for final
1802 * save and then make a comparison.
1803 *
1804 * @return string HTML
1805 */
1806 function getDiff() {
1807 $oldtext = $this->mArticle->fetchContent();
1808 $newtext = $this->mArticle->replaceSection(
1809 $this->section, $this->textbox1, $this->summary, $this->edittime );
1810 $newtext = $this->mArticle->preSaveTransform( $newtext );
1811 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1812 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1813 if ( $oldtext !== false || $newtext != '' ) {
1814 $de = new DifferenceEngine( $this->mTitle );
1815 $de->setText( $oldtext, $newtext );
1816 $difftext = $de->getDiff( $oldtitle, $newtitle );
1817 } else {
1818 $difftext = '';
1819 }
1820
1821 return '<div id="wikiDiff">' . $difftext . '</div>';
1822 }
1823
1824 /**
1825 * Filter an input field through a Unicode de-armoring process if it
1826 * came from an old browser with known broken Unicode editing issues.
1827 *
1828 * @param WebRequest $request
1829 * @param string $field
1830 * @return string
1831 * @private
1832 */
1833 function safeUnicodeInput( $request, $field ) {
1834 $text = rtrim( $request->getText( $field ) );
1835 return $request->getBool( 'safemode' )
1836 ? $this->unmakesafe( $text )
1837 : $text;
1838 }
1839
1840 /**
1841 * Filter an output field through a Unicode armoring process if it is
1842 * going to an old browser with known broken Unicode editing issues.
1843 *
1844 * @param string $text
1845 * @return string
1846 * @private
1847 */
1848 function safeUnicodeOutput( $text ) {
1849 global $wgContLang;
1850 $codedText = $wgContLang->recodeForEdit( $text );
1851 return $this->checkUnicodeCompliantBrowser()
1852 ? $codedText
1853 : $this->makesafe( $codedText );
1854 }
1855
1856 /**
1857 * A number of web browsers are known to corrupt non-ASCII characters
1858 * in a UTF-8 text editing environment. To protect against this,
1859 * detected browsers will be served an armored version of the text,
1860 * with non-ASCII chars converted to numeric HTML character references.
1861 *
1862 * Preexisting such character references will have a 0 added to them
1863 * to ensure that round-trips do not alter the original data.
1864 *
1865 * @param string $invalue
1866 * @return string
1867 * @private
1868 */
1869 function makesafe( $invalue ) {
1870 // Armor existing references for reversability.
1871 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1872
1873 $bytesleft = 0;
1874 $result = "";
1875 $working = 0;
1876 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1877 $bytevalue = ord( $invalue{$i} );
1878 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1879 $result .= chr( $bytevalue );
1880 $bytesleft = 0;
1881 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1882 $working = $working << 6;
1883 $working += ($bytevalue & 0x3F);
1884 $bytesleft--;
1885 if( $bytesleft <= 0 ) {
1886 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1887 }
1888 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1889 $working = $bytevalue & 0x1F;
1890 $bytesleft = 1;
1891 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1892 $working = $bytevalue & 0x0F;
1893 $bytesleft = 2;
1894 } else { //1111 0xxx
1895 $working = $bytevalue & 0x07;
1896 $bytesleft = 3;
1897 }
1898 }
1899 return $result;
1900 }
1901
1902 /**
1903 * Reverse the previously applied transliteration of non-ASCII characters
1904 * back to UTF-8. Used to protect data from corruption by broken web browsers
1905 * as listed in $wgBrowserBlackList.
1906 *
1907 * @param string $invalue
1908 * @return string
1909 * @private
1910 */
1911 function unmakesafe( $invalue ) {
1912 $result = "";
1913 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1914 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
1915 $i += 3;
1916 $hexstring = "";
1917 do {
1918 $hexstring .= $invalue{$i};
1919 $i++;
1920 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1921
1922 // Do some sanity checks. These aren't needed for reversability,
1923 // but should help keep the breakage down if the editor
1924 // breaks one of the entities whilst editing.
1925 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1926 $codepoint = hexdec($hexstring);
1927 $result .= codepointToUtf8( $codepoint );
1928 } else {
1929 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1930 }
1931 } else {
1932 $result .= substr( $invalue, $i, 1 );
1933 }
1934 }
1935 // reverse the transform that we made for reversability reasons.
1936 return strtr( $result, array( "&#x0" => "&#x" ) );
1937 }
1938
1939 function noCreatePermission() {
1940 global $wgOut;
1941 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
1942 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
1943 }
1944
1945 }
1946
1947 ?>