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