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