typo
[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
21 # Form values
22 var $save = false, $preview = false, $diff = false;
23 var $minoredit = false, $watchthis = false;
24 var $textbox1 = '', $textbox2 = '', $summary = '';
25 var $edittime = '', $section = '';
26 var $oldid = 0;
27
28 /**
29 * @todo document
30 * @param $article
31 */
32 function EditPage( $article ) {
33 $this->mArticle =& $article;
34 global $wgTitle;
35 $this->mTitle =& $wgTitle;
36 }
37
38 /**
39 * This is the function that extracts metadata from the article body on the first view.
40 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
41 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
42 */
43 function extractMetaDataFromArticle () {
44 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
45 $this->mMetaData = '' ;
46 if ( !$wgUseMetadataEdit ) return ;
47 if ( $wgMetadataWhitelist == '' ) return ;
48 $s = '' ;
49 $t = $this->mArticle->getContent ( true ) ;
50
51 # MISSING : <nowiki> filtering
52
53 # Categories and language links
54 $t = explode ( "\n" , $t ) ;
55 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY ) ) ;
56 $cat = $ll = array() ;
57 foreach ( $t AS $key => $x )
58 {
59 $y = trim ( strtolower ( $x ) ) ;
60 while ( substr ( $y , 0 , 2 ) == '[[' )
61 {
62 $y = explode ( ']]' , trim ( $x ) ) ;
63 $first = array_shift ( $y ) ;
64 $first = explode ( ':' , $first ) ;
65 $ns = array_shift ( $first ) ;
66 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
67 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
68 {
69 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
70 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
71 else $ll[] = $add ;
72 $x = implode ( ']]' , $y ) ;
73 $t[$key] = $x ;
74 $y = trim ( strtolower ( $x ) ) ;
75 }
76 }
77 }
78 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
79 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
80 $t = implode ( "\n" , $t ) ;
81
82 # Load whitelist
83 $sat = array () ; # stand-alone-templates; must be lowercase
84 $wl_title = Title::newFromText ( $wgMetadataWhitelist ) ;
85 $wl_article = new Article ( $wl_title ) ;
86 $wl = explode ( "\n" , $wl_article->getContent(true) ) ;
87 foreach ( $wl AS $x )
88 {
89 $isentry = false ;
90 $x = trim ( $x ) ;
91 while ( substr ( $x , 0 , 1 ) == '*' )
92 {
93 $isentry = true ;
94 $x = trim ( substr ( $x , 1 ) ) ;
95 }
96 if ( $isentry )
97 {
98 $sat[] = strtolower ( $x ) ;
99 }
100
101 }
102
103 # Templates, but only some
104 $t = explode ( '{{' , $t ) ;
105 $tl = array () ;
106 foreach ( $t AS $key => $x )
107 {
108 $y = explode ( '}}' , $x , 2 ) ;
109 if ( count ( $y ) == 2 )
110 {
111 $z = $y[0] ;
112 $z = explode ( '|' , $z ) ;
113 $tn = array_shift ( $z ) ;
114 if ( in_array ( strtolower ( $tn ) , $sat ) )
115 {
116 $tl[] = '{{' . $y[0] . '}}' ;
117 $t[$key] = $y[1] ;
118 $y = explode ( '}}' , $y[1] , 2 ) ;
119 }
120 else $t[$key] = '{{' . $x ;
121 }
122 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
123 else $t[$key] = $x ;
124 }
125 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
126 $t = implode ( '' , $t ) ;
127
128 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
129 $this->mArticle->mContent = $t ;
130 $this->mMetaData = $s ;
131 }
132
133 /**
134 * This is the function that gets called for "action=edit".
135 */
136 function edit() {
137 global $wgOut, $wgUser, $wgRequest;
138 // this is not an article
139 $wgOut->setArticleFlag(false);
140
141 $this->importFormData( $wgRequest );
142
143 if( $this->live ) {
144 $this->livePreview();
145 return;
146 }
147
148 if ( ! $this->mTitle->userCanEdit() ) {
149 $wgOut->readOnlyPage( $this->mArticle->getContent( true ), true );
150 return;
151 }
152 if ( !$this->preview && !$this->diff && $wgUser->isBlockedFrom( $this->mTitle, !$this->save ) ) {
153 # When previewing, don't check blocked state - will get caught at save time.
154 # Also, check when starting edition is done against slave to improve performance.
155 $this->blockedIPpage();
156 return;
157 }
158 if ( !$wgUser->isAllowed('edit') ) {
159 if ( $wgUser->isAnon() ) {
160 $this->userNotLoggedInPage();
161 return;
162 } else {
163 $wgOut->readOnlyPage( $this->mArticle->getContent( true ), true );
164 return;
165 }
166 }
167 if ( wfReadOnly() ) {
168 if( $this->save || $this->preview ) {
169 $this->editForm( 'preview' );
170 } else if ( $this->diff ) {
171 $this->editForm( 'diff' );
172 } else {
173 $wgOut->readOnlyPage( $this->mArticle->getContent( true ) );
174 }
175 return;
176 }
177 if ( $this->save ) {
178 $this->editForm( 'save' );
179 } else if ( $this->preview ) {
180 $this->editForm( 'preview' );
181 } else if ( $this->diff ) {
182 $this->editForm( 'diff' );
183 } else { # First time through
184 if( $this->previewOnOpen() ) {
185 $this->editForm( 'preview', true );
186 } else {
187 $this->extractMetaDataFromArticle () ;
188 $this->editForm( 'initial', true );
189 }
190 }
191 }
192
193 /**
194 * Return true if this page should be previewed when the edit form
195 * is initially opened.
196 * @return bool
197 * @access private
198 */
199 function previewOnOpen() {
200 global $wgUser;
201 return $wgUser->getOption( 'previewonfirst' ) ||
202 ( $this->mTitle->getNamespace() == NS_CATEGORY &&
203 !$this->mTitle->exists() );
204 }
205
206 /**
207 * @todo document
208 */
209 function importFormData( &$request ) {
210 if( $request->wasPosted() ) {
211 # These fields need to be checked for encoding.
212 # Also remove trailing whitespace, but don't remove _initial_
213 # whitespace from the text boxes. This may be significant formatting.
214 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
215 $this->textbox2 = $this->safeUnicodeInput( $request, 'wpTextbox2' );
216 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
217 $this->summary = $request->getText( 'wpSummary' );
218
219 $this->edittime = $request->getVal( 'wpEdittime' );
220 if( is_null( $this->edittime ) ) {
221 # If the form is incomplete, force to preview.
222 $this->preview = true;
223 } else {
224 if( $this->tokenOk( $request ) ) {
225 # Some browsers will not report any submit button
226 # if the user hits enter in the comment box.
227 # The unmarked state will be assumed to be a save,
228 # if the form seems otherwise complete.
229 $this->preview = $request->getCheck( 'wpPreview' );
230 $this->diff = $request->getCheck( 'wpDiff' );
231 } else {
232 # Page might be a hack attempt posted from
233 # an external site. Preview instead of saving.
234 $this->preview = true;
235 }
236 }
237 $this->save = ! ( $this->preview OR $this->diff );
238 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
239 $this->edittime = null;
240 }
241
242 $this->minoredit = $request->getCheck( 'wpMinoredit' );
243 $this->watchthis = $request->getCheck( 'wpWatchthis' );
244 } else {
245 # Not a posted form? Start with nothing.
246 $this->textbox1 = '';
247 $this->textbox2 = '';
248 $this->mMetaData = '';
249 $this->summary = '';
250 $this->edittime = '';
251 $this->preview = false;
252 $this->save = false;
253 $this->diff = false;
254 $this->minoredit = false;
255 $this->watchthis = false;
256 }
257
258 $this->oldid = $request->getInt( 'oldid' );
259
260 # Section edit can come from either the form or a link
261 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
262
263 $this->live = $request->getCheck( 'live' );
264 }
265
266 /**
267 * Make sure the form isn't faking a user's credentials.
268 *
269 * @param WebRequest $request
270 * @return bool
271 * @access private
272 */
273 function tokenOk( &$request ) {
274 global $wgUser;
275 if( $wgUser->isAnon() ) {
276 # Anonymous users may not have a session
277 # open. Don't tokenize.
278 return true;
279 } else {
280 return $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
281 }
282 }
283
284 function submit() {
285 $this->edit();
286 }
287
288 /**
289 * The edit form is self-submitting, so that when things like
290 * preview and edit conflicts occur, we get the same form back
291 * with the extra stuff added. Only when the final submission
292 * is made and all is well do we actually save and redirect to
293 * the newly-edited page.
294 *
295 * @param string $formtype Type of form either : save, initial, diff or preview
296 * @param bool $firsttime True to load form data from db
297 */
298 function editForm( $formtype, $firsttime = false ) {
299 global $wgOut, $wgUser;
300 global $wgLang, $wgContLang, $wgParser, $wgTitle;
301 global $wgAllowAnonymousMinor, $wgRequest;
302 global $wgSpamRegex, $wgFilterCallback;
303
304 $sk = $wgUser->getSkin();
305 $isConflict = false;
306 // css / js subpages of user pages get a special treatment
307 $isCssJsSubpage = $wgTitle->isCssJsSubpage();
308
309 if(!$this->mTitle->getArticleID()) { # new article
310 $editintro = $wgRequest->getText( 'editintro' );
311 $addstandardintro=true;
312 if($editintro) {
313 $introtitle=Title::newFromText($editintro);
314 if(isset($introtitle) && $introtitle->userCanRead()) {
315 $rev=Revision::newFromTitle($introtitle);
316 if($rev) {
317 $wgOut->addWikiText($rev->getText());
318 $addstandardintro=false;
319 }
320 }
321 }
322 if($addstandardintro) {
323 $wgOut->addWikiText(wfmsg('newarticletext'));
324 }
325 }
326
327 if( $this->mTitle->isTalkPage() ) {
328 $wgOut->addWikiText(wfmsg('talkpagetext'));
329 }
330
331 # Attempt submission here. This will check for edit conflicts,
332 # and redundantly check for locked database, blocked IPs, etc.
333 # that edit() already checked just in case someone tries to sneak
334 # in the back door with a hand-edited submission URL.
335
336 if ( 'save' == $formtype ) {
337 # Reintegrate metadata
338 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
339 $this->mMetaData = '' ;
340
341 # Check for spam
342 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
343 $this->spamPage ( $matches[0] );
344 return;
345 }
346 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
347 # Error messages or other handling should be performed by the filter function
348 return;
349 }
350 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
351 # Check block state against master, thus 'false'.
352 $this->blockedIPpage();
353 return;
354 }
355
356 if ( !$wgUser->isAllowed('edit') ) {
357 if ( $wgUser->isAnon() ) {
358 $this->userNotLoggedInPage();
359 return;
360 }
361 else {
362 $wgOut->readOnlyPage();
363 return;
364 }
365 }
366
367 if ( wfReadOnly() ) {
368 $wgOut->readOnlyPage();
369 return;
370 }
371 if ( $wgUser->pingLimiter() ) {
372 $wgOut->rateLimited();
373 return;
374 }
375
376 # If article is new, insert it.
377 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
378 if ( 0 == $aid ) {
379 # Don't save a new article if it's blank.
380 if ( ( '' == $this->textbox1 ) ||
381 ( wfMsg( 'newarticletext' ) == $this->textbox1 ) ) {
382 $wgOut->redirect( $this->mTitle->getFullURL() );
383 return;
384 }
385 if (wfRunHooks('ArticleSave', array(&$this->mArticle, &$wgUser, &$this->textbox1,
386 &$this->summary, &$this->minoredit, &$this->watchthis, NULL)))
387 {
388
389 $isComment=($this->section=='new');
390 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
391 $this->minoredit, $this->watchthis, false, $isComment);
392 wfRunHooks('ArticleSaveComplete', array(&$this->mArticle, &$wgUser, $this->textbox1,
393 $this->summary, $this->minoredit,
394 $this->watchthis, NULL));
395 }
396 return;
397 }
398
399 # Article exists. Check for edit conflict.
400
401 $this->mArticle->clear(); # Force reload of dates, etc.
402 $this->mArticle->forUpdate( true ); # Lock the article
403
404 if( ( $this->section != 'new' ) &&
405 ($this->mArticle->getTimestamp() != $this->edittime ) ) {
406 $isConflict = true;
407 }
408 $userid = $wgUser->getID();
409
410 if ( $isConflict) {
411 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
412 $this->mArticle->getTimestamp() . "'\n" );
413 $text = $this->mArticle->getTextOfLastEditWithSectionReplacedOrAdded(
414 $this->section, $this->textbox1, $this->summary, $this->edittime);
415 }
416 else {
417 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
418 $text = $this->mArticle->getTextOfLastEditWithSectionReplacedOrAdded(
419 $this->section, $this->textbox1, $this->summary);
420 }
421 # Suppress edit conflict with self
422
423 if ( ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
424 wfDebug( "Suppressing edit conflict, same user.\n" );
425 $isConflict = false;
426 } else {
427 # switch from section editing to normal editing in edit conflict
428 if($isConflict) {
429 # Attempt merge
430 if( $this->mergeChangesInto( $text ) ){
431 // Successful merge! Maybe we should tell the user the good news?
432 $isConflict = false;
433 wfDebug( "Suppressing edit conflict, successful merge.\n" );
434 } else {
435 $this->section = '';
436 $this->textbox1 = $text;
437 wfDebug( "Keeping edit conflict, failed merge.\n" );
438 }
439 }
440 }
441 if ( ! $isConflict ) {
442 # All's well
443 $sectionanchor = '';
444 if( $this->section == 'new' ) {
445 if( $this->summary != '' ) {
446 $sectionanchor = $this->sectionAnchor( $this->summary );
447 }
448 } elseif( $this->section != '' ) {
449 # Try to get a section anchor from the section source, redirect to edited section if header found
450 # XXX: might be better to integrate this into Article::getTextOfLastEditWithSectionReplacedOrAdded
451 # for duplicate heading checking and maybe parsing
452 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
453 # we can't deal with anchors, includes, html etc in the header for now,
454 # headline would need to be parsed to improve this
455 #if($hasmatch and strlen($matches[2]) > 0 and !preg_match( "/[\\['{<>]/", $matches[2])) {
456 if($hasmatch and strlen($matches[2]) > 0) {
457 $sectionanchor = $this->sectionAnchor( $matches[2] );
458 }
459 }
460
461 // Save errors may fall down to the edit form, but we've now
462 // merged the section into full text. Clear the section field
463 // so that later submission of conflict forms won't try to
464 // replace that into a duplicated mess.
465 $this->textbox1 = $text;
466 $this->section = '';
467
468 if (wfRunHooks('ArticleSave', array(&$this->mArticle, &$wgUser, &$text,
469 &$this->summary, &$this->minoredit,
470 &$this->watchthis, &$sectionanchor)))
471 {
472 # update the article here
473 if($this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
474 $this->watchthis, '', $sectionanchor ))
475 {
476 wfRunHooks('ArticleSaveComplete', array(&$this->mArticle, &$wgUser, $text,
477 $this->summary, $this->minoredit,
478 $this->watchthis, $sectionanchor));
479 return;
480 } else {
481 $isConflict = true;
482 }
483 }
484 }
485 }
486 # First time through: get contents, set time for conflict
487 # checking, etc.
488
489 if ( 'initial' == $formtype || $firsttime ) {
490 $this->edittime = $this->mArticle->getTimestamp();
491 $this->textbox1 = $this->mArticle->getContent( true );
492 $this->summary = '';
493 $this->proxyCheck();
494 }
495 $wgOut->setRobotpolicy( 'noindex,nofollow' );
496
497 # Enabled article-related sidebar, toplinks, etc.
498 $wgOut->setArticleRelated( true );
499
500 if ( $isConflict ) {
501 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
502 $wgOut->setPageTitle( $s );
503 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
504
505 $this->textbox2 = $this->textbox1;
506 $this->textbox1 = $this->mArticle->getContent( true );
507 $this->edittime = $this->mArticle->getTimestamp();
508 } else {
509
510 if( $this->section != '' ) {
511 if( $this->section == 'new' ) {
512 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
513 } else {
514 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
515 if( !$this->preview && !$this->diff ) {
516 preg_match( "/^(=+)(.+)\\1/mi",
517 $this->textbox1,
518 $matches );
519 if( !empty( $matches[2] ) ) {
520 $this->summary = "/* ". trim($matches[2])." */ ";
521 }
522 }
523 }
524 } else {
525 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
526 }
527 $wgOut->setPageTitle( $s );
528 if ( !$this->checkUnicodeCompliantBrowser() ) {
529 $this->mArticle->setOldSubtitle();
530 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
531 }
532 if ( isset( $this->mArticle )
533 && isset( $this->mArticle->mRevision )
534 && !$this->mArticle->mRevision->isCurrent() ) {
535 $this->mArticle->setOldSubtitle();
536 $wgOut->addWikiText( wfMsg( 'editingold' ) );
537 }
538 }
539
540 if( wfReadOnly() ) {
541 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
542 } else if ( $isCssJsSubpage and 'preview' != $formtype) {
543 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ));
544 }
545 if( $this->mTitle->isProtected('edit') ) {
546 $wgOut->addWikiText( wfMsg( 'protectedpagewarning' ) );
547 }
548
549 $kblength = (int)(strlen( $this->textbox1 ) / 1024);
550 if( $kblength > 29 ) {
551 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $kblength ) ) );
552 }
553
554 $rows = $wgUser->getOption( 'rows' );
555 $cols = $wgUser->getOption( 'cols' );
556
557 $ew = $wgUser->getOption( 'editwidth' );
558 if ( $ew ) $ew = " style=\"width:100%\"";
559 else $ew = '';
560
561 $q = 'action=submit';
562 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
563 $action = $this->mTitle->escapeLocalURL( $q );
564
565 $summary = wfMsg('summary');
566 $subject = wfMsg('subject');
567 $minor = wfMsg('minoredit');
568 $watchthis = wfMsg ('watchthis');
569 $save = wfMsg('savearticle');
570 $prev = wfMsg('showpreview');
571 $diff = wfMsg('showdiff');
572
573 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
574 wfMsg('cancel') );
575 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsg( 'edithelppage' ));
576 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
577 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
578 htmlspecialchars( wfMsg( 'newwindow' ) );
579
580 global $wgRightsText;
581 $copywarn = "<div id=\"editpage-copywarn\">\n" .
582 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
583 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
584 $wgRightsText ) . "\n</div>";
585
586 if( $wgUser->getOption('showtoolbar') and !$isCssJsSubpage ) {
587 # prepare toolbar for edit buttons
588 $toolbar = $this->getEditToolbar();
589 } else {
590 $toolbar = '';
591 }
592
593 // activate checkboxes if user wants them to be always active
594 if( !$this->preview && !$this->diff ) {
595 if( $wgUser->getOption( 'watchdefault' ) ) $this->watchthis = true;
596 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
597
598 // activate checkbox also if user is already watching the page,
599 // require wpWatchthis to be unset so that second condition is not
600 // checked unnecessarily
601 if( !$this->watchthis && $this->mTitle->userIsWatching() ) $this->watchthis = true;
602 }
603
604 $minoredithtml = '';
605
606 if ( $wgUser->isLoggedIn() || $wgAllowAnonymousMinor ) {
607 $minoredithtml =
608 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
609 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
610 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
611 }
612
613 $watchhtml = '';
614
615 if ( $wgUser->isLoggedIn() ) {
616 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".($this->watchthis?" checked='checked'":"").
617 " accesskey='".wfMsg('accesskey-watch')."' id='wpWatchthis' />".
618 "<label for='wpWatchthis' title='".wfMsg('tooltip-watch')."'>{$watchthis}</label>";
619 }
620
621 $checkboxhtml = $minoredithtml . $watchhtml . '<br />';
622
623 $wgOut->addHTML( '<div id="wikiPreview">' );
624 if ( 'preview' == $formtype) {
625 $previewOutput = $this->getPreviewText( $isConflict, $isCssJsSubpage );
626 if ( $wgUser->getOption('previewontop' ) ) {
627 $wgOut->addHTML( $previewOutput );
628 if($this->mTitle->getNamespace() == NS_CATEGORY) {
629 $this->mArticle->closeShowCategory();
630 }
631 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
632 }
633 }
634 $wgOut->addHTML( '</div>' );
635 if ( 'diff' == $formtype ) {
636 if ( $wgUser->getOption('previewontop' ) ) {
637 $wgOut->addHTML( $this->getDiff() );
638 }
639 }
640
641
642 # if this is a comment, show a subject line at the top, which is also the edit summary.
643 # Otherwise, show a summary field at the bottom
644 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
645 if( $this->section == 'new' ) {
646 $commentsubject="{$subject}: <input tabindex='1' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
647 $editsummary = '';
648 } else {
649 $commentsubject = '';
650 $editsummary="{$summary}: <input tabindex='2' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
651 }
652
653 if( !$this->preview && !$this->diff ) {
654 # Don't select the edit box on preview; this interferes with seeing what's going on.
655 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
656 }
657 # Prepare a list of templates used by this page
658 $templates = '';
659 $articleTemplates = $this->mArticle->getUsedTemplates();
660 if ( count( $articleTemplates ) > 0 ) {
661 $templates = '<br />'. wfMsg( 'templatesused' ) . '<ul>';
662 foreach ( $articleTemplates as $tpl ) {
663 if ( $titleObj = Title::makeTitle( NS_TEMPLATE, $tpl ) ) {
664 $templates .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
665 }
666 }
667 $templates .= '</ul>';
668 }
669
670 global $wgLivePreview, $wgStylePath;
671 /**
672 * Live Preview lets us fetch rendered preview page content and
673 * add it to the page without refreshing the whole page.
674 * Set up the button for it; if not supported by the browser
675 * it will fall through to the normal form submission method.
676 */
677 if( $wgLivePreview ) {
678 global $wgJsMimeType;
679 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
680 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
681 '"></script>' . "\n" );
682 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
683 $liveOnclick = 'onclick="return !livePreview('.
684 'getElementById(\'wikiPreview\'),' .
685 'editform.wpTextbox1.value,' .
686 htmlspecialchars( '"' . $liveAction . '"' ) . ')"';
687 } else {
688 $liveOnclick = '';
689 }
690
691 global $wgUseMetadataEdit ;
692 if ( $wgUseMetadataEdit )
693 {
694 $metadata = $this->mMetaData ;
695 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
696 $helppage = Title::newFromText ( wfmsg("metadata_page") ) ;
697 $top = str_replace ( "$1" , $helppage->getInternalURL() , wfmsg("metadata") ) ;
698 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
699 }
700 else $metadata = "" ;
701
702 $safemodehtml = $this->checkUnicodeCompliantBrowser()
703 ? ""
704 : "<input type='hidden' name=\"safemode\" value='1' />\n";
705
706 $wgOut->addHTML( <<<END
707 {$toolbar}
708 <form id="editform" name="editform" method="post" action="$action"
709 enctype="multipart/form-data">
710 {$commentsubject}
711 <textarea tabindex='1' accesskey="," name="wpTextbox1" rows='{$rows}'
712 cols='{$cols}'{$ew}>
713 END
714 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
715 "
716 </textarea>
717 {$metadata}
718 <br />{$editsummary}
719 {$checkboxhtml}
720 {$safemodehtml}
721 <input tabindex='5' id='wpSave' type='submit' value=\"{$save}\" name=\"wpSave\" accesskey=\"".wfMsg('accesskey-save')."\"".
722 " title=\"".wfMsg('tooltip-save')."\"/>
723 <input tabindex='6' id='wpPreview' type='submit' $liveOnclick value=\"{$prev}\" name=\"wpPreview\" accesskey=\"".wfMsg('accesskey-preview')."\"".
724 " title=\"".wfMsg('tooltip-preview')."\"/>
725 <input tabindex='7' id='wpDiff' type='submit' value=\"{$diff}\" name=\"wpDiff\" accesskey=\"".wfMsg('accesskey-diff')."\"".
726 " title=\"".wfMsg('tooltip-diff')."\"/>
727 <em>{$cancel}</em> | <em>{$edithelp}</em>{$templates}" );
728 $wgOut->addWikiText( $copywarn );
729 $wgOut->addHTML( "
730 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
731 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n" );
732
733 if ( $wgUser->isLoggedIn() ) {
734 /**
735 * To make it harder for someone to slip a user a page
736 * which submits an edit form to the wiki without their
737 * knowledge, a random token is associated with the login
738 * session. If it's not passed back with the submission,
739 * we won't save the page, or render user JavaScript and
740 * CSS previews.
741 */
742 $token = htmlspecialchars( $wgUser->editToken() );
743 $wgOut->addHTML( "
744 <input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
745 }
746
747
748 if ( $isConflict ) {
749 require_once( "DifferenceEngine.php" );
750 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
751 DifferenceEngine::showDiff( $this->textbox2, $this->textbox1,
752 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
753
754 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
755 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
756 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) .
757 "
758 </textarea>" );
759 }
760 $wgOut->addHTML( "</form>\n" );
761 if ( $formtype == 'preview' && !$wgUser->getOption( 'previewontop' ) ) {
762 $wgOut->addHTML( '<div id="wikiPreview">' . $previewOutput . '</div>' );
763 }
764 if ( $formtype == 'diff' && !$wgUser->getOption( 'previewontop' ) ) {
765 #$wgOut->addHTML( '<div id="wikiPreview">' . $difftext . '</div>' );
766 $wgOut->addHTML( $this->getDiff() );
767 }
768 }
769
770 /**
771 * @todo document
772 */
773 function getPreviewText( $isConflict, $isCssJsSubpage ) {
774 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgAllowDiffPreview, $wgEnableDiffPreviewPreference;
775 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
776 "<p class='previewnote'>" . htmlspecialchars( wfMsg( 'previewnote' ) ) . "</p>\n";
777 if ( $isConflict ) {
778 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) .
779 "</h2>\n";
780 }
781
782 $parserOptions = ParserOptions::newFromUser( $wgUser );
783 $parserOptions->setEditSection( false );
784
785 # don't parse user css/js, show message about preview
786 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
787
788 if ( $isCssJsSubpage ) {
789 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
790 $previewtext = wfMsg('usercsspreview');
791 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
792 $previewtext = wfMsg('userjspreview');
793 }
794 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
795 $wgOut->addHTML( $parserOutput->mText );
796 return $previewhead;
797 } else {
798 # if user want to see preview when he edit an article
799 if( $wgUser->getOption('previewonfirst') and ($this->textbox1 == '')) {
800 $this->textbox1 = $this->mArticle->getContent(true);
801 }
802
803 $toparse = $this->textbox1;
804
805 # If we're adding a comment, we need to show the
806 # summary as the headline
807 if($this->section=="new" && $this->summary!="") {
808 $toparse="== {$this->summary} ==\n\n".$toparse;
809 }
810
811 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
812
813 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
814 $wgTitle, $parserOptions );
815
816 $previewHTML = $parserOutput->mText;
817
818 $wgOut->addCategoryLinks($parserOutput->getCategoryLinks());
819 $wgOut->addLanguageLinks($parserOutput->getLanguageLinks());
820 return $previewhead . $previewHTML;
821 }
822 }
823
824 /**
825 * @todo document
826 */
827 function blockedIPpage() {
828 global $wgOut, $wgUser, $wgContLang, $wgIP;
829
830 $wgOut->setPageTitle( wfMsg( 'blockedtitle' ) );
831 $wgOut->setRobotpolicy( 'noindex,nofollow' );
832 $wgOut->setArticleRelated( false );
833
834 $id = $wgUser->blockedBy();
835 $reason = $wgUser->blockedFor();
836 $ip = $wgIP;
837
838 if ( is_numeric( $id ) ) {
839 $name = User::whoIs( $id );
840 } else {
841 $name = $id;
842 }
843 $link = '[[' . $wgContLang->getNsText( NS_USER ) .
844 ":{$name}|{$name}]]";
845
846 $wgOut->addWikiText( wfMsg( 'blockedtext', $link, $reason, $ip, $name ) );
847 $wgOut->returnToMain( false );
848 }
849
850 /**
851 * @todo document
852 */
853 function userNotLoggedInPage() {
854 global $wgOut;
855
856 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
857 $wgOut->setRobotpolicy( 'noindex,nofollow' );
858 $wgOut->setArticleRelated( false );
859
860 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
861 $wgOut->returnToMain( false );
862 }
863
864 /**
865 * @todo document
866 */
867 function spamPage ( $match = false )
868 {
869 global $wgOut;
870 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
871 $wgOut->setRobotpolicy( 'noindex,nofollow' );
872 $wgOut->setArticleRelated( false );
873
874 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
875 if ( $match ) {
876 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
877 }
878 $wgOut->returnToMain( false );
879 }
880
881 /**
882 * Forks processes to scan the originating IP for an open proxy server
883 * MemCached can be used to skip IPs that have already been scanned
884 */
885 function proxyCheck() {
886 global $wgBlockOpenProxies, $wgProxyPorts, $wgProxyScriptPath;
887 global $wgIP, $wgUseMemCached, $wgMemc, $wgDBname, $wgProxyMemcExpiry;
888
889 if ( !$wgBlockOpenProxies ) {
890 return;
891 }
892
893 # Get MemCached key
894 $skip = false;
895 if ( $wgUseMemCached ) {
896 $mcKey = $wgDBname.':proxy:ip:'.$wgIP;
897 $mcValue = $wgMemc->get( $mcKey );
898 if ( $mcValue ) {
899 $skip = true;
900 }
901 }
902
903 # Fork the processes
904 if ( !$skip ) {
905 $title = Title::makeTitle( NS_SPECIAL, 'Blockme' );
906 $iphash = md5( $wgIP . $wgProxyKey );
907 $url = $title->getFullURL( 'ip='.$iphash );
908
909 foreach ( $wgProxyPorts as $port ) {
910 $params = implode( ' ', array(
911 escapeshellarg( $wgProxyScriptPath ),
912 escapeshellarg( $wgIP ),
913 escapeshellarg( $port ),
914 escapeshellarg( $url )
915 ));
916 exec( "php $params &>/dev/null &" );
917 }
918 # Set MemCached key
919 if ( $wgUseMemCached ) {
920 $wgMemc->set( $mcKey, 1, $wgProxyMemcExpiry );
921 }
922 }
923 }
924
925 /**
926 * @access private
927 * @todo document
928 */
929 function mergeChangesInto( &$editText ){
930 $fname = 'EditPage::mergeChangesInto';
931 wfProfileIn( $fname );
932
933 $db =& wfGetDB( DB_MASTER );
934
935 // This is the revision the editor started from
936 $baseRevision = Revision::loadFromTimestamp(
937 $db, $this->mArticle->mTitle, $this->edittime );
938 if( is_null( $baseRevision ) ) {
939 wfProfileOut( $fname );
940 return false;
941 }
942 $baseText = $baseRevision->getText();
943
944 // The current state, we want to merge updates into it
945 $currentRevision = Revision::loadFromTitle(
946 $db, $this->mArticle->mTitle );
947 if( is_null( $currentRevision ) ) {
948 wfProfileOut( $fname );
949 return false;
950 }
951 $currentText = $currentRevision->getText();
952
953 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
954 $editText = $result;
955 wfProfileOut( $fname );
956 return true;
957 } else {
958 wfProfileOut( $fname );
959 return false;
960 }
961 }
962
963
964 function checkUnicodeCompliantBrowser() {
965 global $wgBrowserBlackList;
966 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
967 foreach ( $wgBrowserBlackList as $browser ) {
968 if ( preg_match($browser, $currentbrowser) ) {
969 return false;
970 }
971 }
972 return true;
973 }
974
975 /**
976 * Format an anchor fragment as it would appear for a given section name
977 * @param string $text
978 * @return string
979 * @access private
980 */
981 function sectionAnchor( $text ) {
982 $headline = Sanitizer::decodeCharReferences( $text );
983 # strip out HTML
984 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
985 $headline = trim( $headline );
986 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
987 $replacearray = array(
988 '%3A' => ':',
989 '%' => '.'
990 );
991 return str_replace(
992 array_keys( $replacearray ),
993 array_values( $replacearray ),
994 $sectionanchor );
995 }
996
997 /**
998 * Shows a bulletin board style toolbar for common editing functions.
999 * It can be disabled in the user preferences.
1000 * The necessary JavaScript code can be found in style/wikibits.js.
1001 */
1002 function getEditToolbar() {
1003 global $wgStylePath, $wgLang, $wgMimeType, $wgJsMimeType;
1004
1005 /**
1006 * toolarray an array of arrays which each include the filename of
1007 * the button image (without path), the opening tag, the closing tag,
1008 * and optionally a sample text that is inserted between the two when no
1009 * selection is highlighted.
1010 * The tip text is shown when the user moves the mouse over the button.
1011 *
1012 * Already here are accesskeys (key), which are not used yet until someone
1013 * can figure out a way to make them work in IE. However, we should make
1014 * sure these keys are not defined on the edit page.
1015 */
1016 $toolarray=array(
1017 array( 'image'=>'button_bold.png',
1018 'open' => "\'\'\'",
1019 'close' => "\'\'\'",
1020 'sample'=> wfMsg('bold_sample'),
1021 'tip' => wfMsg('bold_tip'),
1022 'key' => 'B'
1023 ),
1024 array( 'image'=>'button_italic.png',
1025 'open' => "\'\'",
1026 'close' => "\'\'",
1027 'sample'=> wfMsg('italic_sample'),
1028 'tip' => wfMsg('italic_tip'),
1029 'key' => 'I'
1030 ),
1031 array( 'image'=>'button_link.png',
1032 'open' => '[[',
1033 'close' => ']]',
1034 'sample'=> wfMsg('link_sample'),
1035 'tip' => wfMsg('link_tip'),
1036 'key' => 'L'
1037 ),
1038 array( 'image'=>'button_extlink.png',
1039 'open' => '[',
1040 'close' => ']',
1041 'sample'=> wfMsg('extlink_sample'),
1042 'tip' => wfMsg('extlink_tip'),
1043 'key' => 'X'
1044 ),
1045 array( 'image'=>'button_headline.png',
1046 'open' => "\\n== ",
1047 'close' => " ==\\n",
1048 'sample'=> wfMsg('headline_sample'),
1049 'tip' => wfMsg('headline_tip'),
1050 'key' => 'H'
1051 ),
1052 array( 'image'=>'button_image.png',
1053 'open' => '[['.$wgLang->getNsText(NS_IMAGE).":",
1054 'close' => ']]',
1055 'sample'=> wfMsg('image_sample'),
1056 'tip' => wfMsg('image_tip'),
1057 'key' => 'D'
1058 ),
1059 array( 'image' =>'button_media.png',
1060 'open' => '[['.$wgLang->getNsText(NS_MEDIA).':',
1061 'close' => ']]',
1062 'sample'=> wfMsg('media_sample'),
1063 'tip' => wfMsg('media_tip'),
1064 'key' => 'M'
1065 ),
1066 array( 'image' =>'button_math.png',
1067 'open' => "\\<math\\>",
1068 'close' => "\\</math\\>",
1069 'sample'=> wfMsg('math_sample'),
1070 'tip' => wfMsg('math_tip'),
1071 'key' => 'C'
1072 ),
1073 array( 'image' =>'button_nowiki.png',
1074 'open' => "\\<nowiki\\>",
1075 'close' => "\\</nowiki\\>",
1076 'sample'=> wfMsg('nowiki_sample'),
1077 'tip' => wfMsg('nowiki_tip'),
1078 'key' => 'N'
1079 ),
1080 array( 'image' =>'button_sig.png',
1081 'open' => '--~~~~',
1082 'close' => '',
1083 'sample'=> '',
1084 'tip' => wfMsg('sig_tip'),
1085 'key' => 'Y'
1086 ),
1087 array( 'image' =>'button_hr.png',
1088 'open' => "\\n----\\n",
1089 'close' => '',
1090 'sample'=> '',
1091 'tip' => wfMsg('hr_tip'),
1092 'key' => 'R'
1093 )
1094 );
1095 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1096
1097 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1098 foreach($toolarray as $tool) {
1099
1100 $image=$wgStylePath.'/common/images/'.$tool['image'];
1101 $open=$tool['open'];
1102 $close=$tool['close'];
1103 $sample = wfEscapeJsString( $tool['sample'] );
1104
1105 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1106 // Older browsers show a "speedtip" type message only for ALT.
1107 // Ideally these should be different, realistically they
1108 // probably don't need to be.
1109 $tip = wfEscapeJsString( $tool['tip'] );
1110
1111 #$key = $tool["key"];
1112
1113 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1114 }
1115
1116 $toolbar.="addInfobox('" . wfEscapeJsString( wfMsg( "infobox" ) ) .
1117 "','" . wfEscapeJsString( wfMsg( "infobox_alert" ) ) . "');\n";
1118 $toolbar.="document.writeln(\"</div>\");\n";
1119
1120 $toolbar.="/*]]>*/\n</script>";
1121 return $toolbar;
1122 }
1123
1124 /**
1125 * Output preview text only. This can be sucked into the edit page
1126 * via JavaScript, and saves the server time rendering the skin as
1127 * well as theoretically being more robust on the client (doesn't
1128 * disturb the edit box's undo history, won't eat your text on
1129 * failure, etc).
1130 *
1131 * @todo This doesn't include category or interlanguage links.
1132 * Would need to enhance it a bit, maybe wrap them in XML
1133 * or something... that might also require more skin
1134 * initialization, so check whether that's a problem.
1135 */
1136 function livePreview() {
1137 global $wgOut;
1138 $wgOut->disable();
1139 header( 'Content-type: text/xml' );
1140 header( 'Cache-control: no-cache' );
1141 # FIXME
1142 echo $this->getPreviewText( false, false );
1143 }
1144
1145
1146 /**
1147 * Get a diff between the current contents of the edit box and the
1148 * version of the page we're editing from.
1149 *
1150 * If this is a section edit, we'll replace the section as for final
1151 * save and then make a comparison.
1152 *
1153 * @return string HTML
1154 */
1155 function getDiff() {
1156 require_once( 'DifferenceEngine.php' );
1157 $oldtext = $this->mArticle->fetchContent();
1158 $newtext = $this->mArticle->getTextOfLastEditWithSectionReplacedOrAdded(
1159 $this->section, $this->textbox1, $this->summary, $this->edittime );
1160 $oldtitle = wfMsg( 'currentrev' );
1161 $newtitle = wfMsg( 'yourtext' );
1162 if ( $oldtext != wfMsg( 'noarticletext' ) || $newtext != '' ) {
1163 $difftext = DifferenceEngine::getDiff( $oldtext, $newtext, $oldtitle, $newtitle );
1164 }
1165
1166 return '<div id="wikiDiff">' . $difftext . '</div>';
1167 }
1168
1169 /**
1170 * Filter an input field through a Unicode de-armoring process if it
1171 * came from an old browser with known broken Unicode editing issues.
1172 *
1173 * @param WebRequest $request
1174 * @param string $field
1175 * @return string
1176 * @access private
1177 */
1178 function safeUnicodeInput( $request, $field ) {
1179 $text = rtrim( $request->getText( $field ) );
1180 return $request->getBool( 'safemode' )
1181 ? $this->unmakesafe( $text )
1182 : $text;
1183 }
1184
1185 /**
1186 * Filter an output field through a Unicode armoring process if it is
1187 * going to an old browser with known broken Unicode editing issues.
1188 *
1189 * @param string $text
1190 * @return string
1191 * @access private
1192 */
1193 function safeUnicodeOutput( $text ) {
1194 global $wgContLang;
1195 $codedText = $wgContLang->recodeForEdit( $text );
1196 return $this->checkUnicodeCompliantBrowser()
1197 ? $codedText
1198 : $this->makesafe( $codedText );
1199 }
1200
1201 /**
1202 * A number of web browsers are known to corrupt non-ASCII characters
1203 * in a UTF-8 text editing environment. To protect against this,
1204 * detected browsers will be served an armored version of the text,
1205 * with non-ASCII chars converted to numeric HTML character references.
1206 *
1207 * Preexisting such character references will have a 0 added to them
1208 * to ensure that round-trips do not alter the original data.
1209 *
1210 * @param string $invalue
1211 * @return string
1212 * @access private
1213 */
1214 function makesafe( $invalue ) {
1215 // Armor existing references for reversability.
1216 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1217
1218 $bytesleft = 0;
1219 $result = "";
1220 $working = 0;
1221 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1222 $bytevalue = ord( $invalue{$i} );
1223 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1224 $result .= chr( $bytevalue );
1225 $bytesleft = 0;
1226 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1227 $working = $working << 6;
1228 $working += ($bytevalue & 0x3F);
1229 $bytesleft--;
1230 if( $bytesleft <= 0 ) {
1231 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1232 }
1233 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1234 $working = $bytevalue & 0x1F;
1235 $bytesleft = 1;
1236 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1237 $working = $bytevalue & 0x0F;
1238 $bytesleft = 2;
1239 } else { //1111 0xxx
1240 $working = $bytevalue & 0x07;
1241 $bytesleft = 3;
1242 }
1243 }
1244 return $result;
1245 }
1246
1247 /**
1248 * Reverse the previously applied transliteration of non-ASCII characters
1249 * back to UTF-8. Used to protect data from corruption by broken web browsers
1250 * as listed in $wgBrowserBlackList.
1251 *
1252 * @param string $invalue
1253 * @return string
1254 * @access private
1255 */
1256 function unmakesafe( $invalue ) {
1257 $result = "";
1258 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1259 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
1260 $i += 3;
1261 $hexstring = "";
1262 do {
1263 $hexstring .= $invalue{$i};
1264 $i++;
1265 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1266
1267 // Do some sanity checks. These aren't needed for reversability,
1268 // but should help keep the breakage down if the editor
1269 // breaks one of the entities whilst editing.
1270 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1271 $codepoint = hexdec($hexstring);
1272 $result .= codepointToUtf8( $codepoint );
1273 } else {
1274 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1275 }
1276 } else {
1277 $result .= substr( $invalue, $i, 1 );
1278 }
1279 }
1280 // reverse the transform that we made for reversability reasons.
1281 return strtr( $result, array( "&#x0" => "&#x" ) );
1282 }
1283
1284
1285 }
1286
1287 ?>