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