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