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