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