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