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