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