Code housekeeping stuff (and barring any stuff-ups on my behalf, there should be...
[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 $matches = array();
575 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
576 $this->spamPage ( $matches[0] );
577 wfProfileOut( "$fname-checks" );
578 wfProfileOut( $fname );
579 return false;
580 }
581 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
582 # Error messages or other handling should be performed by the filter function
583 wfProfileOut( $fname );
584 wfProfileOut( "$fname-checks" );
585 return false;
586 }
587 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError ) ) ) {
588 # Error messages etc. could be handled within the hook...
589 wfProfileOut( $fname );
590 wfProfileOut( "$fname-checks" );
591 return false;
592 } elseif( $this->hookError != '' ) {
593 # ...or the hook could be expecting us to produce an error
594 wfProfileOut( "$fname-checks " );
595 wfProfileOut( $fname );
596 return true;
597 }
598 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
599 # Check block state against master, thus 'false'.
600 $this->blockedPage();
601 wfProfileOut( "$fname-checks" );
602 wfProfileOut( $fname );
603 return false;
604 }
605 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
606 if ( $this->kblength > $wgMaxArticleSize ) {
607 // Error will be displayed by showEditForm()
608 $this->tooBig = true;
609 wfProfileOut( "$fname-checks" );
610 wfProfileOut( $fname );
611 return true;
612 }
613
614 if ( !$wgUser->isAllowed('edit') ) {
615 if ( $wgUser->isAnon() ) {
616 $this->userNotLoggedInPage();
617 wfProfileOut( "$fname-checks" );
618 wfProfileOut( $fname );
619 return false;
620 }
621 else {
622 $wgOut->readOnlyPage();
623 wfProfileOut( "$fname-checks" );
624 wfProfileOut( $fname );
625 return false;
626 }
627 }
628
629 if ( wfReadOnly() ) {
630 $wgOut->readOnlyPage();
631 wfProfileOut( "$fname-checks" );
632 wfProfileOut( $fname );
633 return false;
634 }
635 if ( $wgUser->pingLimiter() ) {
636 $wgOut->rateLimited();
637 wfProfileOut( "$fname-checks" );
638 wfProfileOut( $fname );
639 return false;
640 }
641
642 # If the article has been deleted while editing, don't save it without
643 # confirmation
644 if ( $this->deletedSinceEdit && !$this->recreate ) {
645 wfProfileOut( "$fname-checks" );
646 wfProfileOut( $fname );
647 return true;
648 }
649
650 wfProfileOut( "$fname-checks" );
651
652 # If article is new, insert it.
653 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
654 if ( 0 == $aid ) {
655 // Late check for create permission, just in case *PARANOIA*
656 if ( !$this->mTitle->userCanCreate() ) {
657 wfDebug( "$fname: no create permission\n" );
658 $this->noCreatePermission();
659 wfProfileOut( $fname );
660 return;
661 }
662
663 # Don't save a new article if it's blank.
664 if ( ( '' == $this->textbox1 ) ) {
665 $wgOut->redirect( $this->mTitle->getFullURL() );
666 wfProfileOut( $fname );
667 return false;
668 }
669
670 $isComment=($this->section=='new');
671 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
672 $this->minoredit, $this->watchthis, false, $isComment);
673
674 wfProfileOut( $fname );
675 return false;
676 }
677
678 # Article exists. Check for edit conflict.
679
680 $this->mArticle->clear(); # Force reload of dates, etc.
681 $this->mArticle->forUpdate( true ); # Lock the article
682
683 if( $this->mArticle->getTimestamp() != $this->edittime ) {
684 $this->isConflict = true;
685 if( $this->section == 'new' ) {
686 if( $this->mArticle->getUserText() == $wgUser->getName() &&
687 $this->mArticle->getComment() == $this->summary ) {
688 // Probably a duplicate submission of a new comment.
689 // This can happen when squid resends a request after
690 // a timeout but the first one actually went through.
691 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
692 } else {
693 // New comment; suppress conflict.
694 $this->isConflict = false;
695 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
696 }
697 }
698 }
699 $userid = $wgUser->getID();
700
701 if ( $this->isConflict) {
702 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
703 $this->mArticle->getTimestamp() . "'\n" );
704 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
705 }
706 else {
707 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
708 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
709 }
710 if( is_null( $text ) ) {
711 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
712 $this->isConflict = true;
713 $text = $this->textbox1;
714 }
715
716 # Suppress edit conflict with self, except for section edits where merging is required.
717 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
718 wfDebug( "Suppressing edit conflict, same user.\n" );
719 $this->isConflict = false;
720 } else {
721 # switch from section editing to normal editing in edit conflict
722 if($this->isConflict) {
723 # Attempt merge
724 if( $this->mergeChangesInto( $text ) ){
725 // Successful merge! Maybe we should tell the user the good news?
726 $this->isConflict = false;
727 wfDebug( "Suppressing edit conflict, successful merge.\n" );
728 } else {
729 $this->section = '';
730 $this->textbox1 = $text;
731 wfDebug( "Keeping edit conflict, failed merge.\n" );
732 }
733 }
734 }
735
736 if ( $this->isConflict ) {
737 wfProfileOut( $fname );
738 return true;
739 }
740
741 $oldtext = $this->mArticle->getContent();
742
743 # Handle the user preference to force summaries here, but not for null edits
744 if( $this->section != 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary')
745 && 0 != strcmp($oldtext, $text) && !Article::getRedirectAutosummary( $text )) {
746 if( md5( $this->summary ) == $this->autoSumm ) {
747 $this->missingSummary = true;
748 wfProfileOut( $fname );
749 return( true );
750 }
751 }
752
753 #And a similar thing for new sections
754 if( $this->section == 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary' ) ) {
755 if (trim($this->summary) == '') {
756 $this->missingSummary = true;
757 wfProfileOut( $fname );
758 return( true );
759 }
760 }
761
762 # All's well
763 wfProfileIn( "$fname-sectionanchor" );
764 $sectionanchor = '';
765 if( $this->section == 'new' ) {
766 if ( $this->textbox1 == '' ) {
767 $this->missingComment = true;
768 return true;
769 }
770 if( $this->summary != '' ) {
771 $sectionanchor = $this->sectionAnchor( $this->summary );
772 }
773 } elseif( $this->section != '' ) {
774 # Try to get a section anchor from the section source, redirect to edited section if header found
775 # XXX: might be better to integrate this into Article::replaceSection
776 # for duplicate heading checking and maybe parsing
777 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
778 # we can't deal with anchors, includes, html etc in the header for now,
779 # headline would need to be parsed to improve this
780 if($hasmatch and strlen($matches[2]) > 0) {
781 $sectionanchor = $this->sectionAnchor( $matches[2] );
782 }
783 }
784 wfProfileOut( "$fname-sectionanchor" );
785
786 // Save errors may fall down to the edit form, but we've now
787 // merged the section into full text. Clear the section field
788 // so that later submission of conflict forms won't try to
789 // replace that into a duplicated mess.
790 $this->textbox1 = $text;
791 $this->section = '';
792
793 // Check for length errors again now that the section is merged in
794 $this->kblength = (int)(strlen( $text ) / 1024);
795 if ( $this->kblength > $wgMaxArticleSize ) {
796 $this->tooBig = true;
797 wfProfileOut( $fname );
798 return true;
799 }
800
801 # update the article here
802 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
803 $this->watchthis, '', $sectionanchor ) ) {
804 wfProfileOut( $fname );
805 return false;
806 } else {
807 $this->isConflict = true;
808 }
809 wfProfileOut( $fname );
810 return true;
811 }
812
813 /**
814 * Initialise form fields in the object
815 * Called on the first invocation, e.g. when a user clicks an edit link
816 */
817 function initialiseForm() {
818 $this->edittime = $this->mArticle->getTimestamp();
819 $this->textbox1 = $this->getContent();
820 $this->summary = '';
821 if ( !$this->mArticle->exists() && $this->mArticle->mTitle->getNamespace() == NS_MEDIAWIKI )
822 $this->textbox1 = wfMsgWeirdKey( $this->mArticle->mTitle->getText() ) ;
823 wfProxyCheck();
824 }
825
826 /**
827 * Send the edit form and related headers to $wgOut
828 * @param $formCallback Optional callable that takes an OutputPage
829 * parameter; will be called during form output
830 * near the top, for captchas and the like.
831 */
832 function showEditForm( $formCallback=null ) {
833 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
834
835 $fname = 'EditPage::showEditForm';
836 wfProfileIn( $fname );
837
838 $sk =& $wgUser->getSkin();
839
840 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
841
842 $wgOut->setRobotpolicy( 'noindex,nofollow' );
843
844 # Enabled article-related sidebar, toplinks, etc.
845 $wgOut->setArticleRelated( true );
846
847 if ( $this->isConflict ) {
848 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
849 $wgOut->setPageTitle( $s );
850 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
851
852 $this->textbox2 = $this->textbox1;
853 $this->textbox1 = $this->getContent();
854 $this->edittime = $this->mArticle->getTimestamp();
855 } else {
856
857 if( $this->section != '' ) {
858 if( $this->section == 'new' ) {
859 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
860 } else {
861 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
862 $matches = array();
863 if( !$this->summary && !$this->preview && !$this->diff ) {
864 preg_match( "/^(=+)(.+)\\1/mi",
865 $this->textbox1,
866 $matches );
867 if( !empty( $matches[2] ) ) {
868 $this->summary = "/* ". trim($matches[2])." */ ";
869 }
870 }
871 }
872 } else {
873 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
874 }
875 $wgOut->setPageTitle( $s );
876
877 if ( $this->missingComment ) {
878 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
879 }
880
881 if( $this->missingSummary && $this->section != 'new' ) {
882 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
883 }
884
885 if( $this->missingSummary && $this->section == 'new' ) {
886 $wgOut->addWikiText( wfMsg( 'missingcommentheader' ) );
887 }
888
889 if( !$this->hookError == '' ) {
890 $wgOut->addWikiText( $this->hookError );
891 }
892
893 if ( !$this->checkUnicodeCompliantBrowser() ) {
894 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
895 }
896 if ( isset( $this->mArticle )
897 && isset( $this->mArticle->mRevision )
898 && !$this->mArticle->mRevision->isCurrent() ) {
899 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
900 $wgOut->addWikiText( wfMsg( 'editingold' ) );
901 }
902 }
903
904 if( wfReadOnly() ) {
905 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
906 } elseif( $wgUser->isAnon() && $this->formtype != 'preview' ) {
907 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
908 } else {
909 if( $this->isCssJsSubpage && $this->formtype != 'preview' ) {
910 # Check the skin exists
911 if( $this->isValidCssJsSubpage ) {
912 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
913 } else {
914 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
915 }
916 }
917 }
918
919 if( $this->mTitle->isProtected( 'edit' ) ) {
920 # Is the protection due to the namespace, e.g. interface text?
921 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
922 # Yes; remind the user
923 $notice = wfMsg( 'editinginterface' );
924 } elseif( $this->mTitle->isSemiProtected() ) {
925 # No; semi protected
926 $notice = wfMsg( 'semiprotectedpagewarning' );
927 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) || $notice == '-' ) {
928 $notice = '';
929 }
930 } else {
931 # No; regular protection
932 $notice = wfMsg( 'protectedpagewarning' );
933 }
934 $wgOut->addWikiText( $notice );
935 }
936
937 if ( $this->kblength === false ) {
938 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
939 }
940 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
941 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize ) );
942 } elseif( $this->kblength > 29 ) {
943 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ) );
944 }
945
946 #need to parse the preview early so that we know which templates are used,
947 #otherwise users with "show preview after edit box" will get a blank list
948 $previewOutput = $this->getPreviewText();
949
950 $rows = $wgUser->getIntOption( 'rows' );
951 $cols = $wgUser->getIntOption( 'cols' );
952
953 $ew = $wgUser->getOption( 'editwidth' );
954 if ( $ew ) $ew = " style=\"width:100%\"";
955 else $ew = '';
956
957 $q = 'action=submit';
958 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
959 $action = $this->mTitle->escapeLocalURL( $q );
960
961 $summary = wfMsg('summary');
962 $subject = wfMsg('subject');
963 $minor = wfMsgExt('minoredit', array('parseinline'));
964 $watchthis = wfMsgExt('watchthis', array('parseinline'));
965
966 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
967 wfMsgExt('cancel', array('parseinline')) );
968 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
969 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
970 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
971 htmlspecialchars( wfMsg( 'newwindow' ) );
972
973 global $wgRightsText;
974 $copywarn = "<div id=\"editpage-copywarn\">\n" .
975 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
976 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
977 $wgRightsText ) . "\n</div>";
978
979 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
980 # prepare toolbar for edit buttons
981 $toolbar = $this->getEditToolbar();
982 } else {
983 $toolbar = '';
984 }
985
986 // activate checkboxes if user wants them to be always active
987 if( !$this->preview && !$this->diff ) {
988 # Sort out the "watch" checkbox
989 if( $wgUser->getOption( 'watchdefault' ) ) {
990 # Watch all edits
991 $this->watchthis = true;
992 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
993 # Watch creations
994 $this->watchthis = true;
995 } elseif( $this->mTitle->userIsWatching() ) {
996 # Already watched
997 $this->watchthis = true;
998 }
999
1000 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
1001 }
1002
1003 $minoredithtml = '';
1004
1005 if ( $wgUser->isAllowed('minoredit') ) {
1006 $minoredithtml =
1007 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
1008 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />\n".
1009 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>\n";
1010 }
1011
1012 $watchhtml = '';
1013
1014 if ( $wgUser->isLoggedIn() ) {
1015 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
1016 ($this->watchthis?" checked='checked'":"").
1017 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />\n".
1018 "<label for='wpWatchthis' title=\"" .
1019 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>\n";
1020 }
1021
1022 $checkboxhtml = $minoredithtml . $watchhtml;
1023
1024 if ( $wgUser->getOption( 'previewontop' ) ) {
1025
1026 if ( 'preview' == $this->formtype ) {
1027 $this->showPreview( $previewOutput );
1028 } else {
1029 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1030 }
1031
1032 if ( 'diff' == $this->formtype ) {
1033 $wgOut->addHTML( $this->getDiff() );
1034 }
1035 }
1036
1037
1038 $wgOut->addHTML( $this->editFormTextTop );
1039
1040 # if this is a comment, show a subject line at the top, which is also the edit summary.
1041 # Otherwise, show a summary field at the bottom
1042 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
1043 if( $this->section == 'new' ) {
1044 $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 />";
1045 $editsummary = '';
1046 $subjectpreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1047 $summarypreview = '';
1048 } else {
1049 $commentsubject = '';
1050 $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 />";
1051 $summarypreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1052 $subjectpreview = '';
1053 }
1054
1055 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1056 if( !$this->preview && !$this->diff ) {
1057 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1058 }
1059 $templates = ($this->preview || $this->section) ? $this->mPreviewTemplates : $this->mArticle->getUsedTemplates();
1060 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != '');
1061
1062 global $wgUseMetadataEdit ;
1063 if ( $wgUseMetadataEdit ) {
1064 $metadata = $this->mMetaData ;
1065 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1066 $top = wfMsgWikiHtml( 'metadata_help' );
1067 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1068 }
1069 else $metadata = "" ;
1070
1071 $hidden = '';
1072 $recreate = '';
1073 if ($this->deletedSinceEdit) {
1074 if ( 'save' != $this->formtype ) {
1075 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1076 } else {
1077 // Hide the toolbar and edit area, use can click preview to get it back
1078 // Add an confirmation checkbox and explanation.
1079 $toolbar = '';
1080 $hidden = 'type="hidden" style="display:none;"';
1081 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
1082 $recreate .=
1083 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1084 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1085 }
1086 }
1087
1088 $temp = array(
1089 'id' => 'wpSave',
1090 'name' => 'wpSave',
1091 'type' => 'submit',
1092 'tabindex' => '5',
1093 'value' => wfMsg('savearticle'),
1094 'accesskey' => wfMsg('accesskey-save'),
1095 'title' => wfMsg('tooltip-save'),
1096 );
1097 $buttons['save'] = wfElement('input', $temp, '');
1098 $temp = array(
1099 'id' => 'wpDiff',
1100 'name' => 'wpDiff',
1101 'type' => 'submit',
1102 'tabindex' => '7',
1103 'value' => wfMsg('showdiff'),
1104 'accesskey' => wfMsg('accesskey-diff'),
1105 'title' => wfMsg('tooltip-diff'),
1106 );
1107 $buttons['diff'] = wfElement('input', $temp, '');
1108
1109 global $wgLivePreview;
1110 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1111 $temp = array(
1112 'id' => 'wpPreview',
1113 'name' => 'wpPreview',
1114 'type' => 'submit',
1115 'tabindex' => '6',
1116 'value' => wfMsg('showpreview'),
1117 'accesskey' => '',
1118 'title' => wfMsg('tooltip-preview'),
1119 'style' => 'display: none;',
1120 );
1121 $buttons['preview'] = wfElement('input', $temp, '');
1122 $temp = array(
1123 'id' => 'wpLivePreview',
1124 'name' => 'wpLivePreview',
1125 'type' => 'submit',
1126 'tabindex' => '6',
1127 'value' => wfMsg('showlivepreview'),
1128 'accesskey' => wfMsg('accesskey-preview'),
1129 'title' => '',
1130 'onclick' => $this->doLivePreviewScript(),
1131 );
1132 $buttons['live'] = wfElement('input', $temp, '');
1133 } else {
1134 $temp = array(
1135 'id' => 'wpPreview',
1136 'name' => 'wpPreview',
1137 'type' => 'submit',
1138 'tabindex' => '6',
1139 'value' => wfMsg('showpreview'),
1140 'accesskey' => wfMsg('accesskey-preview'),
1141 'title' => wfMsg('tooltip-preview'),
1142 );
1143 $buttons['preview'] = wfElement('input', $temp, '');
1144 $buttons['live'] = '';
1145 }
1146
1147 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1148 ? ""
1149 : "<input type='hidden' name=\"safemode\" value='1' />\n";
1150
1151 $wgOut->addHTML( <<<END
1152 {$toolbar}
1153 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1154 END
1155 );
1156
1157 if( is_callable( $formCallback ) ) {
1158 call_user_func_array( $formCallback, array( &$wgOut ) );
1159 }
1160
1161 // Put these up at the top to ensure they aren't lost on early form submission
1162 $wgOut->addHTML( "
1163 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1164 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1165 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1166 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1167
1168 $wgOut->addHTML( <<<END
1169 $recreate
1170 {$commentsubject}
1171 {$subjectpreview}
1172 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1173 cols='{$cols}'{$ew} $hidden>
1174 END
1175 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
1176 "
1177 </textarea>
1178 " );
1179
1180 $wgOut->addWikiText( $copywarn );
1181 $wgOut->addHTML( $this->editFormTextAfterWarn );
1182 $wgOut->addHTML( "
1183 {$metadata}
1184 {$editsummary}
1185 {$summarypreview}
1186 {$checkboxhtml}
1187 {$safemodehtml}
1188 ");
1189
1190 $wgOut->addHTML(
1191 "<div class='editButtons'>
1192 {$buttons['save']}
1193 {$buttons['preview']}
1194 {$buttons['live']}
1195 {$buttons['diff']}
1196 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1197 </div><!-- editButtons -->
1198 </div><!-- editOptions -->");
1199
1200 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1201 $wgOut->addHTML( $this->editFormTextAfterTools );
1202
1203 $wgOut->addHTML( "
1204 <div class='templatesUsed'>
1205 {$formattedtemplates}
1206 </div>
1207 " );
1208
1209 if ( $wgUser->isLoggedIn() ) {
1210 /**
1211 * To make it harder for someone to slip a user a page
1212 * which submits an edit form to the wiki without their
1213 * knowledge, a random token is associated with the login
1214 * session. If it's not passed back with the submission,
1215 * we won't save the page, or render user JavaScript and
1216 * CSS previews.
1217 */
1218 $token = htmlspecialchars( $wgUser->editToken() );
1219 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1220 }
1221
1222 # If a blank edit summary was previously provided, and the appropriate
1223 # user preference is active, pass a hidden tag here. This will stop the
1224 # user being bounced back more than once in the event that a summary
1225 # is not required.
1226 if( $this->missingSummary ) {
1227 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1228 }
1229
1230 # For a bit more sophisticated detection of blank summaries, hash the
1231 # automatic one and pass that in a hidden field.
1232 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1233 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1234
1235 if ( $this->isConflict ) {
1236 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1237
1238 $de = new DifferenceEngine( $this->mTitle );
1239 $de->setText( $this->textbox2, $this->textbox1 );
1240 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1241
1242 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1243 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1244 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1245 }
1246 $wgOut->addHTML( $this->editFormTextBottom );
1247 $wgOut->addHTML( "</form>\n" );
1248 if ( !$wgUser->getOption( 'previewontop' ) ) {
1249
1250 if ( $this->formtype == 'preview') {
1251 $this->showPreview( $previewOutput );
1252 } else {
1253 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1254 }
1255
1256 if ( $this->formtype == 'diff') {
1257 $wgOut->addHTML( $this->getDiff() );
1258 }
1259
1260 }
1261
1262 wfProfileOut( $fname );
1263 }
1264
1265 /**
1266 * Append preview output to $wgOut.
1267 * Includes category rendering if this is a category page.
1268 *
1269 * @param string $text The HTML to be output for the preview.
1270 */
1271 private function showPreview( $text ) {
1272 global $wgOut;
1273
1274 $wgOut->addHTML( '<div id="wikiPreview">' );
1275 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1276 $this->mArticle->openShowCategory();
1277 }
1278 $wgOut->addHTML( $text );
1279 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1280 $this->mArticle->closeShowCategory();
1281 }
1282 $wgOut->addHTML( '</div>' );
1283 }
1284
1285 /**
1286 * Live Preview lets us fetch rendered preview page content and
1287 * add it to the page without refreshing the whole page.
1288 * If not supported by the browser it will fall through to the normal form
1289 * submission method.
1290 *
1291 * This function outputs a script tag to support live preview, and
1292 * returns an onclick handler which should be added to the attributes
1293 * of the preview button
1294 */
1295 function doLivePreviewScript() {
1296 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1297 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1298 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1299 '"></script>' . "\n" );
1300 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1301 return "return !livePreview(" .
1302 "getElementById('wikiPreview')," .
1303 "editform.wpTextbox1.value," .
1304 '"' . $liveAction . '"' . ")";
1305 }
1306
1307 function getLastDelete() {
1308 $dbr =& wfGetDB( DB_SLAVE );
1309 $fname = 'EditPage::getLastDelete';
1310 $res = $dbr->select(
1311 array( 'logging', 'user' ),
1312 array( 'log_type',
1313 'log_action',
1314 'log_timestamp',
1315 'log_user',
1316 'log_namespace',
1317 'log_title',
1318 'log_comment',
1319 'log_params',
1320 'user_name', ),
1321 array( 'log_namespace' => $this->mTitle->getNamespace(),
1322 'log_title' => $this->mTitle->getDBkey(),
1323 'log_type' => 'delete',
1324 'log_action' => 'delete',
1325 'user_id=log_user' ),
1326 $fname,
1327 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1328
1329 if($dbr->numRows($res) == 1) {
1330 while ( $x = $dbr->fetchObject ( $res ) )
1331 $data = $x;
1332 $dbr->freeResult ( $res ) ;
1333 } else {
1334 $data = null;
1335 }
1336 return $data;
1337 }
1338
1339 /**
1340 * @todo document
1341 */
1342 function getPreviewText() {
1343 global $wgOut, $wgUser, $wgTitle, $wgParser;
1344
1345 $fname = 'EditPage::getPreviewText';
1346 wfProfileIn( $fname );
1347
1348 if ( $this->mTriedSave && !$this->mTokenOk ) {
1349 $msg = 'session_fail_preview';
1350 } else {
1351 $msg = 'previewnote';
1352 }
1353 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1354 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1355 if ( $this->isConflict ) {
1356 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1357 }
1358
1359 $parserOptions = ParserOptions::newFromUser( $wgUser );
1360 $parserOptions->setEditSection( false );
1361
1362 global $wgRawHtml;
1363 if( $wgRawHtml && !$this->mTokenOk ) {
1364 // Could be an offsite preview attempt. This is very unsafe if
1365 // HTML is enabled, as it could be an attack.
1366 return $wgOut->parse( "<div class='previewnote'>" .
1367 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1368 }
1369
1370 # don't parse user css/js, show message about preview
1371 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1372
1373 if ( $this->isCssJsSubpage ) {
1374 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1375 $previewtext = wfMsg('usercsspreview');
1376 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1377 $previewtext = wfMsg('userjspreview');
1378 }
1379 $parserOptions->setTidy(true);
1380 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1381 $wgOut->addHTML( $parserOutput->mText );
1382 wfProfileOut( $fname );
1383 return $previewhead;
1384 } else {
1385 $toparse = $this->textbox1;
1386
1387 # If we're adding a comment, we need to show the
1388 # summary as the headline
1389 if($this->section=="new" && $this->summary!="") {
1390 $toparse="== {$this->summary} ==\n\n".$toparse;
1391 }
1392
1393 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1394 $parserOptions->setTidy(true);
1395 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1396 $wgTitle, $parserOptions );
1397
1398 $previewHTML = $parserOutput->getText();
1399 $wgOut->addParserOutputNoText( $parserOutput );
1400
1401 foreach ( $parserOutput->getTemplates() as $ns => $template)
1402 foreach ( array_keys( $template ) as $dbk)
1403 $this->mPreviewTemplates[] = Title::makeTitle($ns, $dbk);
1404
1405 wfProfileOut( $fname );
1406 return $previewhead . $previewHTML;
1407 }
1408 }
1409
1410 /**
1411 * Call the stock "user is blocked" page
1412 */
1413 function blockedPage() {
1414 global $wgOut, $wgUser;
1415 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1416
1417 # If the user made changes, preserve them when showing the markup
1418 # (This happens when a user is blocked during edit, for instance)
1419 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
1420 if( $first ) {
1421 $source = $this->mTitle->exists() ? $this->getContent() : false;
1422 } else {
1423 $source = $this->textbox1;
1424 }
1425
1426 # Spit out the source or the user's modified version
1427 if( $source !== false ) {
1428 $rows = $wgUser->getOption( 'rows' );
1429 $cols = $wgUser->getOption( 'cols' );
1430 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1431 $wgOut->addHtml( '<hr />' );
1432 $wgOut->addWikiText( wfMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() ) );
1433 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1434 }
1435 }
1436
1437 /**
1438 * Produce the stock "please login to edit pages" page
1439 */
1440 function userNotLoggedInPage() {
1441 global $wgUser, $wgOut;
1442 $skin = $wgUser->getSkin();
1443
1444 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1445 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle->getPrefixedUrl() );
1446
1447 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1448 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1449 $wgOut->setArticleRelated( false );
1450
1451 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1452 $wgOut->returnToMain( false, $this->mTitle->getPrefixedUrl() );
1453 }
1454
1455 /**
1456 * Creates a basic error page which informs the user that
1457 * they have to validate their email address before being
1458 * allowed to edit.
1459 */
1460 function userNotConfirmedPage() {
1461 global $wgOut;
1462
1463 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1464 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1465 $wgOut->setArticleRelated( false );
1466
1467 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1468 $wgOut->returnToMain( false );
1469 }
1470
1471 /**
1472 * Produce the stock "your edit contains spam" page
1473 *
1474 * @param $match Text which triggered one or more filters
1475 */
1476 function spamPage( $match = false ) {
1477 global $wgOut;
1478
1479 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1480 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1481 $wgOut->setArticleRelated( false );
1482
1483 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1484 if ( $match )
1485 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1486
1487 $wgOut->returnToMain( false );
1488 }
1489
1490 /**
1491 * @private
1492 * @todo document
1493 */
1494 function mergeChangesInto( &$editText ){
1495 $fname = 'EditPage::mergeChangesInto';
1496 wfProfileIn( $fname );
1497
1498 $db =& wfGetDB( DB_MASTER );
1499
1500 // This is the revision the editor started from
1501 $baseRevision = Revision::loadFromTimestamp(
1502 $db, $this->mArticle->mTitle, $this->edittime );
1503 if( is_null( $baseRevision ) ) {
1504 wfProfileOut( $fname );
1505 return false;
1506 }
1507 $baseText = $baseRevision->getText();
1508
1509 // The current state, we want to merge updates into it
1510 $currentRevision = Revision::loadFromTitle(
1511 $db, $this->mArticle->mTitle );
1512 if( is_null( $currentRevision ) ) {
1513 wfProfileOut( $fname );
1514 return false;
1515 }
1516 $currentText = $currentRevision->getText();
1517
1518 $result = '';
1519 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1520 $editText = $result;
1521 wfProfileOut( $fname );
1522 return true;
1523 } else {
1524 wfProfileOut( $fname );
1525 return false;
1526 }
1527 }
1528
1529 /**
1530 * Check if the browser is on a blacklist of user-agents known to
1531 * mangle UTF-8 data on form submission. Returns true if Unicode
1532 * should make it through, false if it's known to be a problem.
1533 * @return bool
1534 * @private
1535 */
1536 function checkUnicodeCompliantBrowser() {
1537 global $wgBrowserBlackList;
1538 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1539 // No User-Agent header sent? Trust it by default...
1540 return true;
1541 }
1542 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1543 foreach ( $wgBrowserBlackList as $browser ) {
1544 if ( preg_match($browser, $currentbrowser) ) {
1545 return false;
1546 }
1547 }
1548 return true;
1549 }
1550
1551 /**
1552 * Format an anchor fragment as it would appear for a given section name
1553 * @param string $text
1554 * @return string
1555 * @private
1556 */
1557 function sectionAnchor( $text ) {
1558 $headline = Sanitizer::decodeCharReferences( $text );
1559 # strip out HTML
1560 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1561 $headline = trim( $headline );
1562 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1563 $replacearray = array(
1564 '%3A' => ':',
1565 '%' => '.'
1566 );
1567 return str_replace(
1568 array_keys( $replacearray ),
1569 array_values( $replacearray ),
1570 $sectionanchor );
1571 }
1572
1573 /**
1574 * Shows a bulletin board style toolbar for common editing functions.
1575 * It can be disabled in the user preferences.
1576 * The necessary JavaScript code can be found in style/wikibits.js.
1577 */
1578 function getEditToolbar() {
1579 global $wgStylePath, $wgContLang, $wgJsMimeType;
1580
1581 /**
1582 * toolarray an array of arrays which each include the filename of
1583 * the button image (without path), the opening tag, the closing tag,
1584 * and optionally a sample text that is inserted between the two when no
1585 * selection is highlighted.
1586 * The tip text is shown when the user moves the mouse over the button.
1587 *
1588 * Already here are accesskeys (key), which are not used yet until someone
1589 * can figure out a way to make them work in IE. However, we should make
1590 * sure these keys are not defined on the edit page.
1591 */
1592 $toolarray=array(
1593 array( 'image'=>'button_bold.png',
1594 'open' => "\'\'\'",
1595 'close' => "\'\'\'",
1596 'sample'=> wfMsg('bold_sample'),
1597 'tip' => wfMsg('bold_tip'),
1598 'key' => 'B'
1599 ),
1600 array( 'image'=>'button_italic.png',
1601 'open' => "\'\'",
1602 'close' => "\'\'",
1603 'sample'=> wfMsg('italic_sample'),
1604 'tip' => wfMsg('italic_tip'),
1605 'key' => 'I'
1606 ),
1607 array( 'image'=>'button_link.png',
1608 'open' => '[[',
1609 'close' => ']]',
1610 'sample'=> wfMsg('link_sample'),
1611 'tip' => wfMsg('link_tip'),
1612 'key' => 'L'
1613 ),
1614 array( 'image'=>'button_extlink.png',
1615 'open' => '[',
1616 'close' => ']',
1617 'sample'=> wfMsg('extlink_sample'),
1618 'tip' => wfMsg('extlink_tip'),
1619 'key' => 'X'
1620 ),
1621 array( 'image'=>'button_headline.png',
1622 'open' => "\\n== ",
1623 'close' => " ==\\n",
1624 'sample'=> wfMsg('headline_sample'),
1625 'tip' => wfMsg('headline_tip'),
1626 'key' => 'H'
1627 ),
1628 array( 'image'=>'button_image.png',
1629 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).":",
1630 'close' => ']]',
1631 'sample'=> wfMsg('image_sample'),
1632 'tip' => wfMsg('image_tip'),
1633 'key' => 'D'
1634 ),
1635 array( 'image' =>'button_media.png',
1636 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1637 'close' => ']]',
1638 'sample'=> wfMsg('media_sample'),
1639 'tip' => wfMsg('media_tip'),
1640 'key' => 'M'
1641 ),
1642 array( 'image' =>'button_math.png',
1643 'open' => "<math>",
1644 'close' => "<\\/math>",
1645 'sample'=> wfMsg('math_sample'),
1646 'tip' => wfMsg('math_tip'),
1647 'key' => 'C'
1648 ),
1649 array( 'image' =>'button_nowiki.png',
1650 'open' => "<nowiki>",
1651 'close' => "<\\/nowiki>",
1652 'sample'=> wfMsg('nowiki_sample'),
1653 'tip' => wfMsg('nowiki_tip'),
1654 'key' => 'N'
1655 ),
1656 array( 'image' =>'button_sig.png',
1657 'open' => '--~~~~',
1658 'close' => '',
1659 'sample'=> '',
1660 'tip' => wfMsg('sig_tip'),
1661 'key' => 'Y'
1662 ),
1663 array( 'image' =>'button_hr.png',
1664 'open' => "\\n----\\n",
1665 'close' => '',
1666 'sample'=> '',
1667 'tip' => wfMsg('hr_tip'),
1668 'key' => 'R'
1669 )
1670 );
1671 $toolbar = "<div id='toolbar'>\n";
1672 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1673
1674 foreach($toolarray as $tool) {
1675
1676 $image=$wgStylePath.'/common/images/'.$tool['image'];
1677 $open=$tool['open'];
1678 $close=$tool['close'];
1679 $sample = wfEscapeJsString( $tool['sample'] );
1680
1681 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1682 // Older browsers show a "speedtip" type message only for ALT.
1683 // Ideally these should be different, realistically they
1684 // probably don't need to be.
1685 $tip = wfEscapeJsString( $tool['tip'] );
1686
1687 #$key = $tool["key"];
1688
1689 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1690 }
1691
1692 $toolbar.="/*]]>*/\n</script>";
1693 $toolbar.="\n</div>";
1694 return $toolbar;
1695 }
1696
1697 /**
1698 * Output preview text only. This can be sucked into the edit page
1699 * via JavaScript, and saves the server time rendering the skin as
1700 * well as theoretically being more robust on the client (doesn't
1701 * disturb the edit box's undo history, won't eat your text on
1702 * failure, etc).
1703 *
1704 * @todo This doesn't include category or interlanguage links.
1705 * Would need to enhance it a bit, maybe wrap them in XML
1706 * or something... that might also require more skin
1707 * initialization, so check whether that's a problem.
1708 */
1709 function livePreview() {
1710 global $wgOut;
1711 $wgOut->disable();
1712 header( 'Content-type: text/xml' );
1713 header( 'Cache-control: no-cache' );
1714 # FIXME
1715 echo $this->getPreviewText( );
1716 /* To not shake screen up and down between preview and live-preview */
1717 echo "<br style=\"clear:both;\" />\n";
1718 }
1719
1720
1721 /**
1722 * Get a diff between the current contents of the edit box and the
1723 * version of the page we're editing from.
1724 *
1725 * If this is a section edit, we'll replace the section as for final
1726 * save and then make a comparison.
1727 *
1728 * @return string HTML
1729 */
1730 function getDiff() {
1731 $oldtext = $this->mArticle->fetchContent();
1732 $newtext = $this->mArticle->replaceSection(
1733 $this->section, $this->textbox1, $this->summary, $this->edittime );
1734 $newtext = $this->mArticle->preSaveTransform( $newtext );
1735 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1736 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1737 if ( $oldtext !== false || $newtext != '' ) {
1738 $de = new DifferenceEngine( $this->mTitle );
1739 $de->setText( $oldtext, $newtext );
1740 $difftext = $de->getDiff( $oldtitle, $newtitle );
1741 } else {
1742 $difftext = '';
1743 }
1744
1745 return '<div id="wikiDiff">' . $difftext . '</div>';
1746 }
1747
1748 /**
1749 * Filter an input field through a Unicode de-armoring process if it
1750 * came from an old browser with known broken Unicode editing issues.
1751 *
1752 * @param WebRequest $request
1753 * @param string $field
1754 * @return string
1755 * @private
1756 */
1757 function safeUnicodeInput( $request, $field ) {
1758 $text = rtrim( $request->getText( $field ) );
1759 return $request->getBool( 'safemode' )
1760 ? $this->unmakesafe( $text )
1761 : $text;
1762 }
1763
1764 /**
1765 * Filter an output field through a Unicode armoring process if it is
1766 * going to an old browser with known broken Unicode editing issues.
1767 *
1768 * @param string $text
1769 * @return string
1770 * @private
1771 */
1772 function safeUnicodeOutput( $text ) {
1773 global $wgContLang;
1774 $codedText = $wgContLang->recodeForEdit( $text );
1775 return $this->checkUnicodeCompliantBrowser()
1776 ? $codedText
1777 : $this->makesafe( $codedText );
1778 }
1779
1780 /**
1781 * A number of web browsers are known to corrupt non-ASCII characters
1782 * in a UTF-8 text editing environment. To protect against this,
1783 * detected browsers will be served an armored version of the text,
1784 * with non-ASCII chars converted to numeric HTML character references.
1785 *
1786 * Preexisting such character references will have a 0 added to them
1787 * to ensure that round-trips do not alter the original data.
1788 *
1789 * @param string $invalue
1790 * @return string
1791 * @private
1792 */
1793 function makesafe( $invalue ) {
1794 // Armor existing references for reversability.
1795 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1796
1797 $bytesleft = 0;
1798 $result = "";
1799 $working = 0;
1800 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1801 $bytevalue = ord( $invalue{$i} );
1802 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1803 $result .= chr( $bytevalue );
1804 $bytesleft = 0;
1805 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1806 $working = $working << 6;
1807 $working += ($bytevalue & 0x3F);
1808 $bytesleft--;
1809 if( $bytesleft <= 0 ) {
1810 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1811 }
1812 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1813 $working = $bytevalue & 0x1F;
1814 $bytesleft = 1;
1815 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1816 $working = $bytevalue & 0x0F;
1817 $bytesleft = 2;
1818 } else { //1111 0xxx
1819 $working = $bytevalue & 0x07;
1820 $bytesleft = 3;
1821 }
1822 }
1823 return $result;
1824 }
1825
1826 /**
1827 * Reverse the previously applied transliteration of non-ASCII characters
1828 * back to UTF-8. Used to protect data from corruption by broken web browsers
1829 * as listed in $wgBrowserBlackList.
1830 *
1831 * @param string $invalue
1832 * @return string
1833 * @private
1834 */
1835 function unmakesafe( $invalue ) {
1836 $result = "";
1837 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1838 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
1839 $i += 3;
1840 $hexstring = "";
1841 do {
1842 $hexstring .= $invalue{$i};
1843 $i++;
1844 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1845
1846 // Do some sanity checks. These aren't needed for reversability,
1847 // but should help keep the breakage down if the editor
1848 // breaks one of the entities whilst editing.
1849 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1850 $codepoint = hexdec($hexstring);
1851 $result .= codepointToUtf8( $codepoint );
1852 } else {
1853 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1854 }
1855 } else {
1856 $result .= substr( $invalue, $i, 1 );
1857 }
1858 }
1859 // reverse the transform that we made for reversability reasons.
1860 return strtr( $result, array( "&#x0" => "&#x" ) );
1861 }
1862
1863 function noCreatePermission() {
1864 global $wgOut;
1865 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
1866 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
1867 }
1868
1869 }
1870
1871 ?>