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