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