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