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