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