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