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