8cad492656ad38d1dfacbe12f10b2f359b03bd12
[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. Don't tokenize.
560 $this->mTokenOk = true;
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 # Reintegrate metadata
602 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
603 $this->mMetaData = '' ;
604
605 # Check for spam
606 $matches = array();
607 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
608 $this->spamPage ( $matches[0] );
609 wfProfileOut( "$fname-checks" );
610 wfProfileOut( $fname );
611 return false;
612 }
613 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
614 # Error messages or other handling should be performed by the filter function
615 wfProfileOut( $fname );
616 wfProfileOut( "$fname-checks" );
617 return false;
618 }
619 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError ) ) ) {
620 # Error messages etc. could be handled within the hook...
621 wfProfileOut( $fname );
622 wfProfileOut( "$fname-checks" );
623 return false;
624 } elseif( $this->hookError != '' ) {
625 # ...or the hook could be expecting us to produce an error
626 wfProfileOut( "$fname-checks " );
627 wfProfileOut( $fname );
628 return true;
629 }
630 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
631 # Check block state against master, thus 'false'.
632 $this->blockedPage();
633 wfProfileOut( "$fname-checks" );
634 wfProfileOut( $fname );
635 return false;
636 }
637 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
638 if ( $this->kblength > $wgMaxArticleSize ) {
639 // Error will be displayed by showEditForm()
640 $this->tooBig = true;
641 wfProfileOut( "$fname-checks" );
642 wfProfileOut( $fname );
643 return true;
644 }
645
646 if ( !$wgUser->isAllowed('edit') ) {
647 if ( $wgUser->isAnon() ) {
648 $this->userNotLoggedInPage();
649 wfProfileOut( "$fname-checks" );
650 wfProfileOut( $fname );
651 return false;
652 }
653 else {
654 $wgOut->readOnlyPage();
655 wfProfileOut( "$fname-checks" );
656 wfProfileOut( $fname );
657 return false;
658 }
659 }
660
661 if ( wfReadOnly() ) {
662 $wgOut->readOnlyPage();
663 wfProfileOut( "$fname-checks" );
664 wfProfileOut( $fname );
665 return false;
666 }
667 if ( $wgUser->pingLimiter() ) {
668 $wgOut->rateLimited();
669 wfProfileOut( "$fname-checks" );
670 wfProfileOut( $fname );
671 return false;
672 }
673
674 # If the article has been deleted while editing, don't save it without
675 # confirmation
676 if ( $this->deletedSinceEdit && !$this->recreate ) {
677 wfProfileOut( "$fname-checks" );
678 wfProfileOut( $fname );
679 return true;
680 }
681
682 wfProfileOut( "$fname-checks" );
683
684 # If article is new, insert it.
685 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
686 if ( 0 == $aid ) {
687 // Late check for create permission, just in case *PARANOIA*
688 if ( !$this->mTitle->userCanCreate() ) {
689 wfDebug( "$fname: no create permission\n" );
690 $this->noCreatePermission();
691 wfProfileOut( $fname );
692 return;
693 }
694
695 # Don't save a new article if it's blank.
696 if ( ( '' == $this->textbox1 ) ) {
697 $wgOut->redirect( $this->mTitle->getFullURL() );
698 wfProfileOut( $fname );
699 return false;
700 }
701
702 $isComment=($this->section=='new');
703 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
704 $this->minoredit, $this->watchthis, false, $isComment);
705
706 wfProfileOut( $fname );
707 return false;
708 }
709
710 # Article exists. Check for edit conflict.
711
712 $this->mArticle->clear(); # Force reload of dates, etc.
713 $this->mArticle->forUpdate( true ); # Lock the article
714
715 if( $this->mArticle->getTimestamp() != $this->edittime ) {
716 $this->isConflict = true;
717 if( $this->section == 'new' ) {
718 if( $this->mArticle->getUserText() == $wgUser->getName() &&
719 $this->mArticle->getComment() == $this->summary ) {
720 // Probably a duplicate submission of a new comment.
721 // This can happen when squid resends a request after
722 // a timeout but the first one actually went through.
723 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
724 } else {
725 // New comment; suppress conflict.
726 $this->isConflict = false;
727 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
728 }
729 }
730 }
731 $userid = $wgUser->getID();
732
733 if ( $this->isConflict) {
734 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
735 $this->mArticle->getTimestamp() . "'\n" );
736 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
737 }
738 else {
739 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
740 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
741 }
742 if( is_null( $text ) ) {
743 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
744 $this->isConflict = true;
745 $text = $this->textbox1;
746 }
747
748 # Suppress edit conflict with self, except for section edits where merging is required.
749 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
750 wfDebug( "Suppressing edit conflict, same user.\n" );
751 $this->isConflict = false;
752 } else {
753 # switch from section editing to normal editing in edit conflict
754 if($this->isConflict) {
755 # Attempt merge
756 if( $this->mergeChangesInto( $text ) ){
757 // Successful merge! Maybe we should tell the user the good news?
758 $this->isConflict = false;
759 wfDebug( "Suppressing edit conflict, successful merge.\n" );
760 } else {
761 $this->section = '';
762 $this->textbox1 = $text;
763 wfDebug( "Keeping edit conflict, failed merge.\n" );
764 }
765 }
766 }
767
768 if ( $this->isConflict ) {
769 wfProfileOut( $fname );
770 return true;
771 }
772
773 $oldtext = $this->mArticle->getContent();
774
775 # Handle the user preference to force summaries here, but not for null edits
776 if( $this->section != 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary')
777 && 0 != strcmp($oldtext, $text) && !Article::getRedirectAutosummary( $text )) {
778 if( md5( $this->summary ) == $this->autoSumm ) {
779 $this->missingSummary = true;
780 wfProfileOut( $fname );
781 return( true );
782 }
783 }
784
785 #And a similar thing for new sections
786 if( $this->section == 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary' ) ) {
787 if (trim($this->summary) == '') {
788 $this->missingSummary = true;
789 wfProfileOut( $fname );
790 return( true );
791 }
792 }
793
794 # All's well
795 wfProfileIn( "$fname-sectionanchor" );
796 $sectionanchor = '';
797 if( $this->section == 'new' ) {
798 if ( $this->textbox1 == '' ) {
799 $this->missingComment = true;
800 return true;
801 }
802 if( $this->summary != '' ) {
803 $sectionanchor = $this->sectionAnchor( $this->summary );
804 }
805 } elseif( $this->section != '' ) {
806 # Try to get a section anchor from the section source, redirect to edited section if header found
807 # XXX: might be better to integrate this into Article::replaceSection
808 # for duplicate heading checking and maybe parsing
809 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
810 # we can't deal with anchors, includes, html etc in the header for now,
811 # headline would need to be parsed to improve this
812 if($hasmatch and strlen($matches[2]) > 0) {
813 $sectionanchor = $this->sectionAnchor( $matches[2] );
814 }
815 }
816 wfProfileOut( "$fname-sectionanchor" );
817
818 // Save errors may fall down to the edit form, but we've now
819 // merged the section into full text. Clear the section field
820 // so that later submission of conflict forms won't try to
821 // replace that into a duplicated mess.
822 $this->textbox1 = $text;
823 $this->section = '';
824
825 // Check for length errors again now that the section is merged in
826 $this->kblength = (int)(strlen( $text ) / 1024);
827 if ( $this->kblength > $wgMaxArticleSize ) {
828 $this->tooBig = true;
829 wfProfileOut( $fname );
830 return true;
831 }
832
833 # update the article here
834 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
835 $this->watchthis, '', $sectionanchor ) ) {
836 wfProfileOut( $fname );
837 return false;
838 } else {
839 $this->isConflict = true;
840 }
841 wfProfileOut( $fname );
842 return true;
843 }
844
845 /**
846 * Initialise form fields in the object
847 * Called on the first invocation, e.g. when a user clicks an edit link
848 */
849 function initialiseForm() {
850 $this->edittime = $this->mArticle->getTimestamp();
851 $this->summary = '';
852 $this->textbox1 = $this->getContent();
853 if ( !$this->mArticle->exists() && $this->mArticle->mTitle->getNamespace() == NS_MEDIAWIKI )
854 $this->textbox1 = wfMsgWeirdKey( $this->mArticle->mTitle->getText() ) ;
855 wfProxyCheck();
856 }
857
858 /**
859 * Send the edit form and related headers to $wgOut
860 * @param $formCallback Optional callable that takes an OutputPage
861 * parameter; will be called during form output
862 * near the top, for captchas and the like.
863 */
864 function showEditForm( $formCallback=null ) {
865 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
866
867 $fname = 'EditPage::showEditForm';
868 wfProfileIn( $fname );
869
870 $sk =& $wgUser->getSkin();
871
872 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
873
874 $wgOut->setRobotpolicy( 'noindex,nofollow' );
875
876 # Enabled article-related sidebar, toplinks, etc.
877 $wgOut->setArticleRelated( true );
878
879 if ( $this->isConflict ) {
880 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
881 $wgOut->setPageTitle( $s );
882 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
883
884 $this->textbox2 = $this->textbox1;
885 $this->textbox1 = $this->getContent();
886 $this->edittime = $this->mArticle->getTimestamp();
887 } else {
888
889 if( $this->section != '' ) {
890 if( $this->section == 'new' ) {
891 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
892 } else {
893 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
894 $matches = array();
895 if( !$this->summary && !$this->preview && !$this->diff ) {
896 preg_match( "/^(=+)(.+)\\1/mi",
897 $this->textbox1,
898 $matches );
899 if( !empty( $matches[2] ) ) {
900 $this->summary = "/* ". trim($matches[2])." */ ";
901 }
902 }
903 }
904 } else {
905 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
906 }
907 $wgOut->setPageTitle( $s );
908
909 if ( $this->missingComment ) {
910 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
911 }
912
913 if( $this->missingSummary && $this->section != 'new' ) {
914 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
915 }
916
917 if( $this->missingSummary && $this->section == 'new' ) {
918 $wgOut->addWikiText( wfMsg( 'missingcommentheader' ) );
919 }
920
921 if( !$this->hookError == '' ) {
922 $wgOut->addWikiText( $this->hookError );
923 }
924
925 if ( !$this->checkUnicodeCompliantBrowser() ) {
926 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
927 }
928 if ( isset( $this->mArticle )
929 && isset( $this->mArticle->mRevision )
930 && !$this->mArticle->mRevision->isCurrent() ) {
931 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
932 $wgOut->addWikiText( wfMsg( 'editingold' ) );
933 }
934 }
935
936 if( wfReadOnly() ) {
937 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
938 } elseif( $wgUser->isAnon() && $this->formtype != 'preview' ) {
939 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
940 } else {
941 if( $this->isCssJsSubpage && $this->formtype != 'preview' ) {
942 # Check the skin exists
943 if( $this->isValidCssJsSubpage ) {
944 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
945 } else {
946 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
947 }
948 }
949 }
950
951 if( $this->mTitle->isProtected( 'edit' ) ) {
952 # Is the protection due to the namespace, e.g. interface text?
953 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
954 # Yes; remind the user
955 $notice = wfMsg( 'editinginterface' );
956 } elseif( $this->mTitle->isSemiProtected() ) {
957 # No; semi protected
958 $notice = wfMsg( 'semiprotectedpagewarning' );
959 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) || $notice == '-' ) {
960 $notice = '';
961 }
962 } else {
963 # No; regular protection
964 $notice = wfMsg( 'protectedpagewarning' );
965 }
966 $wgOut->addWikiText( $notice );
967 }
968
969 if ( $this->kblength === false ) {
970 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
971 }
972 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
973 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize ) );
974 } elseif( $this->kblength > 29 ) {
975 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ) );
976 }
977
978 #need to parse the preview early so that we know which templates are used,
979 #otherwise users with "show preview after edit box" will get a blank list
980 $previewOutput = $this->getPreviewText();
981
982 $rows = $wgUser->getIntOption( 'rows' );
983 $cols = $wgUser->getIntOption( 'cols' );
984
985 $ew = $wgUser->getOption( 'editwidth' );
986 if ( $ew ) $ew = " style=\"width:100%\"";
987 else $ew = '';
988
989 $q = 'action=submit';
990 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
991 $action = $this->mTitle->escapeLocalURL( $q );
992
993 $summary = wfMsg('summary');
994 $subject = wfMsg('subject');
995 $minor = wfMsgExt('minoredit', array('parseinline'));
996 $watchthis = wfMsgExt('watchthis', array('parseinline'));
997
998 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
999 wfMsgExt('cancel', array('parseinline')) );
1000 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1001 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1002 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1003 htmlspecialchars( wfMsg( 'newwindow' ) );
1004
1005 global $wgRightsText;
1006 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1007 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
1008 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1009 $wgRightsText ) . "\n</div>";
1010
1011 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
1012 # prepare toolbar for edit buttons
1013 $toolbar = $this->getEditToolbar();
1014 } else {
1015 $toolbar = '';
1016 }
1017
1018 // activate checkboxes if user wants them to be always active
1019 if( !$this->preview && !$this->diff ) {
1020 # Sort out the "watch" checkbox
1021 if( $wgUser->getOption( 'watchdefault' ) ) {
1022 # Watch all edits
1023 $this->watchthis = true;
1024 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1025 # Watch creations
1026 $this->watchthis = true;
1027 } elseif( $this->mTitle->userIsWatching() ) {
1028 # Already watched
1029 $this->watchthis = true;
1030 }
1031
1032 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
1033 }
1034
1035 $minoredithtml = '';
1036
1037 if ( $wgUser->isAllowed('minoredit') ) {
1038 $minoredithtml =
1039 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
1040 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />\n".
1041 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>\n";
1042 }
1043
1044 $watchhtml = '';
1045
1046 if ( $wgUser->isLoggedIn() ) {
1047 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
1048 ($this->watchthis?" checked='checked'":"").
1049 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />\n".
1050 "<label for='wpWatchthis' title=\"" .
1051 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>\n";
1052 }
1053
1054 $checkboxhtml = $minoredithtml . $watchhtml;
1055
1056 $wgOut->addHTML( $this->editFormPageTop );
1057
1058 if ( $wgUser->getOption( 'previewontop' ) ) {
1059
1060 if ( 'preview' == $this->formtype ) {
1061 $this->showPreview( $previewOutput );
1062 } else {
1063 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1064 }
1065
1066 if ( 'diff' == $this->formtype ) {
1067 $wgOut->addHTML( $this->getDiff() );
1068 }
1069 }
1070
1071
1072 $wgOut->addHTML( $this->editFormTextTop );
1073
1074 # if this is a comment, show a subject line at the top, which is also the edit summary.
1075 # Otherwise, show a summary field at the bottom
1076 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
1077 if( $this->section == 'new' ) {
1078 $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 />";
1079 $editsummary = '';
1080 $subjectpreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1081 $summarypreview = '';
1082 } else {
1083 $commentsubject = '';
1084 $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 />";
1085 $summarypreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1086 $subjectpreview = '';
1087 }
1088
1089 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1090 if( !$this->preview && !$this->diff ) {
1091 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1092 }
1093 $templates = ($this->preview || $this->section) ? $this->mPreviewTemplates : $this->mArticle->getUsedTemplates();
1094 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != '');
1095
1096 global $wgUseMetadataEdit ;
1097 if ( $wgUseMetadataEdit ) {
1098 $metadata = $this->mMetaData ;
1099 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1100 $top = wfMsgWikiHtml( 'metadata_help' );
1101 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1102 }
1103 else $metadata = "" ;
1104
1105 $hidden = '';
1106 $recreate = '';
1107 if ($this->deletedSinceEdit) {
1108 if ( 'save' != $this->formtype ) {
1109 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1110 } else {
1111 // Hide the toolbar and edit area, use can click preview to get it back
1112 // Add an confirmation checkbox and explanation.
1113 $toolbar = '';
1114 $hidden = 'type="hidden" style="display:none;"';
1115 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
1116 $recreate .=
1117 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1118 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1119 }
1120 }
1121
1122 $temp = array(
1123 'id' => 'wpSave',
1124 'name' => 'wpSave',
1125 'type' => 'submit',
1126 'tabindex' => '5',
1127 'value' => wfMsg('savearticle'),
1128 'accesskey' => wfMsg('accesskey-save'),
1129 'title' => wfMsg('tooltip-save'),
1130 );
1131 $buttons['save'] = wfElement('input', $temp, '');
1132 $temp = array(
1133 'id' => 'wpDiff',
1134 'name' => 'wpDiff',
1135 'type' => 'submit',
1136 'tabindex' => '7',
1137 'value' => wfMsg('showdiff'),
1138 'accesskey' => wfMsg('accesskey-diff'),
1139 'title' => wfMsg('tooltip-diff'),
1140 );
1141 $buttons['diff'] = wfElement('input', $temp, '');
1142
1143 global $wgLivePreview;
1144 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1145 $temp = array(
1146 'id' => 'wpPreview',
1147 'name' => 'wpPreview',
1148 'type' => 'submit',
1149 'tabindex' => '6',
1150 'value' => wfMsg('showpreview'),
1151 'accesskey' => '',
1152 'title' => wfMsg('tooltip-preview'),
1153 'style' => 'display: none;',
1154 );
1155 $buttons['preview'] = wfElement('input', $temp, '');
1156 $temp = array(
1157 'id' => 'wpLivePreview',
1158 'name' => 'wpLivePreview',
1159 'type' => 'submit',
1160 'tabindex' => '6',
1161 'value' => wfMsg('showlivepreview'),
1162 'accesskey' => wfMsg('accesskey-preview'),
1163 'title' => '',
1164 'onclick' => $this->doLivePreviewScript(),
1165 );
1166 $buttons['live'] = wfElement('input', $temp, '');
1167 } else {
1168 $temp = array(
1169 'id' => 'wpPreview',
1170 'name' => 'wpPreview',
1171 'type' => 'submit',
1172 'tabindex' => '6',
1173 'value' => wfMsg('showpreview'),
1174 'accesskey' => wfMsg('accesskey-preview'),
1175 'title' => wfMsg('tooltip-preview'),
1176 );
1177 $buttons['preview'] = wfElement('input', $temp, '');
1178 $buttons['live'] = '';
1179 }
1180
1181 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1182 ? ""
1183 : "<input type='hidden' name=\"safemode\" value='1' />\n";
1184
1185 $wgOut->addHTML( <<<END
1186 {$toolbar}
1187 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1188 END
1189 );
1190
1191 if( is_callable( $formCallback ) ) {
1192 call_user_func_array( $formCallback, array( &$wgOut ) );
1193 }
1194
1195 // Put these up at the top to ensure they aren't lost on early form submission
1196 $wgOut->addHTML( "
1197 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1198 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1199 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1200 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1201
1202 $wgOut->addHTML( <<<END
1203 $recreate
1204 {$commentsubject}
1205 {$subjectpreview}
1206 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1207 cols='{$cols}'{$ew} $hidden>
1208 END
1209 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
1210 "
1211 </textarea>
1212 " );
1213
1214 $wgOut->addWikiText( $copywarn );
1215 $wgOut->addHTML( $this->editFormTextAfterWarn );
1216 $wgOut->addHTML( "
1217 {$metadata}
1218 {$editsummary}
1219 {$summarypreview}
1220 {$checkboxhtml}
1221 {$safemodehtml}
1222 ");
1223
1224 $wgOut->addHTML(
1225 "<div class='editButtons'>
1226 {$buttons['save']}
1227 {$buttons['preview']}
1228 {$buttons['live']}
1229 {$buttons['diff']}
1230 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1231 </div><!-- editButtons -->
1232 </div><!-- editOptions -->");
1233
1234 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1235 $wgOut->addHTML( $this->editFormTextAfterTools );
1236
1237 $wgOut->addHTML( "
1238 <div class='templatesUsed'>
1239 {$formattedtemplates}
1240 </div>
1241 " );
1242
1243 if ( $wgUser->isLoggedIn() ) {
1244 /**
1245 * To make it harder for someone to slip a user a page
1246 * which submits an edit form to the wiki without their
1247 * knowledge, a random token is associated with the login
1248 * session. If it's not passed back with the submission,
1249 * we won't save the page, or render user JavaScript and
1250 * CSS previews.
1251 */
1252 $token = htmlspecialchars( $wgUser->editToken() );
1253 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1254 }
1255
1256 # If a blank edit summary was previously provided, and the appropriate
1257 # user preference is active, pass a hidden tag here. This will stop the
1258 # user being bounced back more than once in the event that a summary
1259 # is not required.
1260 if( $this->missingSummary ) {
1261 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1262 }
1263
1264 # For a bit more sophisticated detection of blank summaries, hash the
1265 # automatic one and pass that in a hidden field.
1266 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1267 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1268
1269 if ( $this->isConflict ) {
1270 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1271
1272 $de = new DifferenceEngine( $this->mTitle );
1273 $de->setText( $this->textbox2, $this->textbox1 );
1274 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1275
1276 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1277 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1278 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1279 }
1280 $wgOut->addHTML( $this->editFormTextBottom );
1281 $wgOut->addHTML( "</form>\n" );
1282 if ( !$wgUser->getOption( 'previewontop' ) ) {
1283
1284 if ( $this->formtype == 'preview') {
1285 $this->showPreview( $previewOutput );
1286 } else {
1287 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1288 }
1289
1290 if ( $this->formtype == 'diff') {
1291 $wgOut->addHTML( $this->getDiff() );
1292 }
1293
1294 }
1295
1296 wfProfileOut( $fname );
1297 }
1298
1299 /**
1300 * Append preview output to $wgOut.
1301 * Includes category rendering if this is a category page.
1302 *
1303 * @param string $text The HTML to be output for the preview.
1304 */
1305 private function showPreview( $text ) {
1306 global $wgOut;
1307
1308 $wgOut->addHTML( '<div id="wikiPreview">' );
1309 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1310 $this->mArticle->openShowCategory();
1311 }
1312 $wgOut->addHTML( $text );
1313 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1314 $this->mArticle->closeShowCategory();
1315 }
1316 $wgOut->addHTML( '</div>' );
1317 }
1318
1319 /**
1320 * Live Preview lets us fetch rendered preview page content and
1321 * add it to the page without refreshing the whole page.
1322 * If not supported by the browser it will fall through to the normal form
1323 * submission method.
1324 *
1325 * This function outputs a script tag to support live preview, and
1326 * returns an onclick handler which should be added to the attributes
1327 * of the preview button
1328 */
1329 function doLivePreviewScript() {
1330 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1331 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1332 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1333 '"></script>' . "\n" );
1334 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1335 return "return !livePreview(" .
1336 "getElementById('wikiPreview')," .
1337 "editform.wpTextbox1.value," .
1338 '"' . $liveAction . '"' . ")";
1339 }
1340
1341 function getLastDelete() {
1342 $dbr =& wfGetDB( DB_SLAVE );
1343 $fname = 'EditPage::getLastDelete';
1344 $res = $dbr->select(
1345 array( 'logging', 'user' ),
1346 array( 'log_type',
1347 'log_action',
1348 'log_timestamp',
1349 'log_user',
1350 'log_namespace',
1351 'log_title',
1352 'log_comment',
1353 'log_params',
1354 'user_name', ),
1355 array( 'log_namespace' => $this->mTitle->getNamespace(),
1356 'log_title' => $this->mTitle->getDBkey(),
1357 'log_type' => 'delete',
1358 'log_action' => 'delete',
1359 'user_id=log_user' ),
1360 $fname,
1361 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1362
1363 if($dbr->numRows($res) == 1) {
1364 while ( $x = $dbr->fetchObject ( $res ) )
1365 $data = $x;
1366 $dbr->freeResult ( $res ) ;
1367 } else {
1368 $data = null;
1369 }
1370 return $data;
1371 }
1372
1373 /**
1374 * @todo document
1375 */
1376 function getPreviewText() {
1377 global $wgOut, $wgUser, $wgTitle, $wgParser;
1378
1379 $fname = 'EditPage::getPreviewText';
1380 wfProfileIn( $fname );
1381
1382 if ( $this->mTriedSave && !$this->mTokenOk ) {
1383 $msg = 'session_fail_preview';
1384 } else {
1385 $msg = 'previewnote';
1386 }
1387 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1388 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1389 if ( $this->isConflict ) {
1390 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1391 }
1392
1393 $parserOptions = ParserOptions::newFromUser( $wgUser );
1394 $parserOptions->setEditSection( false );
1395
1396 global $wgRawHtml;
1397 if( $wgRawHtml && !$this->mTokenOk ) {
1398 // Could be an offsite preview attempt. This is very unsafe if
1399 // HTML is enabled, as it could be an attack.
1400 return $wgOut->parse( "<div class='previewnote'>" .
1401 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1402 }
1403
1404 # don't parse user css/js, show message about preview
1405 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1406
1407 if ( $this->isCssJsSubpage ) {
1408 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1409 $previewtext = wfMsg('usercsspreview');
1410 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1411 $previewtext = wfMsg('userjspreview');
1412 }
1413 $parserOptions->setTidy(true);
1414 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1415 $wgOut->addHTML( $parserOutput->mText );
1416 wfProfileOut( $fname );
1417 return $previewhead;
1418 } else {
1419 $toparse = $this->textbox1;
1420
1421 # If we're adding a comment, we need to show the
1422 # summary as the headline
1423 if($this->section=="new" && $this->summary!="") {
1424 $toparse="== {$this->summary} ==\n\n".$toparse;
1425 }
1426
1427 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1428 $parserOptions->setTidy(true);
1429 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1430 $wgTitle, $parserOptions );
1431
1432 $previewHTML = $parserOutput->getText();
1433 $wgOut->addParserOutputNoText( $parserOutput );
1434
1435 foreach ( $parserOutput->getTemplates() as $ns => $template)
1436 foreach ( array_keys( $template ) as $dbk)
1437 $this->mPreviewTemplates[] = Title::makeTitle($ns, $dbk);
1438
1439 wfProfileOut( $fname );
1440 return $previewhead . $previewHTML;
1441 }
1442 }
1443
1444 /**
1445 * Call the stock "user is blocked" page
1446 */
1447 function blockedPage() {
1448 global $wgOut, $wgUser;
1449 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1450
1451 # If the user made changes, preserve them when showing the markup
1452 # (This happens when a user is blocked during edit, for instance)
1453 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
1454 if( $first ) {
1455 $source = $this->mTitle->exists() ? $this->getContent() : false;
1456 } else {
1457 $source = $this->textbox1;
1458 }
1459
1460 # Spit out the source or the user's modified version
1461 if( $source !== false ) {
1462 $rows = $wgUser->getOption( 'rows' );
1463 $cols = $wgUser->getOption( 'cols' );
1464 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1465 $wgOut->addHtml( '<hr />' );
1466 $wgOut->addWikiText( wfMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() ) );
1467 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1468 }
1469 }
1470
1471 /**
1472 * Produce the stock "please login to edit pages" page
1473 */
1474 function userNotLoggedInPage() {
1475 global $wgUser, $wgOut;
1476 $skin = $wgUser->getSkin();
1477
1478 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1479 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle->getPrefixedUrl() );
1480
1481 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1482 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1483 $wgOut->setArticleRelated( false );
1484
1485 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1486 $wgOut->returnToMain( false, $this->mTitle->getPrefixedUrl() );
1487 }
1488
1489 /**
1490 * Creates a basic error page which informs the user that
1491 * they have to validate their email address before being
1492 * allowed to edit.
1493 */
1494 function userNotConfirmedPage() {
1495 global $wgOut;
1496
1497 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1498 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1499 $wgOut->setArticleRelated( false );
1500
1501 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1502 $wgOut->returnToMain( false );
1503 }
1504
1505 /**
1506 * Produce the stock "your edit contains spam" page
1507 *
1508 * @param $match Text which triggered one or more filters
1509 */
1510 function spamPage( $match = false ) {
1511 global $wgOut;
1512
1513 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1514 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1515 $wgOut->setArticleRelated( false );
1516
1517 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1518 if ( $match )
1519 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1520
1521 $wgOut->returnToMain( false );
1522 }
1523
1524 /**
1525 * @private
1526 * @todo document
1527 */
1528 function mergeChangesInto( &$editText ){
1529 $fname = 'EditPage::mergeChangesInto';
1530 wfProfileIn( $fname );
1531
1532 $db =& wfGetDB( DB_MASTER );
1533
1534 // This is the revision the editor started from
1535 $baseRevision = Revision::loadFromTimestamp(
1536 $db, $this->mArticle->mTitle, $this->edittime );
1537 if( is_null( $baseRevision ) ) {
1538 wfProfileOut( $fname );
1539 return false;
1540 }
1541 $baseText = $baseRevision->getText();
1542
1543 // The current state, we want to merge updates into it
1544 $currentRevision = Revision::loadFromTitle(
1545 $db, $this->mArticle->mTitle );
1546 if( is_null( $currentRevision ) ) {
1547 wfProfileOut( $fname );
1548 return false;
1549 }
1550 $currentText = $currentRevision->getText();
1551
1552 $result = '';
1553 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1554 $editText = $result;
1555 wfProfileOut( $fname );
1556 return true;
1557 } else {
1558 wfProfileOut( $fname );
1559 return false;
1560 }
1561 }
1562
1563 /**
1564 * Check if the browser is on a blacklist of user-agents known to
1565 * mangle UTF-8 data on form submission. Returns true if Unicode
1566 * should make it through, false if it's known to be a problem.
1567 * @return bool
1568 * @private
1569 */
1570 function checkUnicodeCompliantBrowser() {
1571 global $wgBrowserBlackList;
1572 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1573 // No User-Agent header sent? Trust it by default...
1574 return true;
1575 }
1576 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1577 foreach ( $wgBrowserBlackList as $browser ) {
1578 if ( preg_match($browser, $currentbrowser) ) {
1579 return false;
1580 }
1581 }
1582 return true;
1583 }
1584
1585 /**
1586 * Format an anchor fragment as it would appear for a given section name
1587 * @param string $text
1588 * @return string
1589 * @private
1590 */
1591 function sectionAnchor( $text ) {
1592 $headline = Sanitizer::decodeCharReferences( $text );
1593 # strip out HTML
1594 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1595 $headline = trim( $headline );
1596 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1597 $replacearray = array(
1598 '%3A' => ':',
1599 '%' => '.'
1600 );
1601 return str_replace(
1602 array_keys( $replacearray ),
1603 array_values( $replacearray ),
1604 $sectionanchor );
1605 }
1606
1607 /**
1608 * Shows a bulletin board style toolbar for common editing functions.
1609 * It can be disabled in the user preferences.
1610 * The necessary JavaScript code can be found in style/wikibits.js.
1611 */
1612 function getEditToolbar() {
1613 global $wgStylePath, $wgContLang, $wgJsMimeType;
1614
1615 /**
1616 * toolarray an array of arrays which each include the filename of
1617 * the button image (without path), the opening tag, the closing tag,
1618 * and optionally a sample text that is inserted between the two when no
1619 * selection is highlighted.
1620 * The tip text is shown when the user moves the mouse over the button.
1621 *
1622 * Already here are accesskeys (key), which are not used yet until someone
1623 * can figure out a way to make them work in IE. However, we should make
1624 * sure these keys are not defined on the edit page.
1625 */
1626 $toolarray=array(
1627 array( 'image'=>'button_bold.png',
1628 'open' => "\'\'\'",
1629 'close' => "\'\'\'",
1630 'sample'=> wfMsg('bold_sample'),
1631 'tip' => wfMsg('bold_tip'),
1632 'key' => 'B'
1633 ),
1634 array( 'image'=>'button_italic.png',
1635 'open' => "\'\'",
1636 'close' => "\'\'",
1637 'sample'=> wfMsg('italic_sample'),
1638 'tip' => wfMsg('italic_tip'),
1639 'key' => 'I'
1640 ),
1641 array( 'image'=>'button_link.png',
1642 'open' => '[[',
1643 'close' => ']]',
1644 'sample'=> wfMsg('link_sample'),
1645 'tip' => wfMsg('link_tip'),
1646 'key' => 'L'
1647 ),
1648 array( 'image'=>'button_extlink.png',
1649 'open' => '[',
1650 'close' => ']',
1651 'sample'=> wfMsg('extlink_sample'),
1652 'tip' => wfMsg('extlink_tip'),
1653 'key' => 'X'
1654 ),
1655 array( 'image'=>'button_headline.png',
1656 'open' => "\\n== ",
1657 'close' => " ==\\n",
1658 'sample'=> wfMsg('headline_sample'),
1659 'tip' => wfMsg('headline_tip'),
1660 'key' => 'H'
1661 ),
1662 array( 'image'=>'button_image.png',
1663 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).":",
1664 'close' => ']]',
1665 'sample'=> wfMsg('image_sample'),
1666 'tip' => wfMsg('image_tip'),
1667 'key' => 'D'
1668 ),
1669 array( 'image' =>'button_media.png',
1670 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1671 'close' => ']]',
1672 'sample'=> wfMsg('media_sample'),
1673 'tip' => wfMsg('media_tip'),
1674 'key' => 'M'
1675 ),
1676 array( 'image' =>'button_math.png',
1677 'open' => "<math>",
1678 'close' => "<\\/math>",
1679 'sample'=> wfMsg('math_sample'),
1680 'tip' => wfMsg('math_tip'),
1681 'key' => 'C'
1682 ),
1683 array( 'image' =>'button_nowiki.png',
1684 'open' => "<nowiki>",
1685 'close' => "<\\/nowiki>",
1686 'sample'=> wfMsg('nowiki_sample'),
1687 'tip' => wfMsg('nowiki_tip'),
1688 'key' => 'N'
1689 ),
1690 array( 'image' =>'button_sig.png',
1691 'open' => '--~~~~',
1692 'close' => '',
1693 'sample'=> '',
1694 'tip' => wfMsg('sig_tip'),
1695 'key' => 'Y'
1696 ),
1697 array( 'image' =>'button_hr.png',
1698 'open' => "\\n----\\n",
1699 'close' => '',
1700 'sample'=> '',
1701 'tip' => wfMsg('hr_tip'),
1702 'key' => 'R'
1703 )
1704 );
1705 $toolbar = "<div id='toolbar'>\n";
1706 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1707
1708 foreach($toolarray as $tool) {
1709
1710 $image=$wgStylePath.'/common/images/'.$tool['image'];
1711 $open=$tool['open'];
1712 $close=$tool['close'];
1713 $sample = wfEscapeJsString( $tool['sample'] );
1714
1715 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1716 // Older browsers show a "speedtip" type message only for ALT.
1717 // Ideally these should be different, realistically they
1718 // probably don't need to be.
1719 $tip = wfEscapeJsString( $tool['tip'] );
1720
1721 #$key = $tool["key"];
1722
1723 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1724 }
1725
1726 $toolbar.="/*]]>*/\n</script>";
1727 $toolbar.="\n</div>";
1728 return $toolbar;
1729 }
1730
1731 /**
1732 * Output preview text only. This can be sucked into the edit page
1733 * via JavaScript, and saves the server time rendering the skin as
1734 * well as theoretically being more robust on the client (doesn't
1735 * disturb the edit box's undo history, won't eat your text on
1736 * failure, etc).
1737 *
1738 * @todo This doesn't include category or interlanguage links.
1739 * Would need to enhance it a bit, maybe wrap them in XML
1740 * or something... that might also require more skin
1741 * initialization, so check whether that's a problem.
1742 */
1743 function livePreview() {
1744 global $wgOut;
1745 $wgOut->disable();
1746 header( 'Content-type: text/xml' );
1747 header( 'Cache-control: no-cache' );
1748 # FIXME
1749 echo $this->getPreviewText( );
1750 /* To not shake screen up and down between preview and live-preview */
1751 echo "<br style=\"clear:both;\" />\n";
1752 }
1753
1754
1755 /**
1756 * Get a diff between the current contents of the edit box and the
1757 * version of the page we're editing from.
1758 *
1759 * If this is a section edit, we'll replace the section as for final
1760 * save and then make a comparison.
1761 *
1762 * @return string HTML
1763 */
1764 function getDiff() {
1765 $oldtext = $this->mArticle->fetchContent();
1766 $newtext = $this->mArticle->replaceSection(
1767 $this->section, $this->textbox1, $this->summary, $this->edittime );
1768 $newtext = $this->mArticle->preSaveTransform( $newtext );
1769 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1770 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1771 if ( $oldtext !== false || $newtext != '' ) {
1772 $de = new DifferenceEngine( $this->mTitle );
1773 $de->setText( $oldtext, $newtext );
1774 $difftext = $de->getDiff( $oldtitle, $newtitle );
1775 } else {
1776 $difftext = '';
1777 }
1778
1779 return '<div id="wikiDiff">' . $difftext . '</div>';
1780 }
1781
1782 /**
1783 * Filter an input field through a Unicode de-armoring process if it
1784 * came from an old browser with known broken Unicode editing issues.
1785 *
1786 * @param WebRequest $request
1787 * @param string $field
1788 * @return string
1789 * @private
1790 */
1791 function safeUnicodeInput( $request, $field ) {
1792 $text = rtrim( $request->getText( $field ) );
1793 return $request->getBool( 'safemode' )
1794 ? $this->unmakesafe( $text )
1795 : $text;
1796 }
1797
1798 /**
1799 * Filter an output field through a Unicode armoring process if it is
1800 * going to an old browser with known broken Unicode editing issues.
1801 *
1802 * @param string $text
1803 * @return string
1804 * @private
1805 */
1806 function safeUnicodeOutput( $text ) {
1807 global $wgContLang;
1808 $codedText = $wgContLang->recodeForEdit( $text );
1809 return $this->checkUnicodeCompliantBrowser()
1810 ? $codedText
1811 : $this->makesafe( $codedText );
1812 }
1813
1814 /**
1815 * A number of web browsers are known to corrupt non-ASCII characters
1816 * in a UTF-8 text editing environment. To protect against this,
1817 * detected browsers will be served an armored version of the text,
1818 * with non-ASCII chars converted to numeric HTML character references.
1819 *
1820 * Preexisting such character references will have a 0 added to them
1821 * to ensure that round-trips do not alter the original data.
1822 *
1823 * @param string $invalue
1824 * @return string
1825 * @private
1826 */
1827 function makesafe( $invalue ) {
1828 // Armor existing references for reversability.
1829 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1830
1831 $bytesleft = 0;
1832 $result = "";
1833 $working = 0;
1834 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1835 $bytevalue = ord( $invalue{$i} );
1836 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1837 $result .= chr( $bytevalue );
1838 $bytesleft = 0;
1839 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1840 $working = $working << 6;
1841 $working += ($bytevalue & 0x3F);
1842 $bytesleft--;
1843 if( $bytesleft <= 0 ) {
1844 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1845 }
1846 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1847 $working = $bytevalue & 0x1F;
1848 $bytesleft = 1;
1849 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1850 $working = $bytevalue & 0x0F;
1851 $bytesleft = 2;
1852 } else { //1111 0xxx
1853 $working = $bytevalue & 0x07;
1854 $bytesleft = 3;
1855 }
1856 }
1857 return $result;
1858 }
1859
1860 /**
1861 * Reverse the previously applied transliteration of non-ASCII characters
1862 * back to UTF-8. Used to protect data from corruption by broken web browsers
1863 * as listed in $wgBrowserBlackList.
1864 *
1865 * @param string $invalue
1866 * @return string
1867 * @private
1868 */
1869 function unmakesafe( $invalue ) {
1870 $result = "";
1871 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1872 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
1873 $i += 3;
1874 $hexstring = "";
1875 do {
1876 $hexstring .= $invalue{$i};
1877 $i++;
1878 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1879
1880 // Do some sanity checks. These aren't needed for reversability,
1881 // but should help keep the breakage down if the editor
1882 // breaks one of the entities whilst editing.
1883 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1884 $codepoint = hexdec($hexstring);
1885 $result .= codepointToUtf8( $codepoint );
1886 } else {
1887 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1888 }
1889 } else {
1890 $result .= substr( $invalue, $i, 1 );
1891 }
1892 }
1893 // reverse the transform that we made for reversability reasons.
1894 return strtr( $result, array( "&#x0" => "&#x" ) );
1895 }
1896
1897 function noCreatePermission() {
1898 global $wgOut;
1899 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
1900 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
1901 }
1902
1903 }
1904
1905 ?>