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