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