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