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