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