Deferred initialisation of $wgIP, because it's potentially slow, especially if and...
[lhc/web/wiklou.git] / includes / EditPage.php
1 <?php
2 /**
3 * Contain the EditPage class
4 * @package MediaWiki
5 */
6
7 /**
8 * Splitting edit page/HTML interface from Article...
9 * The actual database and text munging is still in Article,
10 * but it should get easier to call those from alternate
11 * interfaces.
12 *
13 * @package MediaWiki
14 */
15
16 class EditPage {
17 var $mArticle;
18 var $mTitle;
19 var $mMetaData = '';
20 var $isConflict = false;
21 var $isCssJsSubpage = false;
22 var $deletedSinceEdit = false;
23 var $formtype;
24 var $firsttime;
25 var $lastDelete;
26
27 # Form values
28 var $save = false, $preview = false, $diff = false;
29 var $minoredit = false, $watchthis = false, $recreate = false;
30 var $textbox1 = '', $textbox2 = '', $summary = '';
31 var $edittime = '', $section = '', $starttime = '';
32 var $oldid = 0, $editintro = '';
33
34 /**
35 * @todo document
36 * @param $article
37 */
38 function EditPage( $article ) {
39 $this->mArticle =& $article;
40 global $wgTitle;
41 $this->mTitle =& $wgTitle;
42 }
43
44 /**
45 * This is the function that extracts metadata from the article body on the first view.
46 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
47 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
48 */
49 function extractMetaDataFromArticle () {
50 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
51 $this->mMetaData = '' ;
52 if ( !$wgUseMetadataEdit ) return ;
53 if ( $wgMetadataWhitelist == '' ) return ;
54 $s = '' ;
55 $t = $this->mArticle->getContent ( true ) ;
56
57 # MISSING : <nowiki> filtering
58
59 # Categories and language links
60 $t = explode ( "\n" , $t ) ;
61 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY ) ) ;
62 $cat = $ll = array() ;
63 foreach ( $t AS $key => $x )
64 {
65 $y = trim ( strtolower ( $x ) ) ;
66 while ( substr ( $y , 0 , 2 ) == '[[' )
67 {
68 $y = explode ( ']]' , trim ( $x ) ) ;
69 $first = array_shift ( $y ) ;
70 $first = explode ( ':' , $first ) ;
71 $ns = array_shift ( $first ) ;
72 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
73 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
74 {
75 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
76 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
77 else $ll[] = $add ;
78 $x = implode ( ']]' , $y ) ;
79 $t[$key] = $x ;
80 $y = trim ( strtolower ( $x ) ) ;
81 }
82 }
83 }
84 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
85 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
86 $t = implode ( "\n" , $t ) ;
87
88 # Load whitelist
89 $sat = array () ; # stand-alone-templates; must be lowercase
90 $wl_title = Title::newFromText ( $wgMetadataWhitelist ) ;
91 $wl_article = new Article ( $wl_title ) ;
92 $wl = explode ( "\n" , $wl_article->getContent(true) ) ;
93 foreach ( $wl AS $x )
94 {
95 $isentry = false ;
96 $x = trim ( $x ) ;
97 while ( substr ( $x , 0 , 1 ) == '*' )
98 {
99 $isentry = true ;
100 $x = trim ( substr ( $x , 1 ) ) ;
101 }
102 if ( $isentry )
103 {
104 $sat[] = strtolower ( $x ) ;
105 }
106
107 }
108
109 # Templates, but only some
110 $t = explode ( '{{' , $t ) ;
111 $tl = array () ;
112 foreach ( $t AS $key => $x )
113 {
114 $y = explode ( '}}' , $x , 2 ) ;
115 if ( count ( $y ) == 2 )
116 {
117 $z = $y[0] ;
118 $z = explode ( '|' , $z ) ;
119 $tn = array_shift ( $z ) ;
120 if ( in_array ( strtolower ( $tn ) , $sat ) )
121 {
122 $tl[] = '{{' . $y[0] . '}}' ;
123 $t[$key] = $y[1] ;
124 $y = explode ( '}}' , $y[1] , 2 ) ;
125 }
126 else $t[$key] = '{{' . $x ;
127 }
128 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
129 else $t[$key] = $x ;
130 }
131 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
132 $t = implode ( '' , $t ) ;
133
134 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
135 $this->mArticle->mContent = $t ;
136 $this->mMetaData = $s ;
137 }
138
139 function submit() {
140 $this->edit();
141 }
142
143 /**
144 * This is the function that gets called for "action=edit". It
145 * sets up various member variables, then passes execution to
146 * another function, usually showEditForm()
147 *
148 * The edit form is self-submitting, so that when things like
149 * preview and edit conflicts occur, we get the same form back
150 * with the extra stuff added. Only when the final submission
151 * is made and all is well do we actually save and redirect to
152 * the newly-edited page.
153 */
154 function edit() {
155 global $wgOut, $wgUser, $wgRequest, $wgTitle;
156
157 $fname = 'EditPage::edit';
158 wfProfileIn( $fname );
159
160 // this is not an article
161 $wgOut->setArticleFlag(false);
162
163 $this->importFormData( $wgRequest );
164 $this->firsttime = false;
165
166 if( $this->live ) {
167 $this->livePreview();
168 wfProfileOut( $fname );
169 return;
170 }
171
172 if ( ! $this->mTitle->userCanEdit() ) {
173 $wgOut->readOnlyPage( $this->mArticle->getContent( true ), true );
174 wfProfileOut( $fname );
175 return;
176 }
177 if ( !$this->preview && !$this->diff && $wgUser->isBlockedFrom( $this->mTitle, !$this->save ) ) {
178 # When previewing, don't check blocked state - will get caught at save time.
179 # Also, check when starting edition is done against slave to improve performance.
180 $this->blockedIPpage();
181 wfProfileOut( $fname );
182 return;
183 }
184 if ( !$wgUser->isAllowed('edit') ) {
185 if ( $wgUser->isAnon() ) {
186 $this->userNotLoggedInPage();
187 wfProfileOut( $fname );
188 return;
189 } else {
190 $wgOut->readOnlyPage( $this->mArticle->getContent( true ), true );
191 wfProfileOut( $fname );
192 return;
193 }
194 }
195 if ( wfReadOnly() ) {
196 if( $this->save || $this->preview ) {
197 $this->formtype = 'preview';
198 } else if ( $this->diff ) {
199 $this->formtype = 'diff';
200 } else {
201 $wgOut->readOnlyPage( $this->mArticle->getContent( true ) );
202 wfProfileOut( $fname );
203 return;
204 }
205 } else {
206 if ( $this->save ) {
207 $this->formtype = 'save';
208 } else if ( $this->preview ) {
209 $this->formtype = 'preview';
210 } else if ( $this->diff ) {
211 $this->formtype = 'diff';
212 } else { # First time through
213 $this->firsttime = true;
214 if( $this->previewOnOpen() ) {
215 $this->formtype = 'preview';
216 } else {
217 $this->extractMetaDataFromArticle () ;
218 $this->formtype = 'initial';
219 }
220 }
221 }
222
223 wfProfileIn( "$fname-business-end" );
224
225 $this->isConflict = false;
226 // css / js subpages of user pages get a special treatment
227 $this->isCssJsSubpage = $wgTitle->isCssJsSubpage();
228
229 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
230 * no matter it's current state
231 */
232 $this->deletedSinceEdit = false;
233 if ( $this->edittime != '' ) {
234 /* Note that we rely on logging table, which hasn't been always there,
235 * but that doesn't matter, because this only applies to brand new
236 * deletes. This is done on every preview and save request. Move it further down
237 * to only perform it on saves
238 */
239 if ( $this->mTitle->isDeleted() ) {
240 $this->lastDelete = $this->getLastDelete();
241 if ( !is_null($this->lastDelete) ) {
242 $deletetime = $this->lastDelete->log_timestamp;
243 if ( ($deletetime - $this->starttime) > 0 ) {
244 $this->deletedSinceEdit = true;
245 }
246 }
247 }
248 }
249
250 if(!$this->mTitle->getArticleID() && ('initial' == $this->formtype || $this->firsttime )) { # new article
251 $this->showIntro();
252 }
253 if( $this->mTitle->isTalkPage() ) {
254 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
255 }
256
257 # Attempt submission here. This will check for edit conflicts,
258 # and redundantly check for locked database, blocked IPs, etc.
259 # that edit() already checked just in case someone tries to sneak
260 # in the back door with a hand-edited submission URL.
261
262 if ( 'save' == $this->formtype ) {
263 if ( !$this->attemptSave() ) {
264 wfProfileOut( "$fname-business-end" );
265 wfProfileOut( $fname );
266 return;
267 }
268 }
269
270 # First time through: get contents, set time for conflict
271 # checking, etc.
272 if ( 'initial' == $this->formtype || $this->firsttime ) {
273 $this->initialiseForm();
274 }
275
276 $this->showEditForm();
277 wfProfileOut( "$fname-business-end" );
278 wfProfileOut( $fname );
279 }
280
281 /**
282 * Return true if this page should be previewed when the edit form
283 * is initially opened.
284 * @return bool
285 * @access private
286 */
287 function previewOnOpen() {
288 global $wgUser;
289 return $wgUser->getOption( 'previewonfirst' ) ||
290 ( $this->mTitle->getNamespace() == NS_CATEGORY &&
291 !$this->mTitle->exists() );
292 }
293
294 /**
295 * @todo document
296 */
297 function importFormData( &$request ) {
298 $fname = 'EditPage::importFormData';
299 wfProfileIn( $fname );
300
301 if( $request->wasPosted() ) {
302 # These fields need to be checked for encoding.
303 # Also remove trailing whitespace, but don't remove _initial_
304 # whitespace from the text boxes. This may be significant formatting.
305 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
306 $this->textbox2 = $this->safeUnicodeInput( $request, 'wpTextbox2' );
307 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
308 $this->summary = $request->getText( 'wpSummary' );
309
310 $this->edittime = $request->getVal( 'wpEdittime' );
311 $this->starttime = $request->getVal( 'wpStarttime' );
312 if( is_null( $this->edittime ) ) {
313 # If the form is incomplete, force to preview.
314 $this->preview = true;
315 } else {
316 if( $this->tokenOk( $request ) ) {
317 # Some browsers will not report any submit button
318 # if the user hits enter in the comment box.
319 # The unmarked state will be assumed to be a save,
320 # if the form seems otherwise complete.
321 $this->preview = $request->getCheck( 'wpPreview' );
322 $this->diff = $request->getCheck( 'wpDiff' );
323 } else {
324 # Page might be a hack attempt posted from
325 # an external site. Preview instead of saving.
326 $this->preview = true;
327 }
328 }
329 $this->save = ! ( $this->preview OR $this->diff );
330 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
331 $this->edittime = null;
332 }
333
334 if( !preg_match( '/^\d{14}$/', $this->starttime )) {
335 $this->starttime = null;
336 }
337
338 $this->recreate = $request->getCheck( 'wpRecreate' );
339
340 $this->minoredit = $request->getCheck( 'wpMinoredit' );
341 $this->watchthis = $request->getCheck( 'wpWatchthis' );
342 } else {
343 # Not a posted form? Start with nothing.
344 $this->textbox1 = '';
345 $this->textbox2 = '';
346 $this->mMetaData = '';
347 $this->summary = '';
348 $this->edittime = '';
349 $this->starttime = wfTimestampNow();
350 $this->preview = false;
351 $this->save = false;
352 $this->diff = false;
353 $this->minoredit = false;
354 $this->watchthis = false;
355 $this->recreate = false;
356 }
357
358 $this->oldid = $request->getInt( 'oldid' );
359
360 # Section edit can come from either the form or a link
361 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
362
363 $this->live = $request->getCheck( 'live' );
364 $this->editintro = $request->getText( 'editintro' );
365
366 wfProfileOut( $fname );
367 }
368
369 /**
370 * Make sure the form isn't faking a user's credentials.
371 *
372 * @param WebRequest $request
373 * @return bool
374 * @access private
375 */
376 function tokenOk( &$request ) {
377 global $wgUser;
378 if( $wgUser->isAnon() ) {
379 # Anonymous users may not have a session
380 # open. Don't tokenize.
381 return true;
382 } else {
383 return $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
384 }
385 }
386
387 function showIntro() {
388 global $wgOut;
389 $addstandardintro=true;
390 if($this->editintro) {
391 $introtitle=Title::newFromText($this->editintro);
392 if(isset($introtitle) && $introtitle->userCanRead()) {
393 $rev=Revision::newFromTitle($introtitle);
394 if($rev) {
395 $wgOut->addWikiText($rev->getText());
396 $addstandardintro=false;
397 }
398 }
399 }
400 if($addstandardintro) {
401 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
402 }
403 }
404
405 /**
406 * Attempt submission
407 * @return bool false if output is done, true if the rest of the form should be displayed
408 */
409 function attemptSave() {
410 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
411
412 $fname = 'EditPage::attemptSave';
413 wfProfileIn( $fname );
414 wfProfileIn( "$fname-checks" );
415
416 # Reintegrate metadata
417 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
418 $this->mMetaData = '' ;
419
420 # Check for spam
421 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
422 $this->spamPage ( $matches[0] );
423 wfProfileOut( "$fname-checks" );
424 wfProfileOut( $fname );
425 return false;
426 }
427 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
428 # Error messages or other handling should be performed by the filter function
429 wfProfileOut( $fname );
430 wfProfileOut( "$fname-checks" );
431 return false;
432 }
433 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
434 # Check block state against master, thus 'false'.
435 $this->blockedIPpage();
436 wfProfileOut( "$fname-checks" );
437 wfProfileOut( $fname );
438 return false;
439 }
440
441 if ( !$wgUser->isAllowed('edit') ) {
442 if ( $wgUser->isAnon() ) {
443 $this->userNotLoggedInPage();
444 wfProfileOut( "$fname-checks" );
445 wfProfileOut( $fname );
446 return false;
447 }
448 else {
449 $wgOut->readOnlyPage();
450 wfProfileOut( $fname );
451 return false;
452 }
453 }
454
455 if ( wfReadOnly() ) {
456 $wgOut->readOnlyPage();
457 wfProfileOut( "$fname-checks" );
458 wfProfileOut( $fname );
459 return false;
460 }
461 if ( $wgUser->pingLimiter() ) {
462 $wgOut->rateLimited();
463 wfProfileOut( "$fname-checks" );
464 wfProfileOut( $fname );
465 return false;
466 }
467
468 # If the article has been deleted while editing, don't save it without
469 # confirmation
470 if ( $this->deletedSinceEdit && !$this->recreate ) {
471 wfProfileOut( "$fname-checks" );
472 wfProfileOut( $fname );
473 return true;
474 }
475
476 wfProfileOut( "$fname-checks" );
477
478 # If article is new, insert it.
479 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
480 if ( 0 == $aid ) {
481 # Don't save a new article if it's blank.
482 if ( ( '' == $this->textbox1 ) ) {
483 $wgOut->redirect( $this->mTitle->getFullURL() );
484 wfProfileOut( $fname );
485 return false;
486 }
487
488 $isComment=($this->section=='new');
489 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
490 $this->minoredit, $this->watchthis, false, $isComment);
491
492 wfProfileOut( $fname );
493 return false;
494 }
495
496 # Article exists. Check for edit conflict.
497
498 $this->mArticle->clear(); # Force reload of dates, etc.
499 $this->mArticle->forUpdate( true ); # Lock the article
500
501 if( ( $this->section != 'new' ) &&
502 ($this->mArticle->getTimestamp() != $this->edittime ) )
503 {
504 $this->isConflict = true;
505 }
506 $userid = $wgUser->getID();
507
508 if ( $this->isConflict) {
509 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
510 $this->mArticle->getTimestamp() . "'\n" );
511 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
512 }
513 else {
514 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
515 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
516 }
517
518 # Suppress edit conflict with self, except for section edits where merging is required.
519 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
520 wfDebug( "Suppressing edit conflict, same user.\n" );
521 $this->isConflict = false;
522 } else {
523 # switch from section editing to normal editing in edit conflict
524 if($this->isConflict) {
525 # Attempt merge
526 if( $this->mergeChangesInto( $text ) ){
527 // Successful merge! Maybe we should tell the user the good news?
528 $this->isConflict = false;
529 wfDebug( "Suppressing edit conflict, successful merge.\n" );
530 } else {
531 $this->section = '';
532 $this->textbox1 = $text;
533 wfDebug( "Keeping edit conflict, failed merge.\n" );
534 }
535 }
536 }
537
538 if ( $this->isConflict ) {
539 wfProfileOut( $fname );
540 return true;
541 }
542
543 # All's well
544 wfProfileIn( "$fname-sectionanchor" );
545 $sectionanchor = '';
546 if( $this->section == 'new' ) {
547 if( $this->summary != '' ) {
548 $sectionanchor = $this->sectionAnchor( $this->summary );
549 }
550 } elseif( $this->section != '' ) {
551 # Try to get a section anchor from the section source, redirect to edited section if header found
552 # XXX: might be better to integrate this into Article::replaceSection
553 # for duplicate heading checking and maybe parsing
554 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
555 # we can't deal with anchors, includes, html etc in the header for now,
556 # headline would need to be parsed to improve this
557 if($hasmatch and strlen($matches[2]) > 0) {
558 $sectionanchor = $this->sectionAnchor( $matches[2] );
559 }
560 }
561 wfProfileOut( "$fname-sectionanchor" );
562
563 // Save errors may fall down to the edit form, but we've now
564 // merged the section into full text. Clear the section field
565 // so that later submission of conflict forms won't try to
566 // replace that into a duplicated mess.
567 $this->textbox1 = $text;
568 $this->section = '';
569
570 # update the article here
571 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
572 $this->watchthis, '', $sectionanchor ) ) {
573 wfProfileOut( $fname );
574 return false;
575 } else {
576 $this->isConflict = true;
577 }
578 wfProfileOut( $fname );
579 return true;
580 }
581
582 /**
583 * Initialise form fields in the object
584 * Called on the first invocation, e.g. when a user clicks an edit link
585 */
586 function initialiseForm() {
587 $this->edittime = $this->mArticle->getTimestamp();
588 $this->textbox1 = $this->mArticle->getContent( true );
589 $this->summary = '';
590 wfProxyCheck();
591 }
592
593 /**
594 * Send the edit form and related headers to $wgOut
595 */
596 function showEditForm() {
597 global $wgOut, $wgUser, $wgAllowAnonymousMinor, $wgLang, $wgContLang;
598
599 $fname = 'EditPage::showEditForm';
600 wfProfileIn( $fname );
601
602 $sk =& $wgUser->getSkin();
603
604 $wgOut->setRobotpolicy( 'noindex,nofollow' );
605
606 # Enabled article-related sidebar, toplinks, etc.
607 $wgOut->setArticleRelated( true );
608
609 if ( $this->isConflict ) {
610 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
611 $wgOut->setPageTitle( $s );
612 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
613
614 $this->textbox2 = $this->textbox1;
615 $this->textbox1 = $this->mArticle->getContent( true );
616 $this->edittime = $this->mArticle->getTimestamp();
617 } else {
618
619 if( $this->section != '' ) {
620 if( $this->section == 'new' ) {
621 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
622 } else {
623 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
624 if( !$this->preview && !$this->diff ) {
625 preg_match( "/^(=+)(.+)\\1/mi",
626 $this->textbox1,
627 $matches );
628 if( !empty( $matches[2] ) ) {
629 $this->summary = "/* ". trim($matches[2])." */ ";
630 }
631 }
632 }
633 } else {
634 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
635 }
636 $wgOut->setPageTitle( $s );
637 if ( !$this->checkUnicodeCompliantBrowser() ) {
638 $this->mArticle->setOldSubtitle();
639 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
640 }
641 if ( isset( $this->mArticle )
642 && isset( $this->mArticle->mRevision )
643 && !$this->mArticle->mRevision->isCurrent() ) {
644 $this->mArticle->setOldSubtitle();
645 $wgOut->addWikiText( wfMsg( 'editingold' ) );
646 }
647 }
648
649 if( wfReadOnly() ) {
650 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
651 } else if ( $this->isCssJsSubpage and 'preview' != $this->formtype) {
652 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ));
653 }
654 if( $this->mTitle->isProtected('edit') ) {
655 $wgOut->addWikiText( wfMsg( 'protectedpagewarning' ) );
656 }
657
658 $kblength = (int)(strlen( $this->textbox1 ) / 1024);
659 if( $kblength > 29 ) {
660 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $kblength ) ) );
661 }
662
663 $rows = $wgUser->getOption( 'rows' );
664 $cols = $wgUser->getOption( 'cols' );
665
666 $ew = $wgUser->getOption( 'editwidth' );
667 if ( $ew ) $ew = " style=\"width:100%\"";
668 else $ew = '';
669
670 $q = 'action=submit';
671 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
672 $action = $this->mTitle->escapeLocalURL( $q );
673
674 $summary = wfMsg('summary');
675 $subject = wfMsg('subject');
676 $minor = wfMsg('minoredit');
677 $watchthis = wfMsg ('watchthis');
678 $save = wfMsg('savearticle');
679 $prev = wfMsg('showpreview');
680 $diff = wfMsg('showdiff');
681
682 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
683 wfMsg('cancel') );
684 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsg( 'edithelppage' ));
685 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
686 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
687 htmlspecialchars( wfMsg( 'newwindow' ) );
688
689 global $wgRightsText;
690 $copywarn = "<div id=\"editpage-copywarn\">\n" .
691 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
692 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
693 $wgRightsText ) . "\n</div>";
694
695 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
696 # prepare toolbar for edit buttons
697 $toolbar = $this->getEditToolbar();
698 } else {
699 $toolbar = '';
700 }
701
702 // activate checkboxes if user wants them to be always active
703 if( !$this->preview && !$this->diff ) {
704 if( $wgUser->getOption( 'watchdefault' ) ) $this->watchthis = true;
705 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
706
707 // activate checkbox also if user is already watching the page,
708 // require wpWatchthis to be unset so that second condition is not
709 // checked unnecessarily
710 if( !$this->watchthis && $this->mTitle->userIsWatching() ) $this->watchthis = true;
711 }
712
713 $minoredithtml = '';
714
715 if ( $wgUser->isLoggedIn() || $wgAllowAnonymousMinor ) {
716 $minoredithtml =
717 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
718 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
719 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
720 }
721
722 $watchhtml = '';
723
724 if ( $wgUser->isLoggedIn() ) {
725 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
726 ($this->watchthis?" checked='checked'":"").
727 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />".
728 "<label for='wpWatchthis' title=\"" .
729 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>";
730 }
731
732 $checkboxhtml = $minoredithtml . $watchhtml . '<br />';
733
734 $wgOut->addHTML( '<div id="wikiPreview">' );
735 if ( 'preview' == $this->formtype) {
736 $previewOutput = $this->getPreviewText();
737 if ( $wgUser->getOption('previewontop' ) ) {
738 $wgOut->addHTML( $previewOutput );
739 if($this->mTitle->getNamespace() == NS_CATEGORY) {
740 $this->mArticle->closeShowCategory();
741 }
742 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
743 }
744 }
745 $wgOut->addHTML( '</div>' );
746 if ( 'diff' == $this->formtype ) {
747 if ( $wgUser->getOption('previewontop' ) ) {
748 $wgOut->addHTML( $this->getDiff() );
749 }
750 }
751
752
753 # if this is a comment, show a subject line at the top, which is also the edit summary.
754 # Otherwise, show a summary field at the bottom
755 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
756 if( $this->section == 'new' ) {
757 $commentsubject="{$subject}: <input tabindex='1' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
758 $editsummary = '';
759 } else {
760 $commentsubject = '';
761 $editsummary="{$summary}: <input tabindex='2' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
762 }
763
764 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
765 if( !$this->preview && !$this->diff ) {
766 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
767 }
768 $templates = $this->getTemplatesUsed();
769
770 global $wgLivePreview;
771 if ( $wgLivePreview ) {
772 $liveOnclick = $this->doLivePreviewScript();
773 } else {
774 $liveOnclick = '';
775 }
776
777 global $wgUseMetadataEdit ;
778 if ( $wgUseMetadataEdit ) {
779 $metadata = $this->mMetaData ;
780 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
781 $helppage = Title::newFromText( wfMsg( "metadata_page" ) ) ;
782 $top = wfMsg( 'metadata', $helppage->getInternalURL() );
783 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
784 }
785 else $metadata = "" ;
786
787 $hidden = '';
788 $recreate = '';
789 if ($this->deletedSinceEdit) {
790 if ( 'save' != $this->formtype ) {
791 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
792 } else {
793 // Hide the toolbar and edit area, use can click preview to get it back
794 // Add an confirmation checkbox and explanation.
795 $toolbar = '';
796 $hidden = 'type="hidden" style="display:none;"';
797 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
798 $recreate .=
799 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
800 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
801 }
802 }
803
804 $safemodehtml = $this->checkUnicodeCompliantBrowser()
805 ? ""
806 : "<input type='hidden' name=\"safemode\" value='1' />\n";
807
808 $wgOut->addHTML( <<<END
809 {$toolbar}
810 <form id="editform" name="editform" method="post" action="$action"
811 enctype="multipart/form-data">
812 $recreate
813 {$commentsubject}
814 <textarea tabindex='1' accesskey="," name="wpTextbox1" rows='{$rows}'
815 cols='{$cols}'{$ew} $hidden>
816 END
817 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
818 "
819 </textarea>
820 {$metadata}
821 <br />{$editsummary}
822 {$checkboxhtml}
823 {$safemodehtml}
824 <input tabindex='5' id='wpSave' type='submit' value=\"{$save}\" name=\"wpSave\" accesskey=\"".wfMsg('accesskey-save')."\"".
825 " title=\"".wfMsg('tooltip-save')."\"/>
826 <input tabindex='6' id='wpPreview' type='submit' $liveOnclick value=\"{$prev}\" name=\"wpPreview\" accesskey=\"".wfMsg('accesskey-preview')."\"".
827 " title=\"".wfMsg('tooltip-preview')."\"/>
828 <input tabindex='7' id='wpDiff' type='submit' value=\"{$diff}\" name=\"wpDiff\" accesskey=\"".wfMsg('accesskey-diff')."\"".
829 " title=\"".wfMsg('tooltip-diff')."\"/>
830 <em>{$cancel}</em> | <em>{$edithelp}</em>{$templates}" );
831 $wgOut->addWikiText( $copywarn );
832 $wgOut->addHTML( "
833 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
834 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
835 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n" );
836
837 if ( $wgUser->isLoggedIn() ) {
838 /**
839 * To make it harder for someone to slip a user a page
840 * which submits an edit form to the wiki without their
841 * knowledge, a random token is associated with the login
842 * session. If it's not passed back with the submission,
843 * we won't save the page, or render user JavaScript and
844 * CSS previews.
845 */
846 $token = htmlspecialchars( $wgUser->editToken() );
847 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
848 }
849
850
851 if ( $this->isConflict ) {
852 require_once( "DifferenceEngine.php" );
853 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
854 DifferenceEngine::showDiff( $this->textbox2, $this->textbox1,
855 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
856
857 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
858 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
859 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
860 }
861 $wgOut->addHTML( "</form>\n" );
862 if ( $this->formtype == 'preview' && !$wgUser->getOption( 'previewontop' ) ) {
863 $wgOut->addHTML( '<div id="wikiPreview">' . $previewOutput . '</div>' );
864 }
865 if ( $this->formtype == 'diff' && !$wgUser->getOption( 'previewontop' ) ) {
866 #$wgOut->addHTML( '<div id="wikiPreview">' . $difftext . '</div>' );
867 $wgOut->addHTML( $this->getDiff() );
868 }
869
870 wfProfileOut( $fname );
871 }
872
873 /**
874 * Prepare a list of templates used by this page. Returns HTML.
875 */
876 function getTemplatesUsed() {
877 global $wgUser;
878
879 $fname = 'EditPage::getTemplatesUsed';
880 wfProfileIn( $fname );
881
882 $sk =& $wgUser->getSkin();
883
884 $templates = '';
885 $articleTemplates = $this->mArticle->getUsedTemplates();
886 if ( count( $articleTemplates ) > 0 ) {
887 $templates = '<br />'. wfMsg( 'templatesused' ) . '<ul>';
888 foreach ( $articleTemplates as $tpl ) {
889 if ( $titleObj = Title::makeTitle( NS_TEMPLATE, $tpl ) ) {
890 $templates .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
891 }
892 }
893 $templates .= '</ul>';
894 }
895 wfProfileOut( $fname );
896 return $templates;
897 }
898
899 /**
900 * Live Preview lets us fetch rendered preview page content and
901 * add it to the page without refreshing the whole page.
902 * If not supported by the browser it will fall through to the normal form
903 * submission method.
904 *
905 * This function outputs a script tag to support live preview, and
906 * returns an onclick handler which should be added to the attributes
907 * of the preview button
908 */
909 function doLivePreviewScript() {
910 global $wgStylePath, $wgJsMimeType, $wgOut;
911 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
912 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
913 '"></script>' . "\n" );
914 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
915 return 'onclick="return !livePreview('.
916 'getElementById(\'wikiPreview\'),' .
917 'editform.wpTextbox1.value,' .
918 htmlspecialchars( '"' . $liveAction . '"' ) . ')"';
919 }
920
921 function getLastDelete() {
922 $dbr =& wfGetDB( DB_SLAVE );
923 $fname = 'EditPage::getLastDelete';
924 $res = $dbr->select(
925 array( 'logging', 'user' ),
926 array( 'log_type',
927 'log_action',
928 'log_timestamp',
929 'log_user',
930 'log_namespace',
931 'log_title',
932 'log_comment',
933 'log_params',
934 'user_name', ),
935 array( 'log_namespace' => $this->mTitle->getNamespace(),
936 'log_title' => $this->mTitle->getDBkey(),
937 'log_type' => 'delete',
938 'log_action' => 'delete',
939 'user_id=log_user' ),
940 $fname,
941 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
942
943 if($dbr->numRows($res) == 1) {
944 while ( $x = $dbr->fetchObject ( $res ) )
945 $data = $x;
946 $dbr->freeResult ( $res ) ;
947 } else {
948 $data = null;
949 }
950 return $data;
951 }
952
953 /**
954 * @todo document
955 */
956 function getPreviewText() {
957 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgAllowDiffPreview, $wgEnableDiffPreviewPreference;
958
959 $fname = 'EditPage::getPreviewText';
960 wfProfileIn( $fname );
961
962 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
963 "<p class='previewnote'>" . htmlspecialchars( wfMsg( 'previewnote' ) ) . "</p>\n";
964 if ( $this->isConflict ) {
965 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) .
966 "</h2>\n";
967 }
968
969 $parserOptions = ParserOptions::newFromUser( $wgUser );
970 $parserOptions->setEditSection( false );
971
972 # don't parse user css/js, show message about preview
973 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
974
975 if ( $this->isCssJsSubpage ) {
976 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
977 $previewtext = wfMsg('usercsspreview');
978 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
979 $previewtext = wfMsg('userjspreview');
980 }
981 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
982 $wgOut->addHTML( $parserOutput->mText );
983 wfProfileOut( $fname );
984 return $previewhead;
985 } else {
986 # if user want to see preview when he edit an article
987 if( $wgUser->getOption('previewonfirst') and ($this->textbox1 == '')) {
988 $this->textbox1 = $this->mArticle->getContent(true);
989 }
990
991 $toparse = $this->textbox1;
992
993 # If we're adding a comment, we need to show the
994 # summary as the headline
995 if($this->section=="new" && $this->summary!="") {
996 $toparse="== {$this->summary} ==\n\n".$toparse;
997 }
998
999 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1000
1001 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1002 $wgTitle, $parserOptions );
1003
1004 $previewHTML = $parserOutput->mText;
1005
1006 $wgOut->addCategoryLinks($parserOutput->getCategoryLinks());
1007 $wgOut->addLanguageLinks($parserOutput->getLanguageLinks());
1008
1009 wfProfileOut( $fname );
1010 return $previewhead . $previewHTML;
1011 }
1012 }
1013
1014 /**
1015 * @todo document
1016 */
1017 function blockedIPpage() {
1018 global $wgOut, $wgUser, $wgContLang;
1019
1020 $wgOut->setPageTitle( wfMsg( 'blockedtitle' ) );
1021 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1022 $wgOut->setArticleRelated( false );
1023
1024 $id = $wgUser->blockedBy();
1025 $reason = $wgUser->blockedFor();
1026 $ip = wfGetIP();
1027
1028 if ( is_numeric( $id ) ) {
1029 $name = User::whoIs( $id );
1030 } else {
1031 $name = $id;
1032 }
1033 $link = '[[' . $wgContLang->getNsText( NS_USER ) .
1034 ":{$name}|{$name}]]";
1035
1036 $wgOut->addWikiText( wfMsg( 'blockedtext', $link, $reason, $ip, $name ) );
1037 $wgOut->returnToMain( false );
1038 }
1039
1040 /**
1041 * @todo document
1042 */
1043 function userNotLoggedInPage() {
1044 global $wgOut;
1045
1046 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1047 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1048 $wgOut->setArticleRelated( false );
1049
1050 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
1051 $wgOut->returnToMain( false );
1052 }
1053
1054 /**
1055 * @todo document
1056 */
1057 function spamPage ( $match = false )
1058 {
1059 global $wgOut;
1060 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1061 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1062 $wgOut->setArticleRelated( false );
1063
1064 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1065 if ( $match ) {
1066 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1067 }
1068 $wgOut->returnToMain( false );
1069 }
1070
1071 /**
1072 * @access private
1073 * @todo document
1074 */
1075 function mergeChangesInto( &$editText ){
1076 $fname = 'EditPage::mergeChangesInto';
1077 wfProfileIn( $fname );
1078
1079 $db =& wfGetDB( DB_MASTER );
1080
1081 // This is the revision the editor started from
1082 $baseRevision = Revision::loadFromTimestamp(
1083 $db, $this->mArticle->mTitle, $this->edittime );
1084 if( is_null( $baseRevision ) ) {
1085 wfProfileOut( $fname );
1086 return false;
1087 }
1088 $baseText = $baseRevision->getText();
1089
1090 // The current state, we want to merge updates into it
1091 $currentRevision = Revision::loadFromTitle(
1092 $db, $this->mArticle->mTitle );
1093 if( is_null( $currentRevision ) ) {
1094 wfProfileOut( $fname );
1095 return false;
1096 }
1097 $currentText = $currentRevision->getText();
1098
1099 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1100 $editText = $result;
1101 wfProfileOut( $fname );
1102 return true;
1103 } else {
1104 wfProfileOut( $fname );
1105 return false;
1106 }
1107 }
1108
1109
1110 function checkUnicodeCompliantBrowser() {
1111 global $wgBrowserBlackList;
1112 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1113 foreach ( $wgBrowserBlackList as $browser ) {
1114 if ( preg_match($browser, $currentbrowser) ) {
1115 return false;
1116 }
1117 }
1118 return true;
1119 }
1120
1121 /**
1122 * Format an anchor fragment as it would appear for a given section name
1123 * @param string $text
1124 * @return string
1125 * @access private
1126 */
1127 function sectionAnchor( $text ) {
1128 $headline = Sanitizer::decodeCharReferences( $text );
1129 # strip out HTML
1130 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1131 $headline = trim( $headline );
1132 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1133 $replacearray = array(
1134 '%3A' => ':',
1135 '%' => '.'
1136 );
1137 return str_replace(
1138 array_keys( $replacearray ),
1139 array_values( $replacearray ),
1140 $sectionanchor );
1141 }
1142
1143 /**
1144 * Shows a bulletin board style toolbar for common editing functions.
1145 * It can be disabled in the user preferences.
1146 * The necessary JavaScript code can be found in style/wikibits.js.
1147 */
1148 function getEditToolbar() {
1149 global $wgStylePath, $wgLang, $wgMimeType, $wgJsMimeType;
1150
1151 /**
1152 * toolarray an array of arrays which each include the filename of
1153 * the button image (without path), the opening tag, the closing tag,
1154 * and optionally a sample text that is inserted between the two when no
1155 * selection is highlighted.
1156 * The tip text is shown when the user moves the mouse over the button.
1157 *
1158 * Already here are accesskeys (key), which are not used yet until someone
1159 * can figure out a way to make them work in IE. However, we should make
1160 * sure these keys are not defined on the edit page.
1161 */
1162 $toolarray=array(
1163 array( 'image'=>'button_bold.png',
1164 'open' => "\'\'\'",
1165 'close' => "\'\'\'",
1166 'sample'=> wfMsg('bold_sample'),
1167 'tip' => wfMsg('bold_tip'),
1168 'key' => 'B'
1169 ),
1170 array( 'image'=>'button_italic.png',
1171 'open' => "\'\'",
1172 'close' => "\'\'",
1173 'sample'=> wfMsg('italic_sample'),
1174 'tip' => wfMsg('italic_tip'),
1175 'key' => 'I'
1176 ),
1177 array( 'image'=>'button_link.png',
1178 'open' => '[[',
1179 'close' => ']]',
1180 'sample'=> wfMsg('link_sample'),
1181 'tip' => wfMsg('link_tip'),
1182 'key' => 'L'
1183 ),
1184 array( 'image'=>'button_extlink.png',
1185 'open' => '[',
1186 'close' => ']',
1187 'sample'=> wfMsg('extlink_sample'),
1188 'tip' => wfMsg('extlink_tip'),
1189 'key' => 'X'
1190 ),
1191 array( 'image'=>'button_headline.png',
1192 'open' => "\\n== ",
1193 'close' => " ==\\n",
1194 'sample'=> wfMsg('headline_sample'),
1195 'tip' => wfMsg('headline_tip'),
1196 'key' => 'H'
1197 ),
1198 array( 'image'=>'button_image.png',
1199 'open' => '[['.$wgLang->getNsText(NS_IMAGE).":",
1200 'close' => ']]',
1201 'sample'=> wfMsg('image_sample'),
1202 'tip' => wfMsg('image_tip'),
1203 'key' => 'D'
1204 ),
1205 array( 'image' =>'button_media.png',
1206 'open' => '[['.$wgLang->getNsText(NS_MEDIA).':',
1207 'close' => ']]',
1208 'sample'=> wfMsg('media_sample'),
1209 'tip' => wfMsg('media_tip'),
1210 'key' => 'M'
1211 ),
1212 array( 'image' =>'button_math.png',
1213 'open' => "\\<math\\>",
1214 'close' => "\\</math\\>",
1215 'sample'=> wfMsg('math_sample'),
1216 'tip' => wfMsg('math_tip'),
1217 'key' => 'C'
1218 ),
1219 array( 'image' =>'button_nowiki.png',
1220 'open' => "\\<nowiki\\>",
1221 'close' => "\\</nowiki\\>",
1222 'sample'=> wfMsg('nowiki_sample'),
1223 'tip' => wfMsg('nowiki_tip'),
1224 'key' => 'N'
1225 ),
1226 array( 'image' =>'button_sig.png',
1227 'open' => '--~~~~',
1228 'close' => '',
1229 'sample'=> '',
1230 'tip' => wfMsg('sig_tip'),
1231 'key' => 'Y'
1232 ),
1233 array( 'image' =>'button_hr.png',
1234 'open' => "\\n----\\n",
1235 'close' => '',
1236 'sample'=> '',
1237 'tip' => wfMsg('hr_tip'),
1238 'key' => 'R'
1239 )
1240 );
1241 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1242
1243 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1244 foreach($toolarray as $tool) {
1245
1246 $image=$wgStylePath.'/common/images/'.$tool['image'];
1247 $open=$tool['open'];
1248 $close=$tool['close'];
1249 $sample = wfEscapeJsString( $tool['sample'] );
1250
1251 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1252 // Older browsers show a "speedtip" type message only for ALT.
1253 // Ideally these should be different, realistically they
1254 // probably don't need to be.
1255 $tip = wfEscapeJsString( $tool['tip'] );
1256
1257 #$key = $tool["key"];
1258
1259 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1260 }
1261
1262 $toolbar.="document.writeln(\"</div>\");\n";
1263 $toolbar.="/*]]>*/\n</script>";
1264 return $toolbar;
1265 }
1266
1267 /**
1268 * Output preview text only. This can be sucked into the edit page
1269 * via JavaScript, and saves the server time rendering the skin as
1270 * well as theoretically being more robust on the client (doesn't
1271 * disturb the edit box's undo history, won't eat your text on
1272 * failure, etc).
1273 *
1274 * @todo This doesn't include category or interlanguage links.
1275 * Would need to enhance it a bit, maybe wrap them in XML
1276 * or something... that might also require more skin
1277 * initialization, so check whether that's a problem.
1278 */
1279 function livePreview() {
1280 global $wgOut;
1281 $wgOut->disable();
1282 header( 'Content-type: text/xml' );
1283 header( 'Cache-control: no-cache' );
1284 # FIXME
1285 echo $this->getPreviewText( false, false );
1286 }
1287
1288
1289 /**
1290 * Get a diff between the current contents of the edit box and the
1291 * version of the page we're editing from.
1292 *
1293 * If this is a section edit, we'll replace the section as for final
1294 * save and then make a comparison.
1295 *
1296 * @return string HTML
1297 */
1298 function getDiff() {
1299 require_once( 'DifferenceEngine.php' );
1300 $oldtext = $this->mArticle->fetchContent();
1301 $newtext = $this->mArticle->replaceSection(
1302 $this->section, $this->textbox1, $this->summary, $this->edittime );
1303 $oldtitle = wfMsg( 'currentrev' );
1304 $newtitle = wfMsg( 'yourtext' );
1305 if ( $oldtext != wfMsg( 'noarticletext' ) || $newtext != '' ) {
1306 $difftext = DifferenceEngine::getDiff( $oldtext, $newtext, $oldtitle, $newtitle );
1307 }
1308
1309 return '<div id="wikiDiff">' . $difftext . '</div>';
1310 }
1311
1312 /**
1313 * Filter an input field through a Unicode de-armoring process if it
1314 * came from an old browser with known broken Unicode editing issues.
1315 *
1316 * @param WebRequest $request
1317 * @param string $field
1318 * @return string
1319 * @access private
1320 */
1321 function safeUnicodeInput( $request, $field ) {
1322 $text = rtrim( $request->getText( $field ) );
1323 return $request->getBool( 'safemode' )
1324 ? $this->unmakesafe( $text )
1325 : $text;
1326 }
1327
1328 /**
1329 * Filter an output field through a Unicode armoring process if it is
1330 * going to an old browser with known broken Unicode editing issues.
1331 *
1332 * @param string $text
1333 * @return string
1334 * @access private
1335 */
1336 function safeUnicodeOutput( $text ) {
1337 global $wgContLang;
1338 $codedText = $wgContLang->recodeForEdit( $text );
1339 return $this->checkUnicodeCompliantBrowser()
1340 ? $codedText
1341 : $this->makesafe( $codedText );
1342 }
1343
1344 /**
1345 * A number of web browsers are known to corrupt non-ASCII characters
1346 * in a UTF-8 text editing environment. To protect against this,
1347 * detected browsers will be served an armored version of the text,
1348 * with non-ASCII chars converted to numeric HTML character references.
1349 *
1350 * Preexisting such character references will have a 0 added to them
1351 * to ensure that round-trips do not alter the original data.
1352 *
1353 * @param string $invalue
1354 * @return string
1355 * @access private
1356 */
1357 function makesafe( $invalue ) {
1358 // Armor existing references for reversability.
1359 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1360
1361 $bytesleft = 0;
1362 $result = "";
1363 $working = 0;
1364 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1365 $bytevalue = ord( $invalue{$i} );
1366 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1367 $result .= chr( $bytevalue );
1368 $bytesleft = 0;
1369 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1370 $working = $working << 6;
1371 $working += ($bytevalue & 0x3F);
1372 $bytesleft--;
1373 if( $bytesleft <= 0 ) {
1374 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1375 }
1376 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1377 $working = $bytevalue & 0x1F;
1378 $bytesleft = 1;
1379 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1380 $working = $bytevalue & 0x0F;
1381 $bytesleft = 2;
1382 } else { //1111 0xxx
1383 $working = $bytevalue & 0x07;
1384 $bytesleft = 3;
1385 }
1386 }
1387 return $result;
1388 }
1389
1390 /**
1391 * Reverse the previously applied transliteration of non-ASCII characters
1392 * back to UTF-8. Used to protect data from corruption by broken web browsers
1393 * as listed in $wgBrowserBlackList.
1394 *
1395 * @param string $invalue
1396 * @return string
1397 * @access private
1398 */
1399 function unmakesafe( $invalue ) {
1400 $result = "";
1401 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1402 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
1403 $i += 3;
1404 $hexstring = "";
1405 do {
1406 $hexstring .= $invalue{$i};
1407 $i++;
1408 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1409
1410 // Do some sanity checks. These aren't needed for reversability,
1411 // but should help keep the breakage down if the editor
1412 // breaks one of the entities whilst editing.
1413 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1414 $codepoint = hexdec($hexstring);
1415 $result .= codepointToUtf8( $codepoint );
1416 } else {
1417 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1418 }
1419 } else {
1420 $result .= substr( $invalue, $i, 1 );
1421 }
1422 }
1423 // reverse the transform that we made for reversability reasons.
1424 return strtr( $result, array( "&#x0" => "&#x" ) );
1425 }
1426
1427
1428 }
1429
1430 ?>