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