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