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