Code cleanup: normalize case of wfMsg() calls, clean up an old str_replace
[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 $metadata = $this->mMetaData ;
738 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
739 $helppage = Title::newFromText( wfMsg( "metadata_page" ) ) ;
740 $top = wfMsg( 'metadata', $helppage->getInternalURL() );
741 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
742 }
743 else $metadata = "" ;
744
745 $hidden = '';
746 $recreate = '';
747 if ($confirmdelete) {
748 if ( 'save' != $formtype ) {
749 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
750 } else {
751 // Hide the toolbar and edit area, use can click preview to get it back
752 // Add an confirmation checkbox and explanation.
753 $toolbar = '';
754 $hidden = 'type="hidden" style="display:none;"';
755 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $query->user_name , $query->log_comment ));
756 $recreate .=
757 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
758 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
759 }
760 }
761
762 $safemodehtml = $this->checkUnicodeCompliantBrowser()
763 ? ""
764 : "<input type='hidden' name=\"safemode\" value='1' />\n";
765
766 $wgOut->addHTML( <<<END
767 {$toolbar}
768 <form id="editform" name="editform" method="post" action="$action"
769 enctype="multipart/form-data">
770 $recreate
771 {$commentsubject}
772 <textarea tabindex='1' accesskey="," name="wpTextbox1" rows='{$rows}'
773 cols='{$cols}'{$ew} $hidden>
774 END
775 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
776 "
777 </textarea>
778 {$metadata}
779 <br />{$editsummary}
780 {$checkboxhtml}
781 {$safemodehtml}
782 <input tabindex='5' id='wpSave' type='submit' value=\"{$save}\" name=\"wpSave\" accesskey=\"".wfMsg('accesskey-save')."\"".
783 " title=\"".wfMsg('tooltip-save')."\"/>
784 <input tabindex='6' id='wpPreview' type='submit' $liveOnclick value=\"{$prev}\" name=\"wpPreview\" accesskey=\"".wfMsg('accesskey-preview')."\"".
785 " title=\"".wfMsg('tooltip-preview')."\"/>
786 <input tabindex='7' id='wpDiff' type='submit' value=\"{$diff}\" name=\"wpDiff\" accesskey=\"".wfMsg('accesskey-diff')."\"".
787 " title=\"".wfMsg('tooltip-diff')."\"/>
788 <em>{$cancel}</em> | <em>{$edithelp}</em>{$templates}" );
789 $wgOut->addWikiText( $copywarn );
790 $wgOut->addHTML( "
791 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
792 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
793 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n" );
794
795 if ( $wgUser->isLoggedIn() ) {
796 /**
797 * To make it harder for someone to slip a user a page
798 * which submits an edit form to the wiki without their
799 * knowledge, a random token is associated with the login
800 * session. If it's not passed back with the submission,
801 * we won't save the page, or render user JavaScript and
802 * CSS previews.
803 */
804 $token = htmlspecialchars( $wgUser->editToken() );
805 $wgOut->addHTML( "
806 <input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
807 }
808
809
810 if ( $isConflict ) {
811 require_once( "DifferenceEngine.php" );
812 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
813 DifferenceEngine::showDiff( $this->textbox2, $this->textbox1,
814 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
815
816 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
817 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
818 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) .
819 "
820 </textarea>" );
821 }
822 $wgOut->addHTML( "</form>\n" );
823 if ( $formtype == 'preview' && !$wgUser->getOption( 'previewontop' ) ) {
824 $wgOut->addHTML( '<div id="wikiPreview">' . $previewOutput . '</div>' );
825 }
826 if ( $formtype == 'diff' && !$wgUser->getOption( 'previewontop' ) ) {
827 #$wgOut->addHTML( '<div id="wikiPreview">' . $difftext . '</div>' );
828 $wgOut->addHTML( $this->getDiff() );
829 }
830 }
831
832 function getLastDelete() {
833 $dbr =& wfGetDB( DB_SLAVE );
834 $fname = 'EditPage::getLastDelete';
835 $res = $dbr->select(
836 array( 'logging', 'user' ),
837 array( 'log_type',
838 'log_action',
839 'log_timestamp',
840 'log_user',
841 'log_namespace',
842 'log_title',
843 'log_comment',
844 'log_params',
845 'user_name', ),
846 array( 'log_namespace="' . $this->mTitle->getNamespace() . '"',
847 'log_title="' . $this->mTitle->getDBkey() . '"',
848 'log_type="delete"',
849 'log_action="delete"',
850 'user_id=log_user' ),
851 $fname,
852 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
853
854 if($dbr->numRows($res) == 1) {
855 while ( $x = $dbr->fetchObject ( $res ) )
856 $data = $x;
857 $dbr->freeResult ( $res ) ;
858 } else {
859 $data = null;
860 }
861 return $data;
862 }
863
864 /**
865 * @todo document
866 */
867 function getPreviewText( $isConflict, $isCssJsSubpage ) {
868 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgAllowDiffPreview, $wgEnableDiffPreviewPreference;
869 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
870 "<p class='previewnote'>" . htmlspecialchars( wfMsg( 'previewnote' ) ) . "</p>\n";
871 if ( $isConflict ) {
872 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) .
873 "</h2>\n";
874 }
875
876 $parserOptions = ParserOptions::newFromUser( $wgUser );
877 $parserOptions->setEditSection( false );
878
879 # don't parse user css/js, show message about preview
880 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
881
882 if ( $isCssJsSubpage ) {
883 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
884 $previewtext = wfMsg('usercsspreview');
885 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
886 $previewtext = wfMsg('userjspreview');
887 }
888 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
889 $wgOut->addHTML( $parserOutput->mText );
890 return $previewhead;
891 } else {
892 # if user want to see preview when he edit an article
893 if( $wgUser->getOption('previewonfirst') and ($this->textbox1 == '')) {
894 $this->textbox1 = $this->mArticle->getContent(true);
895 }
896
897 $toparse = $this->textbox1;
898
899 # If we're adding a comment, we need to show the
900 # summary as the headline
901 if($this->section=="new" && $this->summary!="") {
902 $toparse="== {$this->summary} ==\n\n".$toparse;
903 }
904
905 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
906
907 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
908 $wgTitle, $parserOptions );
909
910 $previewHTML = $parserOutput->mText;
911
912 $wgOut->addCategoryLinks($parserOutput->getCategoryLinks());
913 $wgOut->addLanguageLinks($parserOutput->getLanguageLinks());
914 return $previewhead . $previewHTML;
915 }
916 }
917
918 /**
919 * @todo document
920 */
921 function blockedIPpage() {
922 global $wgOut, $wgUser, $wgContLang, $wgIP;
923
924 $wgOut->setPageTitle( wfMsg( 'blockedtitle' ) );
925 $wgOut->setRobotpolicy( 'noindex,nofollow' );
926 $wgOut->setArticleRelated( false );
927
928 $id = $wgUser->blockedBy();
929 $reason = $wgUser->blockedFor();
930 $ip = $wgIP;
931
932 if ( is_numeric( $id ) ) {
933 $name = User::whoIs( $id );
934 } else {
935 $name = $id;
936 }
937 $link = '[[' . $wgContLang->getNsText( NS_USER ) .
938 ":{$name}|{$name}]]";
939
940 $wgOut->addWikiText( wfMsg( 'blockedtext', $link, $reason, $ip, $name ) );
941 $wgOut->returnToMain( false );
942 }
943
944 /**
945 * @todo document
946 */
947 function userNotLoggedInPage() {
948 global $wgOut;
949
950 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
951 $wgOut->setRobotpolicy( 'noindex,nofollow' );
952 $wgOut->setArticleRelated( false );
953
954 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
955 $wgOut->returnToMain( false );
956 }
957
958 /**
959 * @todo document
960 */
961 function spamPage ( $match = false )
962 {
963 global $wgOut;
964 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
965 $wgOut->setRobotpolicy( 'noindex,nofollow' );
966 $wgOut->setArticleRelated( false );
967
968 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
969 if ( $match ) {
970 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
971 }
972 $wgOut->returnToMain( false );
973 }
974
975 /**
976 * Forks processes to scan the originating IP for an open proxy server
977 * MemCached can be used to skip IPs that have already been scanned
978 */
979 function proxyCheck() {
980 global $wgBlockOpenProxies, $wgProxyPorts, $wgProxyScriptPath;
981 global $wgIP, $wgUseMemCached, $wgMemc, $wgDBname, $wgProxyMemcExpiry;
982
983 if ( !$wgBlockOpenProxies ) {
984 return;
985 }
986
987 # Get MemCached key
988 $skip = false;
989 if ( $wgUseMemCached ) {
990 $mcKey = $wgDBname.':proxy:ip:'.$wgIP;
991 $mcValue = $wgMemc->get( $mcKey );
992 if ( $mcValue ) {
993 $skip = true;
994 }
995 }
996
997 # Fork the processes
998 if ( !$skip ) {
999 $title = Title::makeTitle( NS_SPECIAL, 'Blockme' );
1000 $iphash = md5( $wgIP . $wgProxyKey );
1001 $url = $title->getFullURL( 'ip='.$iphash );
1002
1003 foreach ( $wgProxyPorts as $port ) {
1004 $params = implode( ' ', array(
1005 escapeshellarg( $wgProxyScriptPath ),
1006 escapeshellarg( $wgIP ),
1007 escapeshellarg( $port ),
1008 escapeshellarg( $url )
1009 ));
1010 exec( "php $params &>/dev/null &" );
1011 }
1012 # Set MemCached key
1013 if ( $wgUseMemCached ) {
1014 $wgMemc->set( $mcKey, 1, $wgProxyMemcExpiry );
1015 }
1016 }
1017 }
1018
1019 /**
1020 * @access private
1021 * @todo document
1022 */
1023 function mergeChangesInto( &$editText ){
1024 $fname = 'EditPage::mergeChangesInto';
1025 wfProfileIn( $fname );
1026
1027 $db =& wfGetDB( DB_MASTER );
1028
1029 // This is the revision the editor started from
1030 $baseRevision = Revision::loadFromTimestamp(
1031 $db, $this->mArticle->mTitle, $this->edittime );
1032 if( is_null( $baseRevision ) ) {
1033 wfProfileOut( $fname );
1034 return false;
1035 }
1036 $baseText = $baseRevision->getText();
1037
1038 // The current state, we want to merge updates into it
1039 $currentRevision = Revision::loadFromTitle(
1040 $db, $this->mArticle->mTitle );
1041 if( is_null( $currentRevision ) ) {
1042 wfProfileOut( $fname );
1043 return false;
1044 }
1045 $currentText = $currentRevision->getText();
1046
1047 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1048 $editText = $result;
1049 wfProfileOut( $fname );
1050 return true;
1051 } else {
1052 wfProfileOut( $fname );
1053 return false;
1054 }
1055 }
1056
1057
1058 function checkUnicodeCompliantBrowser() {
1059 global $wgBrowserBlackList;
1060 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1061 foreach ( $wgBrowserBlackList as $browser ) {
1062 if ( preg_match($browser, $currentbrowser) ) {
1063 return false;
1064 }
1065 }
1066 return true;
1067 }
1068
1069 /**
1070 * Format an anchor fragment as it would appear for a given section name
1071 * @param string $text
1072 * @return string
1073 * @access private
1074 */
1075 function sectionAnchor( $text ) {
1076 $headline = Sanitizer::decodeCharReferences( $text );
1077 # strip out HTML
1078 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1079 $headline = trim( $headline );
1080 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1081 $replacearray = array(
1082 '%3A' => ':',
1083 '%' => '.'
1084 );
1085 return str_replace(
1086 array_keys( $replacearray ),
1087 array_values( $replacearray ),
1088 $sectionanchor );
1089 }
1090
1091 /**
1092 * Shows a bulletin board style toolbar for common editing functions.
1093 * It can be disabled in the user preferences.
1094 * The necessary JavaScript code can be found in style/wikibits.js.
1095 */
1096 function getEditToolbar() {
1097 global $wgStylePath, $wgLang, $wgMimeType, $wgJsMimeType;
1098
1099 /**
1100 * toolarray an array of arrays which each include the filename of
1101 * the button image (without path), the opening tag, the closing tag,
1102 * and optionally a sample text that is inserted between the two when no
1103 * selection is highlighted.
1104 * The tip text is shown when the user moves the mouse over the button.
1105 *
1106 * Already here are accesskeys (key), which are not used yet until someone
1107 * can figure out a way to make them work in IE. However, we should make
1108 * sure these keys are not defined on the edit page.
1109 */
1110 $toolarray=array(
1111 array( 'image'=>'button_bold.png',
1112 'open' => "\'\'\'",
1113 'close' => "\'\'\'",
1114 'sample'=> wfMsg('bold_sample'),
1115 'tip' => wfMsg('bold_tip'),
1116 'key' => 'B'
1117 ),
1118 array( 'image'=>'button_italic.png',
1119 'open' => "\'\'",
1120 'close' => "\'\'",
1121 'sample'=> wfMsg('italic_sample'),
1122 'tip' => wfMsg('italic_tip'),
1123 'key' => 'I'
1124 ),
1125 array( 'image'=>'button_link.png',
1126 'open' => '[[',
1127 'close' => ']]',
1128 'sample'=> wfMsg('link_sample'),
1129 'tip' => wfMsg('link_tip'),
1130 'key' => 'L'
1131 ),
1132 array( 'image'=>'button_extlink.png',
1133 'open' => '[',
1134 'close' => ']',
1135 'sample'=> wfMsg('extlink_sample'),
1136 'tip' => wfMsg('extlink_tip'),
1137 'key' => 'X'
1138 ),
1139 array( 'image'=>'button_headline.png',
1140 'open' => "\\n== ",
1141 'close' => " ==\\n",
1142 'sample'=> wfMsg('headline_sample'),
1143 'tip' => wfMsg('headline_tip'),
1144 'key' => 'H'
1145 ),
1146 array( 'image'=>'button_image.png',
1147 'open' => '[['.$wgLang->getNsText(NS_IMAGE).":",
1148 'close' => ']]',
1149 'sample'=> wfMsg('image_sample'),
1150 'tip' => wfMsg('image_tip'),
1151 'key' => 'D'
1152 ),
1153 array( 'image' =>'button_media.png',
1154 'open' => '[['.$wgLang->getNsText(NS_MEDIA).':',
1155 'close' => ']]',
1156 'sample'=> wfMsg('media_sample'),
1157 'tip' => wfMsg('media_tip'),
1158 'key' => 'M'
1159 ),
1160 array( 'image' =>'button_math.png',
1161 'open' => "\\<math\\>",
1162 'close' => "\\</math\\>",
1163 'sample'=> wfMsg('math_sample'),
1164 'tip' => wfMsg('math_tip'),
1165 'key' => 'C'
1166 ),
1167 array( 'image' =>'button_nowiki.png',
1168 'open' => "\\<nowiki\\>",
1169 'close' => "\\</nowiki\\>",
1170 'sample'=> wfMsg('nowiki_sample'),
1171 'tip' => wfMsg('nowiki_tip'),
1172 'key' => 'N'
1173 ),
1174 array( 'image' =>'button_sig.png',
1175 'open' => '--~~~~',
1176 'close' => '',
1177 'sample'=> '',
1178 'tip' => wfMsg('sig_tip'),
1179 'key' => 'Y'
1180 ),
1181 array( 'image' =>'button_hr.png',
1182 'open' => "\\n----\\n",
1183 'close' => '',
1184 'sample'=> '',
1185 'tip' => wfMsg('hr_tip'),
1186 'key' => 'R'
1187 )
1188 );
1189 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1190
1191 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1192 foreach($toolarray as $tool) {
1193
1194 $image=$wgStylePath.'/common/images/'.$tool['image'];
1195 $open=$tool['open'];
1196 $close=$tool['close'];
1197 $sample = wfEscapeJsString( $tool['sample'] );
1198
1199 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1200 // Older browsers show a "speedtip" type message only for ALT.
1201 // Ideally these should be different, realistically they
1202 // probably don't need to be.
1203 $tip = wfEscapeJsString( $tool['tip'] );
1204
1205 #$key = $tool["key"];
1206
1207 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1208 }
1209
1210 $toolbar.="addInfobox('" . wfEscapeJsString( wfMsg( "infobox" ) ) .
1211 "','" . wfEscapeJsString( wfMsg( "infobox_alert" ) ) . "');\n";
1212 $toolbar.="document.writeln(\"</div>\");\n";
1213
1214 $toolbar.="/*]]>*/\n</script>";
1215 return $toolbar;
1216 }
1217
1218 /**
1219 * Output preview text only. This can be sucked into the edit page
1220 * via JavaScript, and saves the server time rendering the skin as
1221 * well as theoretically being more robust on the client (doesn't
1222 * disturb the edit box's undo history, won't eat your text on
1223 * failure, etc).
1224 *
1225 * @todo This doesn't include category or interlanguage links.
1226 * Would need to enhance it a bit, maybe wrap them in XML
1227 * or something... that might also require more skin
1228 * initialization, so check whether that's a problem.
1229 */
1230 function livePreview() {
1231 global $wgOut;
1232 $wgOut->disable();
1233 header( 'Content-type: text/xml' );
1234 header( 'Cache-control: no-cache' );
1235 # FIXME
1236 echo $this->getPreviewText( false, false );
1237 }
1238
1239
1240 /**
1241 * Get a diff between the current contents of the edit box and the
1242 * version of the page we're editing from.
1243 *
1244 * If this is a section edit, we'll replace the section as for final
1245 * save and then make a comparison.
1246 *
1247 * @return string HTML
1248 */
1249 function getDiff() {
1250 require_once( 'DifferenceEngine.php' );
1251 $oldtext = $this->mArticle->fetchContent();
1252 $newtext = $this->mArticle->getTextOfLastEditWithSectionReplacedOrAdded(
1253 $this->section, $this->textbox1, $this->summary, $this->edittime );
1254 $oldtitle = wfMsg( 'currentrev' );
1255 $newtitle = wfMsg( 'yourtext' );
1256 if ( $oldtext != wfMsg( 'noarticletext' ) || $newtext != '' ) {
1257 $difftext = DifferenceEngine::getDiff( $oldtext, $newtext, $oldtitle, $newtitle );
1258 }
1259
1260 return '<div id="wikiDiff">' . $difftext . '</div>';
1261 }
1262
1263 /**
1264 * Filter an input field through a Unicode de-armoring process if it
1265 * came from an old browser with known broken Unicode editing issues.
1266 *
1267 * @param WebRequest $request
1268 * @param string $field
1269 * @return string
1270 * @access private
1271 */
1272 function safeUnicodeInput( $request, $field ) {
1273 $text = rtrim( $request->getText( $field ) );
1274 return $request->getBool( 'safemode' )
1275 ? $this->unmakesafe( $text )
1276 : $text;
1277 }
1278
1279 /**
1280 * Filter an output field through a Unicode armoring process if it is
1281 * going to an old browser with known broken Unicode editing issues.
1282 *
1283 * @param string $text
1284 * @return string
1285 * @access private
1286 */
1287 function safeUnicodeOutput( $text ) {
1288 global $wgContLang;
1289 $codedText = $wgContLang->recodeForEdit( $text );
1290 return $this->checkUnicodeCompliantBrowser()
1291 ? $codedText
1292 : $this->makesafe( $codedText );
1293 }
1294
1295 /**
1296 * A number of web browsers are known to corrupt non-ASCII characters
1297 * in a UTF-8 text editing environment. To protect against this,
1298 * detected browsers will be served an armored version of the text,
1299 * with non-ASCII chars converted to numeric HTML character references.
1300 *
1301 * Preexisting such character references will have a 0 added to them
1302 * to ensure that round-trips do not alter the original data.
1303 *
1304 * @param string $invalue
1305 * @return string
1306 * @access private
1307 */
1308 function makesafe( $invalue ) {
1309 // Armor existing references for reversability.
1310 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1311
1312 $bytesleft = 0;
1313 $result = "";
1314 $working = 0;
1315 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1316 $bytevalue = ord( $invalue{$i} );
1317 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1318 $result .= chr( $bytevalue );
1319 $bytesleft = 0;
1320 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1321 $working = $working << 6;
1322 $working += ($bytevalue & 0x3F);
1323 $bytesleft--;
1324 if( $bytesleft <= 0 ) {
1325 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1326 }
1327 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1328 $working = $bytevalue & 0x1F;
1329 $bytesleft = 1;
1330 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1331 $working = $bytevalue & 0x0F;
1332 $bytesleft = 2;
1333 } else { //1111 0xxx
1334 $working = $bytevalue & 0x07;
1335 $bytesleft = 3;
1336 }
1337 }
1338 return $result;
1339 }
1340
1341 /**
1342 * Reverse the previously applied transliteration of non-ASCII characters
1343 * back to UTF-8. Used to protect data from corruption by broken web browsers
1344 * as listed in $wgBrowserBlackList.
1345 *
1346 * @param string $invalue
1347 * @return string
1348 * @access private
1349 */
1350 function unmakesafe( $invalue ) {
1351 $result = "";
1352 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1353 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
1354 $i += 3;
1355 $hexstring = "";
1356 do {
1357 $hexstring .= $invalue{$i};
1358 $i++;
1359 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1360
1361 // Do some sanity checks. These aren't needed for reversability,
1362 // but should help keep the breakage down if the editor
1363 // breaks one of the entities whilst editing.
1364 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1365 $codepoint = hexdec($hexstring);
1366 $result .= codepointToUtf8( $codepoint );
1367 } else {
1368 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1369 }
1370 } else {
1371 $result .= substr( $invalue, $i, 1 );
1372 }
1373 }
1374 // reverse the transform that we made for reversability reasons.
1375 return strtr( $result, array( "&#x0" => "&#x" ) );
1376 }
1377
1378
1379 }
1380
1381 ?>