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