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