3 * Contain the EditPage class
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
20 var $isConflict = false;
21 var $isCssJsSubpage = false;
22 var $deletedSinceEdit = false;
29 var $save = false, $preview = false, $diff = false;
30 var $minoredit = false, $watchthis = false, $recreate = false;
31 var $textbox1 = '', $textbox2 = '', $summary = '';
32 var $edittime = '', $section = '', $starttime = '';
33 var $oldid = 0, $editintro = '', $scrolltop = null;
39 function EditPage( $article ) {
40 $this->mArticle
=& $article;
42 $this->mTitle
=& $wgTitle;
46 * This is the function that extracts metadata from the article body on the first view.
47 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
48 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
50 function extractMetaDataFromArticle () {
51 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
52 $this->mMetaData
= '' ;
53 if ( !$wgUseMetadataEdit ) return ;
54 if ( $wgMetadataWhitelist == '' ) return ;
56 $t = $this->mArticle
->getContent();
58 # MISSING : <nowiki> filtering
60 # Categories and language links
61 $t = explode ( "\n" , $t ) ;
62 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY
) ) ;
63 $cat = $ll = array() ;
64 foreach ( $t AS $key => $x )
66 $y = trim ( strtolower ( $x ) ) ;
67 while ( substr ( $y , 0 , 2 ) == '[[' )
69 $y = explode ( ']]' , trim ( $x ) ) ;
70 $first = array_shift ( $y ) ;
71 $first = explode ( ':' , $first ) ;
72 $ns = array_shift ( $first ) ;
73 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
74 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
76 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
77 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
79 $x = implode ( ']]' , $y ) ;
81 $y = trim ( strtolower ( $x ) ) ;
85 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
86 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
87 $t = implode ( "\n" , $t ) ;
90 $sat = array () ; # stand-alone-templates; must be lowercase
91 $wl_title = Title
::newFromText ( $wgMetadataWhitelist ) ;
92 $wl_article = new Article ( $wl_title ) ;
93 $wl = explode ( "\n" , $wl_article->getContent() ) ;
98 while ( substr ( $x , 0 , 1 ) == '*' )
101 $x = trim ( substr ( $x , 1 ) ) ;
105 $sat[] = strtolower ( $x ) ;
110 # Templates, but only some
111 $t = explode ( '{{' , $t ) ;
113 foreach ( $t AS $key => $x )
115 $y = explode ( '}}' , $x , 2 ) ;
116 if ( count ( $y ) == 2 )
119 $z = explode ( '|' , $z ) ;
120 $tn = array_shift ( $z ) ;
121 if ( in_array ( strtolower ( $tn ) , $sat ) )
123 $tl[] = '{{' . $y[0] . '}}' ;
125 $y = explode ( '}}' , $y[1] , 2 ) ;
127 else $t[$key] = '{{' . $x ;
129 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
132 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
133 $t = implode ( '' , $t ) ;
135 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
136 $this->mArticle
->mContent
= $t ;
137 $this->mMetaData
= $s ;
145 * This is the function that gets called for "action=edit". It
146 * sets up various member variables, then passes execution to
147 * another function, usually showEditForm()
149 * The edit form is self-submitting, so that when things like
150 * preview and edit conflicts occur, we get the same form back
151 * with the extra stuff added. Only when the final submission
152 * is made and all is well do we actually save and redirect to
153 * the newly-edited page.
156 global $wgOut, $wgUser, $wgRequest, $wgTitle,
157 $wgEmailConfirmToEdit;
159 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
162 $fname = 'EditPage::edit';
163 wfProfileIn( $fname );
164 wfDebug( "$fname: enter\n" );
166 // this is not an article
167 $wgOut->setArticleFlag(false);
169 $this->importFormData( $wgRequest );
170 $this->firsttime
= false;
173 $this->livePreview();
174 wfProfileOut( $fname );
178 if ( ! $this->mTitle
->userCanEdit() ) {
179 wfDebug( "$fname: user can't edit\n" );
180 $wgOut->readOnlyPage( $this->mArticle
->getContent(), true );
181 wfProfileOut( $fname );
184 wfDebug( "$fname: Checking blocks\n" );
185 if ( !$this->preview
&& !$this->diff
&& $wgUser->isBlockedFrom( $this->mTitle
, !$this->save
) ) {
186 # When previewing, don't check blocked state - will get caught at save time.
187 # Also, check when starting edition is done against slave to improve performance.
188 wfDebug( "$fname: user is blocked\n" );
189 $wgOut->blockedPage();
190 wfProfileOut( $fname );
193 if ( !$wgUser->isAllowed('edit') ) {
194 if ( $wgUser->isAnon() ) {
195 wfDebug( "$fname: user must log in\n" );
196 $this->userNotLoggedInPage();
197 wfProfileOut( $fname );
200 wfDebug( "$fname: read-only page\n" );
201 $wgOut->readOnlyPage( $this->mArticle
->getContent(), true );
202 wfProfileOut( $fname );
206 if ($wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed()) {
207 wfDebug("$fname: user must confirm e-mail address\n");
208 $this->userNotConfirmedPage();
209 wfProfileOut($fname);
212 if ( !$this->mTitle
->userCan( 'create' ) && !$this->mTitle
->exists() ) {
213 wfDebug( "$fname: no create permission\n" );
214 $this->noCreatePermission();
215 wfProfileOut( $fname );
218 if ( wfReadOnly() ) {
219 wfDebug( "$fname: read-only mode is engaged\n" );
220 if( $this->save ||
$this->preview
) {
221 $this->formtype
= 'preview';
222 } else if ( $this->diff
) {
223 $this->formtype
= 'diff';
225 $wgOut->readOnlyPage( $this->mArticle
->getContent() );
226 wfProfileOut( $fname );
231 $this->formtype
= 'save';
232 } else if ( $this->preview
) {
233 $this->formtype
= 'preview';
234 } else if ( $this->diff
) {
235 $this->formtype
= 'diff';
236 } else { # First time through
237 $this->firsttime
= true;
238 if( $this->previewOnOpen() ) {
239 $this->formtype
= 'preview';
241 $this->extractMetaDataFromArticle () ;
242 $this->formtype
= 'initial';
247 wfProfileIn( "$fname-business-end" );
249 $this->isConflict
= false;
250 // css / js subpages of user pages get a special treatment
251 $this->isCssJsSubpage
= $wgTitle->isCssJsSubpage();
253 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
254 * no matter it's current state
256 $this->deletedSinceEdit
= false;
257 if ( $this->edittime
!= '' ) {
258 /* Note that we rely on logging table, which hasn't been always there,
259 * but that doesn't matter, because this only applies to brand new
260 * deletes. This is done on every preview and save request. Move it further down
261 * to only perform it on saves
263 if ( $this->mTitle
->isDeleted() ) {
264 $this->lastDelete
= $this->getLastDelete();
265 if ( !is_null($this->lastDelete
) ) {
266 $deletetime = $this->lastDelete
->log_timestamp
;
267 if ( ($deletetime - $this->starttime
) > 0 ) {
268 $this->deletedSinceEdit
= true;
274 if(!$this->mTitle
->getArticleID() && ('initial' == $this->formtype ||
$this->firsttime
)) { # new article
277 if( $this->mTitle
->isTalkPage() ) {
278 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
281 # Attempt submission here. This will check for edit conflicts,
282 # and redundantly check for locked database, blocked IPs, etc.
283 # that edit() already checked just in case someone tries to sneak
284 # in the back door with a hand-edited submission URL.
286 if ( 'save' == $this->formtype
) {
287 if ( !$this->attemptSave() ) {
288 wfProfileOut( "$fname-business-end" );
289 wfProfileOut( $fname );
294 # First time through: get contents, set time for conflict
296 if ( 'initial' == $this->formtype ||
$this->firsttime
) {
297 $this->initialiseForm();
300 $this->showEditForm();
301 wfProfileOut( "$fname-business-end" );
302 wfProfileOut( $fname );
306 * Return true if this page should be previewed when the edit form
307 * is initially opened.
311 function previewOnOpen() {
313 return $this->section
!= 'new' &&
314 ( ( $wgUser->getOption( 'previewonfirst' ) && $this->mTitle
->exists() ) ||
315 ( $this->mTitle
->getNamespace() == NS_CATEGORY
&&
316 !$this->mTitle
->exists() ) );
322 function importFormData( &$request ) {
324 $fname = 'EditPage::importFormData';
325 wfProfileIn( $fname );
327 if( $request->wasPosted() ) {
328 # These fields need to be checked for encoding.
329 # Also remove trailing whitespace, but don't remove _initial_
330 # whitespace from the text boxes. This may be significant formatting.
331 $this->textbox1
= $this->safeUnicodeInput( $request, 'wpTextbox1' );
332 $this->textbox2
= $this->safeUnicodeInput( $request, 'wpTextbox2' );
333 $this->mMetaData
= rtrim( $request->getText( 'metadata' ) );
334 # Truncate for whole multibyte characters. +5 bytes for ellipsis
335 $this->summary
= $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
337 $this->edittime
= $request->getVal( 'wpEdittime' );
338 $this->starttime
= $request->getVal( 'wpStarttime' );
340 $this->scrolltop
= $request->getIntOrNull( 'wpScrolltop' );
342 if( is_null( $this->edittime
) ) {
343 # If the form is incomplete, force to preview.
344 wfDebug( "$fname: Form data appears to be incomplete\n" );
345 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
346 $this->preview
= true;
348 $this->preview
= $request->getCheck( 'wpPreview' );
349 $this->diff
= $request->getCheck( 'wpDiff' );
351 if( !$this->preview
) {
352 if ( $this->tokenOk( $request ) ) {
353 # Some browsers will not report any submit button
354 # if the user hits enter in the comment box.
355 # The unmarked state will be assumed to be a save,
356 # if the form seems otherwise complete.
357 wfDebug( "$fname: Passed token check.\n" );
359 # Page might be a hack attempt posted from
360 # an external site. Preview instead of saving.
361 wfDebug( "$fname: Failed token check; forcing preview\n" );
362 $this->preview
= true;
366 $this->save
= ! ( $this->preview
OR $this->diff
);
367 if( !preg_match( '/^\d{14}$/', $this->edittime
)) {
368 $this->edittime
= null;
371 if( !preg_match( '/^\d{14}$/', $this->starttime
)) {
372 $this->starttime
= null;
375 $this->recreate
= $request->getCheck( 'wpRecreate' );
377 $this->minoredit
= $request->getCheck( 'wpMinoredit' );
378 $this->watchthis
= $request->getCheck( 'wpWatchthis' );
380 # Not a posted form? Start with nothing.
381 wfDebug( "$fname: Not a posted form.\n" );
382 $this->textbox1
= '';
383 $this->textbox2
= '';
384 $this->mMetaData
= '';
386 $this->edittime
= '';
387 $this->starttime
= wfTimestampNow();
388 $this->preview
= false;
391 $this->minoredit
= false;
392 $this->watchthis
= false;
393 $this->recreate
= false;
396 $this->oldid
= $request->getInt( 'oldid' );
398 # Section edit can come from either the form or a link
399 $this->section
= $request->getVal( 'wpSection', $request->getVal( 'section' ) );
401 $this->live
= $request->getCheck( 'live' );
402 $this->editintro
= $request->getText( 'editintro' );
404 wfProfileOut( $fname );
408 * Make sure the form isn't faking a user's credentials.
410 * @param WebRequest $request
414 function tokenOk( &$request ) {
416 if( $wgUser->isAnon() ) {
417 # Anonymous users may not have a session
418 # open. Don't tokenize.
419 $this->mTokenOk
= true;
421 $this->mTokenOk
= $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
423 return $this->mTokenOk
;
426 function showIntro() {
427 global $wgOut, $wgUser;
428 $addstandardintro=true;
429 if($this->editintro
) {
430 $introtitle=Title
::newFromText($this->editintro
);
431 if(isset($introtitle) && $introtitle->userCanRead()) {
432 $rev=Revision
::newFromTitle($introtitle);
434 $wgOut->addSecondaryWikiText($rev->getText());
435 $addstandardintro=false;
439 if($addstandardintro) {
440 if ( $wgUser->isLoggedIn() )
441 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
443 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
449 * @return bool false if output is done, true if the rest of the form should be displayed
451 function attemptSave() {
452 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
454 $fname = 'EditPage::attemptSave';
455 wfProfileIn( $fname );
456 wfProfileIn( "$fname-checks" );
458 # Reintegrate metadata
459 if ( $this->mMetaData
!= '' ) $this->textbox1
.= "\n" . $this->mMetaData
;
460 $this->mMetaData
= '' ;
463 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1
, $matches ) ) {
464 $this->spamPage ( $matches[0] );
465 wfProfileOut( "$fname-checks" );
466 wfProfileOut( $fname );
469 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle
, $this->textbox1
, $this->section
) ) {
470 # Error messages or other handling should be performed by the filter function
471 wfProfileOut( $fname );
472 wfProfileOut( "$fname-checks" );
475 if ( !wfRunHooks( 'EditFilter', array( &$this, $this->textbox1
, $this->section
) ) ) {
476 # Error messages or other handling should be performed by the filter function
477 wfProfileOut( $fname );
478 wfProfileOut( "$fname-checks" );
481 if ( $wgUser->isBlockedFrom( $this->mTitle
, false ) ) {
482 # Check block state against master, thus 'false'.
483 $this->blockedIPpage();
484 wfProfileOut( "$fname-checks" );
485 wfProfileOut( $fname );
489 if ( !$wgUser->isAllowed('edit') ) {
490 if ( $wgUser->isAnon() ) {
491 $this->userNotLoggedInPage();
492 wfProfileOut( "$fname-checks" );
493 wfProfileOut( $fname );
497 $wgOut->readOnlyPage();
498 wfProfileOut( "$fname-checks" );
499 wfProfileOut( $fname );
504 if ( wfReadOnly() ) {
505 $wgOut->readOnlyPage();
506 wfProfileOut( "$fname-checks" );
507 wfProfileOut( $fname );
510 if ( $wgUser->pingLimiter() ) {
511 $wgOut->rateLimited();
512 wfProfileOut( "$fname-checks" );
513 wfProfileOut( $fname );
517 # If the article has been deleted while editing, don't save it without
519 if ( $this->deletedSinceEdit
&& !$this->recreate
) {
520 wfProfileOut( "$fname-checks" );
521 wfProfileOut( $fname );
525 wfProfileOut( "$fname-checks" );
527 # If article is new, insert it.
528 $aid = $this->mTitle
->getArticleID( GAID_FOR_UPDATE
);
530 // Late check for create permission, just in case *PARANOIA*
531 if ( !$this->mTitle
->userCan( 'create' ) ) {
532 wfDebug( "$fname: no create permission\n" );
533 $this->noCreatePermission();
534 wfProfileOut( $fname );
538 # Don't save a new article if it's blank.
539 if ( ( '' == $this->textbox1
) ) {
540 $wgOut->redirect( $this->mTitle
->getFullURL() );
541 wfProfileOut( $fname );
545 $isComment=($this->section
=='new');
546 $this->mArticle
->insertNewArticle( $this->textbox1
, $this->summary
,
547 $this->minoredit
, $this->watchthis
, false, $isComment);
549 wfProfileOut( $fname );
553 # Article exists. Check for edit conflict.
555 $this->mArticle
->clear(); # Force reload of dates, etc.
556 $this->mArticle
->forUpdate( true ); # Lock the article
558 if( $this->mArticle
->getTimestamp() != $this->edittime
) {
559 $this->isConflict
= true;
560 if( $this->section
== 'new' ) {
561 if( $this->mArticle
->getUserText() == $wgUser->getName() &&
562 $this->mArticle
->getComment() == $this->summary
) {
563 // Probably a duplicate submission of a new comment.
564 // This can happen when squid resends a request after
565 // a timeout but the first one actually went through.
566 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
568 // New comment; suppress conflict.
569 $this->isConflict
= false;
570 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
574 $userid = $wgUser->getID();
576 if ( $this->isConflict
) {
577 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
578 $this->mArticle
->getTimestamp() . "'\n" );
579 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
582 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
583 $text = $this->mArticle
->replaceSection( $this->section
, $this->textbox1
, $this->summary
);
585 if( is_null( $text ) ) {
586 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
587 $this->isConflict
= true;
588 $text = $this->textbox1
;
591 # Suppress edit conflict with self, except for section edits where merging is required.
592 if ( ( $this->section
== '' ) && ( 0 != $userid ) && ( $this->mArticle
->getUser() == $userid ) ) {
593 wfDebug( "Suppressing edit conflict, same user.\n" );
594 $this->isConflict
= false;
596 # switch from section editing to normal editing in edit conflict
597 if($this->isConflict
) {
599 if( $this->mergeChangesInto( $text ) ){
600 // Successful merge! Maybe we should tell the user the good news?
601 $this->isConflict
= false;
602 wfDebug( "Suppressing edit conflict, successful merge.\n" );
605 $this->textbox1
= $text;
606 wfDebug( "Keeping edit conflict, failed merge.\n" );
611 if ( $this->isConflict
) {
612 wfProfileOut( $fname );
617 wfProfileIn( "$fname-sectionanchor" );
619 if( $this->section
== 'new' ) {
620 if( $this->summary
!= '' ) {
621 $sectionanchor = $this->sectionAnchor( $this->summary
);
623 } elseif( $this->section
!= '' ) {
624 # Try to get a section anchor from the section source, redirect to edited section if header found
625 # XXX: might be better to integrate this into Article::replaceSection
626 # for duplicate heading checking and maybe parsing
627 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1
, $matches );
628 # we can't deal with anchors, includes, html etc in the header for now,
629 # headline would need to be parsed to improve this
630 if($hasmatch and strlen($matches[2]) > 0) {
631 $sectionanchor = $this->sectionAnchor( $matches[2] );
634 wfProfileOut( "$fname-sectionanchor" );
636 // Save errors may fall down to the edit form, but we've now
637 // merged the section into full text. Clear the section field
638 // so that later submission of conflict forms won't try to
639 // replace that into a duplicated mess.
640 $this->textbox1
= $text;
643 # update the article here
644 if( $this->mArticle
->updateArticle( $text, $this->summary
, $this->minoredit
,
645 $this->watchthis
, '', $sectionanchor ) ) {
646 wfProfileOut( $fname );
649 $this->isConflict
= true;
651 wfProfileOut( $fname );
656 * Initialise form fields in the object
657 * Called on the first invocation, e.g. when a user clicks an edit link
659 function initialiseForm() {
660 $this->edittime
= $this->mArticle
->getTimestamp();
661 $this->textbox1
= $this->mArticle
->getContent();
663 if ( !$this->mArticle
->exists() && $this->mArticle
->mTitle
->getNamespace() == NS_MEDIAWIKI
)
664 $this->textbox1
= wfMsgWeirdKey ( $this->mArticle
->mTitle
->getText() ) ;
669 * Send the edit form and related headers to $wgOut
670 * @param $formCallback Optional callable that takes an OutputPage
671 * parameter; will be called during form output
672 * near the top, for captchas and the like.
674 function showEditForm( $formCallback=null ) {
675 global $wgOut, $wgUser, $wgLang, $wgContLang;
677 $fname = 'EditPage::showEditForm';
678 wfProfileIn( $fname );
680 $sk =& $wgUser->getSkin();
682 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
684 $wgOut->setRobotpolicy( 'noindex,nofollow' );
686 # Enabled article-related sidebar, toplinks, etc.
687 $wgOut->setArticleRelated( true );
689 if ( $this->isConflict
) {
690 $s = wfMsg( 'editconflict', $this->mTitle
->getPrefixedText() );
691 $wgOut->setPageTitle( $s );
692 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
694 $this->textbox2
= $this->textbox1
;
695 $this->textbox1
= $this->mArticle
->getContent();
696 $this->edittime
= $this->mArticle
->getTimestamp();
699 if( $this->section
!= '' ) {
700 if( $this->section
== 'new' ) {
701 $s = wfMsg('editingcomment', $this->mTitle
->getPrefixedText() );
703 $s = wfMsg('editingsection', $this->mTitle
->getPrefixedText() );
704 if( !$this->preview
&& !$this->diff
) {
705 preg_match( "/^(=+)(.+)\\1/mi",
708 if( !empty( $matches[2] ) ) {
709 $this->summary
= "/* ". trim($matches[2])." */ ";
714 $s = wfMsg( 'editing', $this->mTitle
->getPrefixedText() );
716 $wgOut->setPageTitle( $s );
717 if ( !$this->checkUnicodeCompliantBrowser() ) {
718 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
720 if ( isset( $this->mArticle
)
721 && isset( $this->mArticle
->mRevision
)
722 && !$this->mArticle
->mRevision
->isCurrent() ) {
723 $this->mArticle
->setOldSubtitle( $this->mArticle
->mRevision
->getId() );
724 $wgOut->addWikiText( wfMsg( 'editingold' ) );
729 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
730 } else if ( $this->isCssJsSubpage
and 'preview' != $this->formtype
) {
731 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ));
732 } else if( $wgUser->isAnon() && $this->formtype
!= 'preview' ) {
733 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
736 if( $this->mTitle
->isProtected( 'edit' ) ) {
737 if( $this->mTitle
->isSemiProtected() ) {
738 $notice = wfMsg( 'semiprotectedpagewarning' );
739 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) ||
$notice == '-' ) {
743 $notice = wfMsg( 'protectedpagewarning' );
745 $wgOut->addWikiText( $notice );
748 $kblength = (int)(strlen( $this->textbox1
) / 1024);
749 if( $kblength > 29 ) {
750 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $kblength ) ) );
753 $rows = $wgUser->getOption( 'rows' );
754 $cols = $wgUser->getOption( 'cols' );
756 $ew = $wgUser->getOption( 'editwidth' );
757 if ( $ew ) $ew = " style=\"width:100%\"";
760 $q = 'action=submit';
761 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
762 $action = $this->mTitle
->escapeLocalURL( $q );
764 $summary = wfMsg('summary');
765 $subject = wfMsg('subject');
766 $minor = wfMsg('minoredit');
767 $watchthis = wfMsg ('watchthis');
768 $save = wfMsg('savearticle');
769 $prev = wfMsg('showpreview');
770 $diff = wfMsg('showdiff');
772 $cancel = $sk->makeKnownLink( $this->mTitle
->getPrefixedText(),
774 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsg( 'edithelppage' ));
775 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
776 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
777 htmlspecialchars( wfMsg( 'newwindow' ) );
779 global $wgRightsText;
780 $copywarn = "<div id=\"editpage-copywarn\">\n" .
781 wfMsg( $wgRightsText ?
'copyrightwarning' : 'copyrightwarning2',
782 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
783 $wgRightsText ) . "\n</div>";
785 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage
) {
786 # prepare toolbar for edit buttons
787 $toolbar = $this->getEditToolbar();
792 // activate checkboxes if user wants them to be always active
793 if( !$this->preview
&& !$this->diff
) {
794 if( $wgUser->getOption( 'watchdefault' ) ) $this->watchthis
= true;
795 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit
= true;
797 // activate checkbox also if user is already watching the page,
798 // require wpWatchthis to be unset so that second condition is not
799 // checked unnecessarily
800 if( !$this->watchthis
&& $this->mTitle
->userIsWatching() ) $this->watchthis
= true;
805 if ( $wgUser->isAllowed('minoredit') ) {
807 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?
" checked='checked'":"").
808 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
809 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
814 if ( $wgUser->isLoggedIn() ) {
815 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
816 ($this->watchthis?
" checked='checked'":"").
817 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />".
818 "<label for='wpWatchthis' title=\"" .
819 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>";
822 $checkboxhtml = $minoredithtml . $watchhtml;
824 if ( 'preview' == $this->formtype
&& $wgUser->getOption( 'previewontop' ) ) {
825 $this->showPreview();
827 if ( 'diff' == $this->formtype
) {
828 if ( $wgUser->getOption('previewontop' ) ) {
829 $wgOut->addHTML( $this->getDiff() );
834 # if this is a comment, show a subject line at the top, which is also the edit summary.
835 # Otherwise, show a summary field at the bottom
836 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary
) ); # FIXME
837 if( $this->section
== 'new' ) {
838 $commentsubject="<span id='wpSummaryLabel'><label for='wpSummary'>{$subject}:</label></span> <div class='editOptions'><input tabindex='1' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
841 $commentsubject = '';
842 $editsummary="<span id='wpSummaryLabel'><label for='wpSummary'>{$summary}:</label></span> <div class='editOptions'><input tabindex='2' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
845 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
846 if( !$this->preview
&& !$this->diff
) {
847 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
849 $templates = $this->formatTemplates();
851 global $wgLivePreview;
852 if ( $wgLivePreview ) {
853 $liveOnclick = $this->doLivePreviewScript();
858 global $wgUseMetadataEdit ;
859 if ( $wgUseMetadataEdit ) {
860 $metadata = $this->mMetaData
;
861 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
862 $helppage = Title
::newFromText( wfMsg( "metadata_page" ) ) ;
863 $top = wfMsg( 'metadata', $helppage->getLocalURL() );
864 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
866 else $metadata = "" ;
870 if ($this->deletedSinceEdit
) {
871 if ( 'save' != $this->formtype
) {
872 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
874 // Hide the toolbar and edit area, use can click preview to get it back
875 // Add an confirmation checkbox and explanation.
877 $hidden = 'type="hidden" style="display:none;"';
878 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete
->user_name
, $this->lastDelete
->log_comment
));
880 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
881 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
885 $safemodehtml = $this->checkUnicodeCompliantBrowser()
887 : "<input type='hidden' name=\"safemode\" value='1' />\n";
889 $wgOut->addHTML( <<<END
891 <form id="editform" name="editform" method="post" action="$action"
892 enctype="multipart/form-data">
895 if( is_callable( $formCallback ) ) {
896 call_user_func_array( $formCallback, array( &$wgOut ) );
899 // Put these up at the top to ensure they aren't lost on early form submission
901 <input type='hidden' value=\"" . htmlspecialchars( $this->section
) . "\" name=\"wpSection\" />
902 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
903 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
904 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
906 $wgOut->addHTML( <<<END
909 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
910 cols='{$cols}'{$ew} $hidden>
912 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1
) ) .
918 $wgOut->addWikiText( $copywarn );
928 <div class='editButtons'>
929 <input tabindex='5' id='wpSave' type='submit' value=\"{$save}\" name=\"wpSave\" accesskey=\"".wfMsg('accesskey-save')."\"".
930 " title=\"".wfMsg('tooltip-save')."\"/>
931 <input tabindex='6' id='wpPreview' type='submit' $liveOnclick value=\"{$prev}\" name=\"wpPreview\" accesskey=\"".wfMsg('accesskey-preview')."\"".
932 " title=\"".wfMsg('tooltip-preview')."\"/>
933 <input tabindex='7' id='wpDiff' type='submit' value=\"{$diff}\" name=\"wpDiff\" accesskey=\"".wfMsg('accesskey-diff')."\"".
934 " title=\"".wfMsg('tooltip-diff')."\"/> <span class='editHelp'>{$cancel} | {$edithelp}</span></div>
938 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
941 <div class='templatesUsed'>
946 if ( $wgUser->isLoggedIn() ) {
948 * To make it harder for someone to slip a user a page
949 * which submits an edit form to the wiki without their
950 * knowledge, a random token is associated with the login
951 * session. If it's not passed back with the submission,
952 * we won't save the page, or render user JavaScript and
955 $token = htmlspecialchars( $wgUser->editToken() );
956 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
960 if ( $this->isConflict
) {
961 require_once( "DifferenceEngine.php" );
962 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
964 $de = new DifferenceEngine( $this->mTitle
);
965 $de->setText( $this->textbox2
, $this->textbox1
);
966 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
968 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
969 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
970 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2
) ) . "\n</textarea>" );
972 $wgOut->addHTML( "</form>\n" );
973 if ( $this->formtype
== 'preview' && !$wgUser->getOption( 'previewontop' ) ) {
974 $this->showPreview();
976 if ( $this->formtype
== 'diff' && !$wgUser->getOption( 'previewontop' ) ) {
977 #$wgOut->addHTML( '<div id="wikiPreview">' . $difftext . '</div>' );
978 $wgOut->addHTML( $this->getDiff() );
981 wfProfileOut( $fname );
985 * Append preview output to $wgOut.
986 * Includes category rendering if this is a category page.
989 function showPreview() {
991 $wgOut->addHTML( '<div id="wikiPreview">' );
992 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
993 $this->mArticle
->openShowCategory();
995 $previewOutput = $this->getPreviewText();
996 $wgOut->addHTML( $previewOutput );
997 if($this->mTitle
->getNamespace() == NS_CATEGORY
) {
998 $this->mArticle
->closeShowCategory();
1000 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
1001 $wgOut->addHTML( '</div>' );
1005 * Prepare a list of templates used by this page. Returns HTML.
1007 function formatTemplates() {
1010 $fname = 'EditPage::formatTemplates';
1011 wfProfileIn( $fname );
1013 $sk =& $wgUser->getSkin();
1016 $templates = $this->mArticle
->getUsedTemplates();
1017 if ( count( $templates ) > 0 ) {
1018 # Do a batch existence check
1019 $batch = new LinkBatch
;
1020 foreach( $templates as $title ) {
1021 $batch->addObj( $title );
1025 # Construct the HTML
1026 $outText = '<br />'. wfMsg( 'templatesused' ) . '<ul>';
1027 foreach ( $templates as $titleObj ) {
1028 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
1030 $outText .= '</ul>';
1032 wfProfileOut( $fname );
1037 * Live Preview lets us fetch rendered preview page content and
1038 * add it to the page without refreshing the whole page.
1039 * If not supported by the browser it will fall through to the normal form
1040 * submission method.
1042 * This function outputs a script tag to support live preview, and
1043 * returns an onclick handler which should be added to the attributes
1044 * of the preview button
1046 function doLivePreviewScript() {
1047 global $wgStylePath, $wgJsMimeType, $wgOut;
1048 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1049 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
1050 '"></script>' . "\n" );
1051 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1052 return 'onclick="return !livePreview('.
1053 'getElementById(\'wikiPreview\'),' .
1054 'editform.wpTextbox1.value,' .
1055 htmlspecialchars( '"' . $liveAction . '"' ) . ')"';
1058 function getLastDelete() {
1059 $dbr =& wfGetDB( DB_SLAVE
);
1060 $fname = 'EditPage::getLastDelete';
1061 $res = $dbr->select(
1062 array( 'logging', 'user' ),
1072 array( 'log_namespace' => $this->mTitle
->getNamespace(),
1073 'log_title' => $this->mTitle
->getDBkey(),
1074 'log_type' => 'delete',
1075 'log_action' => 'delete',
1076 'user_id=log_user' ),
1078 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1080 if($dbr->numRows($res) == 1) {
1081 while ( $x = $dbr->fetchObject ( $res ) )
1083 $dbr->freeResult ( $res ) ;
1093 function getPreviewText() {
1094 global $wgOut, $wgUser, $wgTitle, $wgParser;
1096 $fname = 'EditPage::getPreviewText';
1097 wfProfileIn( $fname );
1099 if ( $this->mTokenOk
) {
1100 $msg = 'previewnote';
1102 $msg = 'session_fail_preview';
1104 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1105 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1106 if ( $this->isConflict
) {
1107 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1110 $parserOptions = ParserOptions
::newFromUser( $wgUser );
1111 $parserOptions->setEditSection( false );
1113 # don't parse user css/js, show message about preview
1114 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1116 if ( $this->isCssJsSubpage
) {
1117 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1118 $previewtext = wfMsg('usercsspreview');
1119 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1120 $previewtext = wfMsg('userjspreview');
1122 $parserOptions->setTidy(true);
1123 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1124 $wgOut->addHTML( $parserOutput->mText
);
1125 wfProfileOut( $fname );
1126 return $previewhead;
1128 # if user want to see preview when he edit an article
1129 if( $wgUser->getOption('previewonfirst') and ($this->textbox1
== '')) {
1130 $this->textbox1
= $this->mArticle
->getContent();
1133 $toparse = $this->textbox1
;
1135 # If we're adding a comment, we need to show the
1136 # summary as the headline
1137 if($this->section
=="new" && $this->summary
!="") {
1138 $toparse="== {$this->summary} ==\n\n".$toparse;
1141 if ( $this->mMetaData
!= "" ) $toparse .= "\n" . $this->mMetaData
;
1142 $parserOptions->setTidy(true);
1143 $parserOutput = $wgParser->parse( $this->mArticle
->preSaveTransform( $toparse ) ."\n\n",
1144 $wgTitle, $parserOptions );
1146 $previewHTML = $parserOutput->getText();
1147 $wgOut->addParserOutputNoText( $parserOutput );
1149 wfProfileOut( $fname );
1150 return $previewhead . $previewHTML;
1157 function blockedIPpage() {
1159 $wgOut->blockedPage();
1165 function userNotLoggedInPage() {
1168 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1169 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1170 $wgOut->setArticleRelated( false );
1172 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
1173 $wgOut->returnToMain( false );
1177 * Creates a basic error page which informs the user that
1178 * they have to validate their email address before being
1181 function userNotConfirmedPage() {
1185 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1186 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1187 $wgOut->setArticleRelated( false );
1188 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1189 $wgOut->returnToMain( false );
1195 function spamPage ( $match = false )
1198 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1199 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1200 $wgOut->setArticleRelated( false );
1202 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1204 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1206 $wgOut->returnToMain( false );
1213 function mergeChangesInto( &$editText ){
1214 $fname = 'EditPage::mergeChangesInto';
1215 wfProfileIn( $fname );
1217 $db =& wfGetDB( DB_MASTER
);
1219 // This is the revision the editor started from
1220 $baseRevision = Revision
::loadFromTimestamp(
1221 $db, $this->mArticle
->mTitle
, $this->edittime
);
1222 if( is_null( $baseRevision ) ) {
1223 wfProfileOut( $fname );
1226 $baseText = $baseRevision->getText();
1228 // The current state, we want to merge updates into it
1229 $currentRevision = Revision
::loadFromTitle(
1230 $db, $this->mArticle
->mTitle
);
1231 if( is_null( $currentRevision ) ) {
1232 wfProfileOut( $fname );
1235 $currentText = $currentRevision->getText();
1237 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1238 $editText = $result;
1239 wfProfileOut( $fname );
1242 wfProfileOut( $fname );
1248 * Check if the browser is on a blacklist of user-agents known to
1249 * mangle UTF-8 data on form submission. Returns true if Unicode
1250 * should make it through, false if it's known to be a problem.
1254 function checkUnicodeCompliantBrowser() {
1255 global $wgBrowserBlackList;
1256 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1257 // No User-Agent header sent? Trust it by default...
1260 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1261 foreach ( $wgBrowserBlackList as $browser ) {
1262 if ( preg_match($browser, $currentbrowser) ) {
1270 * Format an anchor fragment as it would appear for a given section name
1271 * @param string $text
1275 function sectionAnchor( $text ) {
1276 $headline = Sanitizer
::decodeCharReferences( $text );
1278 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1279 $headline = trim( $headline );
1280 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1281 $replacearray = array(
1286 array_keys( $replacearray ),
1287 array_values( $replacearray ),
1292 * Shows a bulletin board style toolbar for common editing functions.
1293 * It can be disabled in the user preferences.
1294 * The necessary JavaScript code can be found in style/wikibits.js.
1296 function getEditToolbar() {
1297 global $wgStylePath, $wgContLang, $wgJsMimeType;
1300 * toolarray an array of arrays which each include the filename of
1301 * the button image (without path), the opening tag, the closing tag,
1302 * and optionally a sample text that is inserted between the two when no
1303 * selection is highlighted.
1304 * The tip text is shown when the user moves the mouse over the button.
1306 * Already here are accesskeys (key), which are not used yet until someone
1307 * can figure out a way to make them work in IE. However, we should make
1308 * sure these keys are not defined on the edit page.
1311 array( 'image'=>'button_bold.png',
1313 'close' => "\'\'\'",
1314 'sample'=> wfMsg('bold_sample'),
1315 'tip' => wfMsg('bold_tip'),
1318 array( 'image'=>'button_italic.png',
1321 'sample'=> wfMsg('italic_sample'),
1322 'tip' => wfMsg('italic_tip'),
1325 array( 'image'=>'button_link.png',
1328 'sample'=> wfMsg('link_sample'),
1329 'tip' => wfMsg('link_tip'),
1332 array( 'image'=>'button_extlink.png',
1335 'sample'=> wfMsg('extlink_sample'),
1336 'tip' => wfMsg('extlink_tip'),
1339 array( 'image'=>'button_headline.png',
1341 'close' => " ==\\n",
1342 'sample'=> wfMsg('headline_sample'),
1343 'tip' => wfMsg('headline_tip'),
1346 array( 'image'=>'button_image.png',
1347 'open' => '[['.$wgContLang->getNsText(NS_IMAGE
).":",
1349 'sample'=> wfMsg('image_sample'),
1350 'tip' => wfMsg('image_tip'),
1353 array( 'image' =>'button_media.png',
1354 'open' => '[['.$wgContLang->getNsText(NS_MEDIA
).':',
1356 'sample'=> wfMsg('media_sample'),
1357 'tip' => wfMsg('media_tip'),
1360 array( 'image' =>'button_math.png',
1361 'open' => "\\<math\\>",
1362 'close' => "\\</math\\>",
1363 'sample'=> wfMsg('math_sample'),
1364 'tip' => wfMsg('math_tip'),
1367 array( 'image' =>'button_nowiki.png',
1368 'open' => "\\<nowiki\\>",
1369 'close' => "\\</nowiki\\>",
1370 'sample'=> wfMsg('nowiki_sample'),
1371 'tip' => wfMsg('nowiki_tip'),
1374 array( 'image' =>'button_sig.png',
1378 'tip' => wfMsg('sig_tip'),
1381 array( 'image' =>'button_hr.png',
1382 'open' => "\\n----\\n",
1385 'tip' => wfMsg('hr_tip'),
1389 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1391 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1392 foreach($toolarray as $tool) {
1394 $image=$wgStylePath.'/common/images/'.$tool['image'];
1395 $open=$tool['open'];
1396 $close=$tool['close'];
1397 $sample = wfEscapeJsString( $tool['sample'] );
1399 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1400 // Older browsers show a "speedtip" type message only for ALT.
1401 // Ideally these should be different, realistically they
1402 // probably don't need to be.
1403 $tip = wfEscapeJsString( $tool['tip'] );
1405 #$key = $tool["key"];
1407 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1410 $toolbar.="document.writeln(\"</div>\");\n";
1411 $toolbar.="/*]]>*/\n</script>";
1416 * Output preview text only. This can be sucked into the edit page
1417 * via JavaScript, and saves the server time rendering the skin as
1418 * well as theoretically being more robust on the client (doesn't
1419 * disturb the edit box's undo history, won't eat your text on
1422 * @todo This doesn't include category or interlanguage links.
1423 * Would need to enhance it a bit, maybe wrap them in XML
1424 * or something... that might also require more skin
1425 * initialization, so check whether that's a problem.
1427 function livePreview() {
1430 header( 'Content-type: text/xml' );
1431 header( 'Cache-control: no-cache' );
1433 echo $this->getPreviewText( false, false );
1438 * Get a diff between the current contents of the edit box and the
1439 * version of the page we're editing from.
1441 * If this is a section edit, we'll replace the section as for final
1442 * save and then make a comparison.
1444 * @return string HTML
1446 function getDiff() {
1449 require_once( 'DifferenceEngine.php' );
1450 $oldtext = $this->mArticle
->fetchContent();
1451 $newtext = $this->mArticle
->replaceSection(
1452 $this->section
, $this->textbox1
, $this->summary
, $this->edittime
);
1453 $oldtitle = wfMsg( 'currentrev' );
1454 $newtitle = wfMsg( 'yourtext' );
1455 if ( $oldtext !== false ||
$newtext != '' ) {
1456 $de = new DifferenceEngine( $this->mTitle
);
1457 $de->setText( $oldtext, $newtext );
1458 $difftext = $de->getDiff( $oldtitle, $newtitle );
1463 return '<div id="wikiDiff">' . $difftext . '</div>';
1467 * Filter an input field through a Unicode de-armoring process if it
1468 * came from an old browser with known broken Unicode editing issues.
1470 * @param WebRequest $request
1471 * @param string $field
1475 function safeUnicodeInput( $request, $field ) {
1476 $text = rtrim( $request->getText( $field ) );
1477 return $request->getBool( 'safemode' )
1478 ?
$this->unmakesafe( $text )
1483 * Filter an output field through a Unicode armoring process if it is
1484 * going to an old browser with known broken Unicode editing issues.
1486 * @param string $text
1490 function safeUnicodeOutput( $text ) {
1492 $codedText = $wgContLang->recodeForEdit( $text );
1493 return $this->checkUnicodeCompliantBrowser()
1495 : $this->makesafe( $codedText );
1499 * A number of web browsers are known to corrupt non-ASCII characters
1500 * in a UTF-8 text editing environment. To protect against this,
1501 * detected browsers will be served an armored version of the text,
1502 * with non-ASCII chars converted to numeric HTML character references.
1504 * Preexisting such character references will have a 0 added to them
1505 * to ensure that round-trips do not alter the original data.
1507 * @param string $invalue
1511 function makesafe( $invalue ) {
1512 // Armor existing references for reversability.
1513 $invalue = strtr( $invalue, array( "&#x" => "�" ) );
1518 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1519 $bytevalue = ord( $invalue{$i} );
1520 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1521 $result .= chr( $bytevalue );
1523 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1524 $working = $working << 6;
1525 $working +
= ($bytevalue & 0x3F);
1527 if( $bytesleft <= 0 ) {
1528 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1530 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1531 $working = $bytevalue & 0x1F;
1533 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1534 $working = $bytevalue & 0x0F;
1536 } else { //1111 0xxx
1537 $working = $bytevalue & 0x07;
1545 * Reverse the previously applied transliteration of non-ASCII characters
1546 * back to UTF-8. Used to protect data from corruption by broken web browsers
1547 * as listed in $wgBrowserBlackList.
1549 * @param string $invalue
1553 function unmakesafe( $invalue ) {
1555 for( $i = 0; $i < strlen( $invalue ); $i++
) {
1556 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+
3} != '0' ) ) {
1560 $hexstring .= $invalue{$i};
1562 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1564 // Do some sanity checks. These aren't needed for reversability,
1565 // but should help keep the breakage down if the editor
1566 // breaks one of the entities whilst editing.
1567 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1568 $codepoint = hexdec($hexstring);
1569 $result .= codepointToUtf8( $codepoint );
1571 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1574 $result .= substr( $invalue, $i, 1 );
1577 // reverse the transform that we made for reversability reasons.
1578 return strtr( $result, array( "�" => "&#x" ) );
1581 function noCreatePermission() {
1583 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
1584 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );