Documentation tweaks to help documentation systems (Doxygen + PHPDocumentor)
[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 # It's either cascading protection or regular protection; work out which
999 list($cascadeSources, $restrictions) = $this->mTitle->getCascadeProtectionSources();
1000 if ( !$cascadeSources || count( $cascadeSources ) == 0 ) {
1001 # Regular protection
1002 $notice = wfMsg( 'protectedpagewarning' );
1003 } else {
1004 # Cascading protection; explain, and list the titles responsible
1005 $notice = wfMsg( 'cascadeprotectedwarning' ) . "\n";
1006 foreach( $cascadeSources as $source )
1007 $notice .= '* [[:' . $source->getPrefixedText() . "]]\n";
1008 }
1009 }
1010 $wgOut->addWikiText( $notice );
1011 }
1012
1013 if ( $this->kblength === false ) {
1014 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
1015 }
1016 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
1017 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize ) );
1018 } elseif( $this->kblength > 29 ) {
1019 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ) );
1020 }
1021
1022 #need to parse the preview early so that we know which templates are used,
1023 #otherwise users with "show preview after edit box" will get a blank list
1024 if ( $this->formtype == 'preview' ) {
1025 $previewOutput = $this->getPreviewText();
1026 }
1027
1028 $rows = $wgUser->getIntOption( 'rows' );
1029 $cols = $wgUser->getIntOption( 'cols' );
1030
1031 $ew = $wgUser->getOption( 'editwidth' );
1032 if ( $ew ) $ew = " style=\"width:100%\"";
1033 else $ew = '';
1034
1035 $q = 'action=submit';
1036 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1037 $action = $this->mTitle->escapeLocalURL( $q );
1038
1039 $summary = wfMsg('summary');
1040 $subject = wfMsg('subject');
1041
1042 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
1043 wfMsgExt('cancel', array('parseinline')) );
1044 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1045 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1046 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1047 htmlspecialchars( wfMsg( 'newwindow' ) );
1048
1049 global $wgRightsText;
1050 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1051 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
1052 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1053 $wgRightsText ) . "\n</div>";
1054
1055 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
1056 # prepare toolbar for edit buttons
1057 $toolbar = $this->getEditToolbar();
1058 } else {
1059 $toolbar = '';
1060 }
1061
1062 // activate checkboxes if user wants them to be always active
1063 if( !$this->preview && !$this->diff ) {
1064 # Sort out the "watch" checkbox
1065 if( $wgUser->getOption( 'watchdefault' ) ) {
1066 # Watch all edits
1067 $this->watchthis = true;
1068 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1069 # Watch creations
1070 $this->watchthis = true;
1071 } elseif( $this->mTitle->userIsWatching() ) {
1072 # Already watched
1073 $this->watchthis = true;
1074 }
1075
1076 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
1077 }
1078
1079 $wgOut->addHTML( $this->editFormPageTop );
1080
1081 if ( $wgUser->getOption( 'previewontop' ) ) {
1082
1083 if ( 'preview' == $this->formtype ) {
1084 $this->showPreview( $previewOutput );
1085 } else {
1086 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1087 }
1088
1089 if ( 'diff' == $this->formtype ) {
1090 $wgOut->addHTML( $this->getDiff() );
1091 }
1092 }
1093
1094
1095 $wgOut->addHTML( $this->editFormTextTop );
1096
1097 # if this is a comment, show a subject line at the top, which is also the edit summary.
1098 # Otherwise, show a summary field at the bottom
1099 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
1100 if( $this->section == 'new' ) {
1101 $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 />";
1102 $editsummary = '';
1103 $subjectpreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1104 $summarypreview = '';
1105 } else {
1106 $commentsubject = '';
1107 $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 />";
1108 $summarypreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1109 $subjectpreview = '';
1110 }
1111
1112 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1113 if( !$this->preview && !$this->diff ) {
1114 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1115 }
1116 $templates = ($this->preview || $this->section) ? $this->mPreviewTemplates : $this->mArticle->getUsedTemplates();
1117 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != '');
1118
1119 global $wgUseMetadataEdit ;
1120 if ( $wgUseMetadataEdit ) {
1121 $metadata = $this->mMetaData ;
1122 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1123 $top = wfMsgWikiHtml( 'metadata_help' );
1124 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1125 }
1126 else $metadata = "" ;
1127
1128 $hidden = '';
1129 $recreate = '';
1130 if ($this->deletedSinceEdit) {
1131 if ( 'save' != $this->formtype ) {
1132 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1133 } else {
1134 // Hide the toolbar and edit area, use can click preview to get it back
1135 // Add an confirmation checkbox and explanation.
1136 $toolbar = '';
1137 $hidden = 'type="hidden" style="display:none;"';
1138 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
1139 $recreate .=
1140 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1141 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1142 }
1143 }
1144
1145 $tabindex = 2;
1146
1147 $checkboxes = self::getCheckboxes( $tabindex, $sk,
1148 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
1149
1150 $checkboxhtml = implode( $checkboxes, "\n" );
1151
1152 $buttons = $this->getEditButtons( $tabindex );
1153 $buttonshtml = implode( $buttons, "\n" );
1154
1155 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1156 ? '' : Xml::hidden( 'safemode', '1' );
1157
1158 $wgOut->addHTML( <<<END
1159 {$toolbar}
1160 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1161 END
1162 );
1163
1164 if( is_callable( $formCallback ) ) {
1165 call_user_func_array( $formCallback, array( &$wgOut ) );
1166 }
1167
1168 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1169
1170 // Put these up at the top to ensure they aren't lost on early form submission
1171 $wgOut->addHTML( "
1172 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1173 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1174 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1175 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1176
1177 $wgOut->addHTML( <<<END
1178 $recreate
1179 {$commentsubject}
1180 {$subjectpreview}
1181 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1182 cols='{$cols}'{$ew} $hidden>
1183 END
1184 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
1185 "
1186 </textarea>
1187 " );
1188
1189 $wgOut->addWikiText( $copywarn );
1190 $wgOut->addHTML( $this->editFormTextAfterWarn );
1191 $wgOut->addHTML( "
1192 {$metadata}
1193 {$editsummary}
1194 {$summarypreview}
1195 {$checkboxhtml}
1196 {$safemodehtml}
1197 ");
1198
1199 $wgOut->addHTML(
1200 "<div class='editButtons'>
1201 {$buttonshtml}
1202 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1203 </div><!-- editButtons -->
1204 </div><!-- editOptions -->");
1205
1206 $wgOut->addHtml( '<div class="mw-editTools">' );
1207 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1208 $wgOut->addHtml( '</div>' );
1209
1210 $wgOut->addHTML( $this->editFormTextAfterTools );
1211
1212 $wgOut->addHTML( "
1213 <div class='templatesUsed'>
1214 {$formattedtemplates}
1215 </div>
1216 " );
1217
1218 /**
1219 * To make it harder for someone to slip a user a page
1220 * which submits an edit form to the wiki without their
1221 * knowledge, a random token is associated with the login
1222 * session. If it's not passed back with the submission,
1223 * we won't save the page, or render user JavaScript and
1224 * CSS previews.
1225 *
1226 * For anon editors, who may not have a session, we just
1227 * include the constant suffix to prevent editing from
1228 * broken text-mangling proxies.
1229 */
1230 if ( $wgUser->isLoggedIn() )
1231 $token = htmlspecialchars( $wgUser->editToken() );
1232 else
1233 $token = EDIT_TOKEN_SUFFIX;
1234 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1235
1236
1237 # If a blank edit summary was previously provided, and the appropriate
1238 # user preference is active, pass a hidden tag here. This will stop the
1239 # user being bounced back more than once in the event that a summary
1240 # is not required.
1241 if( $this->missingSummary ) {
1242 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1243 }
1244
1245 # For a bit more sophisticated detection of blank summaries, hash the
1246 # automatic one and pass that in a hidden field.
1247 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1248 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1249
1250 if ( $this->isConflict ) {
1251 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1252
1253 $de = new DifferenceEngine( $this->mTitle );
1254 $de->setText( $this->textbox2, $this->textbox1 );
1255 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1256
1257 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1258 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1259 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1260 }
1261 $wgOut->addHTML( $this->editFormTextBottom );
1262 $wgOut->addHTML( "</form>\n" );
1263 if ( !$wgUser->getOption( 'previewontop' ) ) {
1264
1265 if ( $this->formtype == 'preview') {
1266 $this->showPreview( $previewOutput );
1267 } else {
1268 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1269 }
1270
1271 if ( $this->formtype == 'diff') {
1272 $wgOut->addHTML( $this->getDiff() );
1273 }
1274
1275 }
1276
1277 wfProfileOut( $fname );
1278 }
1279
1280 /**
1281 * Append preview output to $wgOut.
1282 * Includes category rendering if this is a category page.
1283 *
1284 * @param string $text The HTML to be output for the preview.
1285 */
1286 private function showPreview( $text ) {
1287 global $wgOut;
1288
1289 $wgOut->addHTML( '<div id="wikiPreview">' );
1290 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1291 $this->mArticle->openShowCategory();
1292 }
1293 $wgOut->addHTML( $text );
1294 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1295 $this->mArticle->closeShowCategory();
1296 }
1297 $wgOut->addHTML( '</div>' );
1298 }
1299
1300 /**
1301 * Live Preview lets us fetch rendered preview page content and
1302 * add it to the page without refreshing the whole page.
1303 * If not supported by the browser it will fall through to the normal form
1304 * submission method.
1305 *
1306 * This function outputs a script tag to support live preview, and
1307 * returns an onclick handler which should be added to the attributes
1308 * of the preview button
1309 */
1310 function doLivePreviewScript() {
1311 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1312 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1313 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1314 '"></script>' . "\n" );
1315 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1316 return "return !livePreview(" .
1317 "getElementById('wikiPreview')," .
1318 "editform.wpTextbox1.value," .
1319 '"' . $liveAction . '"' . ")";
1320 }
1321
1322 function getLastDelete() {
1323 $dbr = wfGetDB( DB_SLAVE );
1324 $fname = 'EditPage::getLastDelete';
1325 $res = $dbr->select(
1326 array( 'logging', 'user' ),
1327 array( 'log_type',
1328 'log_action',
1329 'log_timestamp',
1330 'log_user',
1331 'log_namespace',
1332 'log_title',
1333 'log_comment',
1334 'log_params',
1335 'user_name', ),
1336 array( 'log_namespace' => $this->mTitle->getNamespace(),
1337 'log_title' => $this->mTitle->getDBkey(),
1338 'log_type' => 'delete',
1339 'log_action' => 'delete',
1340 'user_id=log_user' ),
1341 $fname,
1342 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1343
1344 if($dbr->numRows($res) == 1) {
1345 while ( $x = $dbr->fetchObject ( $res ) )
1346 $data = $x;
1347 $dbr->freeResult ( $res ) ;
1348 } else {
1349 $data = null;
1350 }
1351 return $data;
1352 }
1353
1354 /**
1355 * @todo document
1356 */
1357 function getPreviewText() {
1358 global $wgOut, $wgUser, $wgTitle, $wgParser;
1359
1360 $fname = 'EditPage::getPreviewText';
1361 wfProfileIn( $fname );
1362
1363 if ( $this->mTriedSave && !$this->mTokenOk ) {
1364 $msg = 'session_fail_preview';
1365 } else {
1366 $msg = 'previewnote';
1367 }
1368 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1369 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1370 if ( $this->isConflict ) {
1371 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1372 }
1373
1374 $parserOptions = ParserOptions::newFromUser( $wgUser );
1375 $parserOptions->setEditSection( false );
1376
1377 global $wgRawHtml;
1378 if( $wgRawHtml && !$this->mTokenOk ) {
1379 // Could be an offsite preview attempt. This is very unsafe if
1380 // HTML is enabled, as it could be an attack.
1381 return $wgOut->parse( "<div class='previewnote'>" .
1382 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1383 }
1384
1385 # don't parse user css/js, show message about preview
1386 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1387
1388 if ( $this->isCssJsSubpage ) {
1389 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1390 $previewtext = wfMsg('usercsspreview');
1391 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1392 $previewtext = wfMsg('userjspreview');
1393 }
1394 $parserOptions->setTidy(true);
1395 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1396 $wgOut->addHTML( $parserOutput->mText );
1397 wfProfileOut( $fname );
1398 return $previewhead;
1399 } else {
1400 $toparse = $this->textbox1;
1401
1402 # If we're adding a comment, we need to show the
1403 # summary as the headline
1404 if($this->section=="new" && $this->summary!="") {
1405 $toparse="== {$this->summary} ==\n\n".$toparse;
1406 }
1407
1408 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1409 $parserOptions->setTidy(true);
1410 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1411 $wgTitle, $parserOptions );
1412
1413 $previewHTML = $parserOutput->getText();
1414 $wgOut->addParserOutputNoText( $parserOutput );
1415
1416 foreach ( $parserOutput->getTemplates() as $ns => $template)
1417 foreach ( array_keys( $template ) as $dbk)
1418 $this->mPreviewTemplates[] = Title::makeTitle($ns, $dbk);
1419
1420 wfProfileOut( $fname );
1421 return $previewhead . $previewHTML;
1422 }
1423 }
1424
1425 /**
1426 * Call the stock "user is blocked" page
1427 */
1428 function blockedPage() {
1429 global $wgOut, $wgUser;
1430 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1431
1432 # If the user made changes, preserve them when showing the markup
1433 # (This happens when a user is blocked during edit, for instance)
1434 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
1435 if( $first ) {
1436 $source = $this->mTitle->exists() ? $this->getContent() : false;
1437 } else {
1438 $source = $this->textbox1;
1439 }
1440
1441 # Spit out the source or the user's modified version
1442 if( $source !== false ) {
1443 $rows = $wgUser->getOption( 'rows' );
1444 $cols = $wgUser->getOption( 'cols' );
1445 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1446 $wgOut->addHtml( '<hr />' );
1447 $wgOut->addWikiText( wfMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() ) );
1448 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1449 }
1450 }
1451
1452 /**
1453 * Produce the stock "please login to edit pages" page
1454 */
1455 function userNotLoggedInPage() {
1456 global $wgUser, $wgOut;
1457 $skin = $wgUser->getSkin();
1458
1459 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1460 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $this->mTitle->getPrefixedUrl() );
1461
1462 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1463 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1464 $wgOut->setArticleRelated( false );
1465
1466 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1467 $wgOut->returnToMain( false, $this->mTitle->getPrefixedUrl() );
1468 }
1469
1470 /**
1471 * Creates a basic error page which informs the user that
1472 * they have to validate their email address before being
1473 * allowed to edit.
1474 */
1475 function userNotConfirmedPage() {
1476 global $wgOut;
1477
1478 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1479 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1480 $wgOut->setArticleRelated( false );
1481
1482 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1483 $wgOut->returnToMain( false );
1484 }
1485
1486 /**
1487 * Creates a basic error page which informs the user that
1488 * they have attempted to edit a nonexistant section.
1489 */
1490 function noSuchSectionPage() {
1491 global $wgOut;
1492
1493 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1494 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1495 $wgOut->setArticleRelated( false );
1496
1497 $wgOut->addWikiText( wfMsg( 'nosuchsectiontext', $this->section ) );
1498 $wgOut->returnToMain( false );
1499 }
1500
1501 /**
1502 * Produce the stock "your edit contains spam" page
1503 *
1504 * @param $match Text which triggered one or more filters
1505 */
1506 function spamPage( $match = false ) {
1507 global $wgOut;
1508
1509 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1510 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1511 $wgOut->setArticleRelated( false );
1512
1513 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1514 if ( $match )
1515 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1516
1517 $wgOut->returnToMain( false );
1518 }
1519
1520 /**
1521 * @private
1522 * @todo document
1523 */
1524 function mergeChangesInto( &$editText ){
1525 $fname = 'EditPage::mergeChangesInto';
1526 wfProfileIn( $fname );
1527
1528 $db = wfGetDB( DB_MASTER );
1529
1530 // This is the revision the editor started from
1531 $baseRevision = Revision::loadFromTimestamp(
1532 $db, $this->mArticle->mTitle, $this->edittime );
1533 if( is_null( $baseRevision ) ) {
1534 wfProfileOut( $fname );
1535 return false;
1536 }
1537 $baseText = $baseRevision->getText();
1538
1539 // The current state, we want to merge updates into it
1540 $currentRevision = Revision::loadFromTitle(
1541 $db, $this->mArticle->mTitle );
1542 if( is_null( $currentRevision ) ) {
1543 wfProfileOut( $fname );
1544 return false;
1545 }
1546 $currentText = $currentRevision->getText();
1547
1548 $result = '';
1549 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1550 $editText = $result;
1551 wfProfileOut( $fname );
1552 return true;
1553 } else {
1554 wfProfileOut( $fname );
1555 return false;
1556 }
1557 }
1558
1559 /**
1560 * Check if the browser is on a blacklist of user-agents known to
1561 * mangle UTF-8 data on form submission. Returns true if Unicode
1562 * should make it through, false if it's known to be a problem.
1563 * @return bool
1564 * @private
1565 */
1566 function checkUnicodeCompliantBrowser() {
1567 global $wgBrowserBlackList;
1568 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1569 // No User-Agent header sent? Trust it by default...
1570 return true;
1571 }
1572 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1573 foreach ( $wgBrowserBlackList as $browser ) {
1574 if ( preg_match($browser, $currentbrowser) ) {
1575 return false;
1576 }
1577 }
1578 return true;
1579 }
1580
1581 /**
1582 * Format an anchor fragment as it would appear for a given section name
1583 * @param string $text
1584 * @return string
1585 * @private
1586 */
1587 function sectionAnchor( $text ) {
1588 $headline = Sanitizer::decodeCharReferences( $text );
1589 # strip out HTML
1590 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1591 $headline = trim( $headline );
1592 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1593 $replacearray = array(
1594 '%3A' => ':',
1595 '%' => '.'
1596 );
1597 return str_replace(
1598 array_keys( $replacearray ),
1599 array_values( $replacearray ),
1600 $sectionanchor );
1601 }
1602
1603 /**
1604 * Shows a bulletin board style toolbar for common editing functions.
1605 * It can be disabled in the user preferences.
1606 * The necessary JavaScript code can be found in style/wikibits.js.
1607 */
1608 function getEditToolbar() {
1609 global $wgStylePath, $wgContLang, $wgJsMimeType;
1610
1611 /**
1612 * toolarray an array of arrays which each include the filename of
1613 * the button image (without path), the opening tag, the closing tag,
1614 * and optionally a sample text that is inserted between the two when no
1615 * selection is highlighted.
1616 * The tip text is shown when the user moves the mouse over the button.
1617 *
1618 * Already here are accesskeys (key), which are not used yet until someone
1619 * can figure out a way to make them work in IE. However, we should make
1620 * sure these keys are not defined on the edit page.
1621 */
1622 $toolarray = array(
1623 array( 'image' => 'button_bold.png',
1624 'id' => 'mw-editbutton-bold',
1625 'open' => '\\\'\\\'\\\'',
1626 'close' => '\\\'\\\'\\\'',
1627 'sample'=> wfMsg('bold_sample'),
1628 'tip' => wfMsg('bold_tip'),
1629 'key' => 'B'
1630 ),
1631 array( 'image' => 'button_italic.png',
1632 'id' => 'mw-editbutton-italic',
1633 'open' => '\\\'\\\'',
1634 'close' => '\\\'\\\'',
1635 'sample'=> wfMsg('italic_sample'),
1636 'tip' => wfMsg('italic_tip'),
1637 'key' => 'I'
1638 ),
1639 array( 'image' => 'button_link.png',
1640 'id' => 'mw-editbutton-link',
1641 'open' => '[[',
1642 'close' => ']]',
1643 'sample'=> wfMsg('link_sample'),
1644 'tip' => wfMsg('link_tip'),
1645 'key' => 'L'
1646 ),
1647 array( 'image' => 'button_extlink.png',
1648 'id' => 'mw-editbutton-extlink',
1649 'open' => '[',
1650 'close' => ']',
1651 'sample'=> wfMsg('extlink_sample'),
1652 'tip' => wfMsg('extlink_tip'),
1653 'key' => 'X'
1654 ),
1655 array( 'image' => 'button_headline.png',
1656 'id' => 'mw-editbutton-headline',
1657 'open' => "\\n== ",
1658 'close' => " ==\\n",
1659 'sample'=> wfMsg('headline_sample'),
1660 'tip' => wfMsg('headline_tip'),
1661 'key' => 'H'
1662 ),
1663 array( 'image' => 'button_image.png',
1664 'id' => 'mw-editbutton-image',
1665 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).":",
1666 'close' => ']]',
1667 'sample'=> wfMsg('image_sample'),
1668 'tip' => wfMsg('image_tip'),
1669 'key' => 'D'
1670 ),
1671 array( 'image' => 'button_media.png',
1672 'id' => 'mw-editbutton-media',
1673 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1674 'close' => ']]',
1675 'sample'=> wfMsg('media_sample'),
1676 'tip' => wfMsg('media_tip'),
1677 'key' => 'M'
1678 ),
1679 array( 'image' => 'button_math.png',
1680 'id' => 'mw-editbutton-math',
1681 'open' => "<math>",
1682 'close' => "<\\/math>",
1683 'sample'=> wfMsg('math_sample'),
1684 'tip' => wfMsg('math_tip'),
1685 'key' => 'C'
1686 ),
1687 array( 'image' => 'button_nowiki.png',
1688 'id' => 'mw-editbutton-nowiki',
1689 'open' => "<nowiki>",
1690 'close' => "<\\/nowiki>",
1691 'sample'=> wfMsg('nowiki_sample'),
1692 'tip' => wfMsg('nowiki_tip'),
1693 'key' => 'N'
1694 ),
1695 array( 'image' => 'button_sig.png',
1696 'id' => 'mw-editbutton-signature',
1697 'open' => '--~~~~',
1698 'close' => '',
1699 'sample'=> '',
1700 'tip' => wfMsg('sig_tip'),
1701 'key' => 'Y'
1702 ),
1703 array( 'image' => 'button_hr.png',
1704 'id' => 'mw-editbutton-hr',
1705 'open' => "\\n----\\n",
1706 'close' => '',
1707 'sample'=> '',
1708 'tip' => wfMsg('hr_tip'),
1709 'key' => 'R'
1710 )
1711 );
1712 $toolbar = "<div id='toolbar'>\n";
1713 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1714
1715 foreach($toolarray as $tool) {
1716
1717 $cssId = $tool['id'];
1718 $image=$wgStylePath.'/common/images/'.$tool['image'];
1719 $open=$tool['open'];
1720 $close=$tool['close'];
1721 $sample = wfEscapeJsString( $tool['sample'] );
1722
1723 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1724 // Older browsers show a "speedtip" type message only for ALT.
1725 // Ideally these should be different, realistically they
1726 // probably don't need to be.
1727 $tip = wfEscapeJsString( $tool['tip'] );
1728
1729 #$key = $tool["key"];
1730
1731 $toolbar.="addButton('$image','$tip','$open','$close','$sample','$cssId');\n";
1732 }
1733
1734 $toolbar.="/*]]>*/\n</script>";
1735 $toolbar.="\n</div>";
1736 return $toolbar;
1737 }
1738
1739 /**
1740 * Returns an array of html code of the following checkboxes:
1741 * minor and watch
1742 *
1743 * @param $tabindex Current tabindex
1744 * @param $skin Skin object
1745 * @param $checked Array of checkbox => bool, where bool indicates the checked
1746 * status of the checkbox
1747 *
1748 * @return array
1749 */
1750 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1751 global $wgUser;
1752
1753 $checkboxes = array();
1754
1755 $checkboxes['minor'] = '';
1756 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1757 if ( $wgUser->isAllowed('minoredit') ) {
1758 $attribs = array(
1759 'tabindex' => ++$tabindex,
1760 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1761 'id' => 'wpMinoredit',
1762 );
1763 $checkboxes['minor'] =
1764 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1765 "&nbsp;<label for='wpMinoredit'".$skin->tooltipAndAccesskey('minoredit').">{$minorLabel}</label>";
1766 }
1767
1768 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
1769 $checkboxes['watch'] = '';
1770 if ( $wgUser->isLoggedIn() ) {
1771 $attribs = array(
1772 'tabindex' => ++$tabindex,
1773 'accesskey' => wfMsg( 'accesskey-watch' ),
1774 'id' => 'wpWatchthis',
1775 );
1776 $checkboxes['watch'] =
1777 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
1778 "&nbsp;<label for='wpWatchthis'".$skin->tooltipAndAccesskey('watch').">{$watchLabel}</label>";
1779 }
1780 return $checkboxes;
1781 }
1782
1783 /**
1784 * Returns an array of html code of the following buttons:
1785 * save, diff, preview and live
1786 *
1787 * @param $tabindex Current tabindex
1788 *
1789 * @return array
1790 */
1791 public function getEditButtons(&$tabindex) {
1792 global $wgLivePreview, $wgUser;
1793
1794 $buttons = array();
1795
1796 $temp = array(
1797 'id' => 'wpSave',
1798 'name' => 'wpSave',
1799 'type' => 'submit',
1800 'tabindex' => ++$tabindex,
1801 'value' => wfMsg('savearticle'),
1802 'accesskey' => wfMsg('accesskey-save'),
1803 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1804 );
1805 $buttons['save'] = wfElement('input', $temp, '');
1806
1807 ++$tabindex; // use the same for preview and live preview
1808 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1809 $temp = array(
1810 'id' => 'wpPreview',
1811 'name' => 'wpPreview',
1812 'type' => 'submit',
1813 'tabindex' => $tabindex,
1814 'value' => wfMsg('showpreview'),
1815 'accesskey' => '',
1816 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1817 'style' => 'display: none;',
1818 );
1819 $buttons['preview'] = wfElement('input', $temp, '');
1820
1821 $temp = array(
1822 'id' => 'wpLivePreview',
1823 'name' => 'wpLivePreview',
1824 'type' => 'submit',
1825 'tabindex' => $tabindex,
1826 'value' => wfMsg('showlivepreview'),
1827 'accesskey' => wfMsg('accesskey-preview'),
1828 'title' => '',
1829 'onclick' => $this->doLivePreviewScript(),
1830 );
1831 $buttons['live'] = wfElement('input', $temp, '');
1832 } else {
1833 $temp = array(
1834 'id' => 'wpPreview',
1835 'name' => 'wpPreview',
1836 'type' => 'submit',
1837 'tabindex' => $tabindex,
1838 'value' => wfMsg('showpreview'),
1839 'accesskey' => wfMsg('accesskey-preview'),
1840 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1841 );
1842 $buttons['preview'] = wfElement('input', $temp, '');
1843 $buttons['live'] = '';
1844 }
1845
1846 $temp = array(
1847 'id' => 'wpDiff',
1848 'name' => 'wpDiff',
1849 'type' => 'submit',
1850 'tabindex' => ++$tabindex,
1851 'value' => wfMsg('showdiff'),
1852 'accesskey' => wfMsg('accesskey-diff'),
1853 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1854 );
1855 $buttons['diff'] = wfElement('input', $temp, '');
1856
1857 return $buttons;
1858 }
1859
1860 /**
1861 * Output preview text only. This can be sucked into the edit page
1862 * via JavaScript, and saves the server time rendering the skin as
1863 * well as theoretically being more robust on the client (doesn't
1864 * disturb the edit box's undo history, won't eat your text on
1865 * failure, etc).
1866 *
1867 * @todo This doesn't include category or interlanguage links.
1868 * Would need to enhance it a bit, <s>maybe wrap them in XML
1869 * or something...</s> that might also require more skin
1870 * initialization, so check whether that's a problem.
1871 */
1872 function livePreview() {
1873 global $wgOut;
1874 $wgOut->disable();
1875 header( 'Content-type: text/xml; charset=utf-8' );
1876 header( 'Cache-control: no-cache' );
1877
1878 $s =
1879 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
1880 Xml::openElement( 'livepreview' ) .
1881 Xml::element( 'preview', null, $this->getPreviewText() ) .
1882 Xml::element( 'br', array( 'style' => 'clear: both;' ) ) .
1883 Xml::closeElement( 'livepreview' );
1884 echo $s;
1885 }
1886
1887
1888 /**
1889 * Get a diff between the current contents of the edit box and the
1890 * version of the page we're editing from.
1891 *
1892 * If this is a section edit, we'll replace the section as for final
1893 * save and then make a comparison.
1894 *
1895 * @return string HTML
1896 */
1897 function getDiff() {
1898 $oldtext = $this->mArticle->fetchContent();
1899 $newtext = $this->mArticle->replaceSection(
1900 $this->section, $this->textbox1, $this->summary, $this->edittime );
1901 $newtext = $this->mArticle->preSaveTransform( $newtext );
1902 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1903 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
1904 if ( $oldtext !== false || $newtext != '' ) {
1905 $de = new DifferenceEngine( $this->mTitle );
1906 $de->setText( $oldtext, $newtext );
1907 $difftext = $de->getDiff( $oldtitle, $newtitle );
1908 } else {
1909 $difftext = '';
1910 }
1911
1912 return '<div id="wikiDiff">' . $difftext . '</div>';
1913 }
1914
1915 /**
1916 * Filter an input field through a Unicode de-armoring process if it
1917 * came from an old browser with known broken Unicode editing issues.
1918 *
1919 * @param WebRequest $request
1920 * @param string $field
1921 * @return string
1922 * @private
1923 */
1924 function safeUnicodeInput( $request, $field ) {
1925 $text = rtrim( $request->getText( $field ) );
1926 return $request->getBool( 'safemode' )
1927 ? $this->unmakesafe( $text )
1928 : $text;
1929 }
1930
1931 /**
1932 * Filter an output field through a Unicode armoring process if it is
1933 * going to an old browser with known broken Unicode editing issues.
1934 *
1935 * @param string $text
1936 * @return string
1937 * @private
1938 */
1939 function safeUnicodeOutput( $text ) {
1940 global $wgContLang;
1941 $codedText = $wgContLang->recodeForEdit( $text );
1942 return $this->checkUnicodeCompliantBrowser()
1943 ? $codedText
1944 : $this->makesafe( $codedText );
1945 }
1946
1947 /**
1948 * A number of web browsers are known to corrupt non-ASCII characters
1949 * in a UTF-8 text editing environment. To protect against this,
1950 * detected browsers will be served an armored version of the text,
1951 * with non-ASCII chars converted to numeric HTML character references.
1952 *
1953 * Preexisting such character references will have a 0 added to them
1954 * to ensure that round-trips do not alter the original data.
1955 *
1956 * @param string $invalue
1957 * @return string
1958 * @private
1959 */
1960 function makesafe( $invalue ) {
1961 // Armor existing references for reversability.
1962 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1963
1964 $bytesleft = 0;
1965 $result = "";
1966 $working = 0;
1967 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1968 $bytevalue = ord( $invalue{$i} );
1969 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1970 $result .= chr( $bytevalue );
1971 $bytesleft = 0;
1972 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1973 $working = $working << 6;
1974 $working += ($bytevalue & 0x3F);
1975 $bytesleft--;
1976 if( $bytesleft <= 0 ) {
1977 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1978 }
1979 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1980 $working = $bytevalue & 0x1F;
1981 $bytesleft = 1;
1982 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1983 $working = $bytevalue & 0x0F;
1984 $bytesleft = 2;
1985 } else { //1111 0xxx
1986 $working = $bytevalue & 0x07;
1987 $bytesleft = 3;
1988 }
1989 }
1990 return $result;
1991 }
1992
1993 /**
1994 * Reverse the previously applied transliteration of non-ASCII characters
1995 * back to UTF-8. Used to protect data from corruption by broken web browsers
1996 * as listed in $wgBrowserBlackList.
1997 *
1998 * @param string $invalue
1999 * @return string
2000 * @private
2001 */
2002 function unmakesafe( $invalue ) {
2003 $result = "";
2004 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2005 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
2006 $i += 3;
2007 $hexstring = "";
2008 do {
2009 $hexstring .= $invalue{$i};
2010 $i++;
2011 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2012
2013 // Do some sanity checks. These aren't needed for reversability,
2014 // but should help keep the breakage down if the editor
2015 // breaks one of the entities whilst editing.
2016 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
2017 $codepoint = hexdec($hexstring);
2018 $result .= codepointToUtf8( $codepoint );
2019 } else {
2020 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2021 }
2022 } else {
2023 $result .= substr( $invalue, $i, 1 );
2024 }
2025 }
2026 // reverse the transform that we made for reversability reasons.
2027 return strtr( $result, array( "&#x0" => "&#x" ) );
2028 }
2029
2030 function noCreatePermission() {
2031 global $wgOut;
2032 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2033 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
2034 }
2035
2036 }
2037
2038 ?>