removed some debugging statements, I think they were all added by kate in the oracle...
[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 if( ( $this->section != 'new' ) &&
444 ($this->mArticle->getTimestamp() != $this->edittime ) ) {
445 $isConflict = true;
446 }
447 $userid = $wgUser->getID();
448
449 if ( $isConflict) {
450 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
451 $this->mArticle->getTimestamp() . "'\n" );
452 $text = $this->mArticle->getTextOfLastEditWithSectionReplacedOrAdded(
453 $this->section, $this->textbox1, $this->summary, $this->edittime);
454 }
455 else {
456 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
457 $text = $this->mArticle->getTextOfLastEditWithSectionReplacedOrAdded(
458 $this->section, $this->textbox1, $this->summary);
459 }
460 # Suppress edit conflict with self
461
462 if ( ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
463 wfDebug( "Suppressing edit conflict, same user.\n" );
464 $isConflict = false;
465 } else {
466 # switch from section editing to normal editing in edit conflict
467 if($isConflict) {
468 # Attempt merge
469 if( $this->mergeChangesInto( $text ) ){
470 // Successful merge! Maybe we should tell the user the good news?
471 $isConflict = false;
472 wfDebug( "Suppressing edit conflict, successful merge.\n" );
473 } else {
474 $this->section = '';
475 $this->textbox1 = $text;
476 wfDebug( "Keeping edit conflict, failed merge.\n" );
477 }
478 }
479 }
480 if ( ! $isConflict ) {
481 # All's well
482 $sectionanchor = '';
483 if( $this->section == 'new' ) {
484 if( $this->summary != '' ) {
485 $sectionanchor = $this->sectionAnchor( $this->summary );
486 }
487 } elseif( $this->section != '' ) {
488 # Try to get a section anchor from the section source, redirect to edited section if header found
489 # XXX: might be better to integrate this into Article::getTextOfLastEditWithSectionReplacedOrAdded
490 # for duplicate heading checking and maybe parsing
491 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
492 # we can't deal with anchors, includes, html etc in the header for now,
493 # headline would need to be parsed to improve this
494 #if($hasmatch and strlen($matches[2]) > 0 and !preg_match( "/[\\['{<>]/", $matches[2])) {
495 if($hasmatch and strlen($matches[2]) > 0) {
496 $sectionanchor = $this->sectionAnchor( $matches[2] );
497 }
498 }
499
500 // Save errors may fall down to the edit form, but we've now
501 // merged the section into full text. Clear the section field
502 // so that later submission of conflict forms won't try to
503 // replace that into a duplicated mess.
504 $this->textbox1 = $text;
505 $this->section = '';
506
507 if (wfRunHooks('ArticleSave', array(&$this->mArticle, &$wgUser, &$text,
508 &$this->summary, &$this->minoredit,
509 &$this->watchthis, &$sectionanchor)))
510 {
511 # update the article here
512 if($this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
513 $this->watchthis, '', $sectionanchor ))
514 {
515 wfRunHooks('ArticleSaveComplete',
516 array(&$this->mArticle, &$wgUser, $text,
517 $this->summary, $this->minoredit,
518 $this->watchthis, $sectionanchor));
519 return;
520 } else {
521 $isConflict = true;
522 }
523 }
524 }
525 }
526 }
527 # First time through: get contents, set time for conflict
528 # checking, etc.
529
530 if ( 'initial' == $formtype || $firsttime ) {
531 $this->edittime = $this->mArticle->getTimestamp();
532 $this->textbox1 = $this->mArticle->getContent( true );
533 $this->summary = '';
534 $this->proxyCheck();
535 }
536 $wgOut->setRobotpolicy( 'noindex,nofollow' );
537
538 # Enabled article-related sidebar, toplinks, etc.
539 $wgOut->setArticleRelated( true );
540
541 if ( $isConflict ) {
542 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
543 $wgOut->setPageTitle( $s );
544 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
545
546 $this->textbox2 = $this->textbox1;
547 $this->textbox1 = $this->mArticle->getContent( true );
548 $this->edittime = $this->mArticle->getTimestamp();
549 } else {
550
551 if( $this->section != '' ) {
552 if( $this->section == 'new' ) {
553 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
554 } else {
555 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
556 if( !$this->preview && !$this->diff ) {
557 preg_match( "/^(=+)(.+)\\1/mi",
558 $this->textbox1,
559 $matches );
560 if( !empty( $matches[2] ) ) {
561 $this->summary = "/* ". trim($matches[2])." */ ";
562 }
563 }
564 }
565 } else {
566 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
567 }
568 $wgOut->setPageTitle( $s );
569 if ( !$this->checkUnicodeCompliantBrowser() ) {
570 $this->mArticle->setOldSubtitle();
571 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
572 }
573 if ( isset( $this->mArticle )
574 && isset( $this->mArticle->mRevision )
575 && !$this->mArticle->mRevision->isCurrent() ) {
576 $this->mArticle->setOldSubtitle();
577 $wgOut->addWikiText( wfMsg( 'editingold' ) );
578 }
579 }
580
581 if( wfReadOnly() ) {
582 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
583 } else if ( $isCssJsSubpage and 'preview' != $formtype) {
584 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ));
585 }
586 if( $this->mTitle->isProtected('edit') ) {
587 $wgOut->addWikiText( wfMsg( 'protectedpagewarning' ) );
588 }
589
590 $kblength = (int)(strlen( $this->textbox1 ) / 1024);
591 if( $kblength > 29 ) {
592 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $kblength ) ) );
593 }
594
595 $rows = $wgUser->getOption( 'rows' );
596 $cols = $wgUser->getOption( 'cols' );
597
598 $ew = $wgUser->getOption( 'editwidth' );
599 if ( $ew ) $ew = " style=\"width:100%\"";
600 else $ew = '';
601
602 $q = 'action=submit';
603 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
604 $action = $this->mTitle->escapeLocalURL( $q );
605
606 $summary = wfMsg('summary');
607 $subject = wfMsg('subject');
608 $minor = wfMsg('minoredit');
609 $watchthis = wfMsg ('watchthis');
610 $save = wfMsg('savearticle');
611 $prev = wfMsg('showpreview');
612 $diff = wfMsg('showdiff');
613
614 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
615 wfMsg('cancel') );
616 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsg( 'edithelppage' ));
617 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
618 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
619 htmlspecialchars( wfMsg( 'newwindow' ) );
620
621 global $wgRightsText;
622 $copywarn = "<div id=\"editpage-copywarn\">\n" .
623 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
624 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
625 $wgRightsText ) . "\n</div>";
626
627 if( $wgUser->getOption('showtoolbar') and !$isCssJsSubpage ) {
628 # prepare toolbar for edit buttons
629 $toolbar = $this->getEditToolbar();
630 } else {
631 $toolbar = '';
632 }
633
634 // activate checkboxes if user wants them to be always active
635 if( !$this->preview && !$this->diff ) {
636 if( $wgUser->getOption( 'watchdefault' ) ) $this->watchthis = true;
637 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
638
639 // activate checkbox also if user is already watching the page,
640 // require wpWatchthis to be unset so that second condition is not
641 // checked unnecessarily
642 if( !$this->watchthis && $this->mTitle->userIsWatching() ) $this->watchthis = true;
643 }
644
645 $minoredithtml = '';
646
647 if ( $wgUser->isLoggedIn() || $wgAllowAnonymousMinor ) {
648 $minoredithtml =
649 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
650 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
651 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
652 }
653
654 $watchhtml = '';
655
656 if ( $wgUser->isLoggedIn() ) {
657 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
658 ($this->watchthis?" checked='checked'":"").
659 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />".
660 "<label for='wpWatchthis' title=\"" .
661 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>";
662 }
663
664 $checkboxhtml = $minoredithtml . $watchhtml . '<br />';
665
666 $wgOut->addHTML( '<div id="wikiPreview">' );
667 if ( 'preview' == $formtype) {
668 $previewOutput = $this->getPreviewText( $isConflict, $isCssJsSubpage );
669 if ( $wgUser->getOption('previewontop' ) ) {
670 $wgOut->addHTML( $previewOutput );
671 if($this->mTitle->getNamespace() == NS_CATEGORY) {
672 $this->mArticle->closeShowCategory();
673 }
674 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
675 }
676 }
677 $wgOut->addHTML( '</div>' );
678 if ( 'diff' == $formtype ) {
679 if ( $wgUser->getOption('previewontop' ) ) {
680 $wgOut->addHTML( $this->getDiff() );
681 }
682 }
683
684
685 # if this is a comment, show a subject line at the top, which is also the edit summary.
686 # Otherwise, show a summary field at the bottom
687 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
688 if( $this->section == 'new' ) {
689 $commentsubject="{$subject}: <input tabindex='1' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
690 $editsummary = '';
691 } else {
692 $commentsubject = '';
693 $editsummary="{$summary}: <input tabindex='2' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
694 }
695
696 if( !$this->preview && !$this->diff ) {
697 # Don't select the edit box on preview; this interferes with seeing what's going on.
698 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
699 }
700 # Prepare a list of templates used by this page
701 $templates = '';
702 $articleTemplates = $this->mArticle->getUsedTemplates();
703 if ( count( $articleTemplates ) > 0 ) {
704 $templates = '<br />'. wfMsg( 'templatesused' ) . '<ul>';
705 foreach ( $articleTemplates as $tpl ) {
706 if ( $titleObj = Title::makeTitle( NS_TEMPLATE, $tpl ) ) {
707 $templates .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
708 }
709 }
710 $templates .= '</ul>';
711 }
712
713 global $wgLivePreview, $wgStylePath;
714 /**
715 * Live Preview lets us fetch rendered preview page content and
716 * add it to the page without refreshing the whole page.
717 * Set up the button for it; if not supported by the browser
718 * it will fall through to the normal form submission method.
719 */
720 if( $wgLivePreview ) {
721 global $wgJsMimeType;
722 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
723 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
724 '"></script>' . "\n" );
725 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
726 $liveOnclick = 'onclick="return !livePreview('.
727 'getElementById(\'wikiPreview\'),' .
728 'editform.wpTextbox1.value,' .
729 htmlspecialchars( '"' . $liveAction . '"' ) . ')"';
730 } else {
731 $liveOnclick = '';
732 }
733
734 global $wgUseMetadataEdit ;
735 if ( $wgUseMetadataEdit ) {
736 $metadata = $this->mMetaData ;
737 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
738 $helppage = Title::newFromText( wfMsg( "metadata_page" ) ) ;
739 $top = wfMsg( 'metadata', $helppage->getInternalURL() );
740 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
741 }
742 else $metadata = "" ;
743
744 $hidden = '';
745 $recreate = '';
746 if ($confirmdelete) {
747 if ( 'save' != $formtype ) {
748 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
749 } else {
750 // Hide the toolbar and edit area, use can click preview to get it back
751 // Add an confirmation checkbox and explanation.
752 $toolbar = '';
753 $hidden = 'type="hidden" style="display:none;"';
754 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $query->user_name , $query->log_comment ));
755 $recreate .=
756 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
757 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
758 }
759 }
760
761 $safemodehtml = $this->checkUnicodeCompliantBrowser()
762 ? ""
763 : "<input type='hidden' name=\"safemode\" value='1' />\n";
764
765 $wgOut->addHTML( <<<END
766 {$toolbar}
767 <form id="editform" name="editform" method="post" action="$action"
768 enctype="multipart/form-data">
769 $recreate
770 {$commentsubject}
771 <textarea tabindex='1' accesskey="," name="wpTextbox1" rows='{$rows}'
772 cols='{$cols}'{$ew} $hidden>
773 END
774 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
775 "
776 </textarea>
777 {$metadata}
778 <br />{$editsummary}
779 {$checkboxhtml}
780 {$safemodehtml}
781 <input tabindex='5' id='wpSave' type='submit' value=\"{$save}\" name=\"wpSave\" accesskey=\"".wfMsg('accesskey-save')."\"".
782 " title=\"".wfMsg('tooltip-save')."\"/>
783 <input tabindex='6' id='wpPreview' type='submit' $liveOnclick value=\"{$prev}\" name=\"wpPreview\" accesskey=\"".wfMsg('accesskey-preview')."\"".
784 " title=\"".wfMsg('tooltip-preview')."\"/>
785 <input tabindex='7' id='wpDiff' type='submit' value=\"{$diff}\" name=\"wpDiff\" accesskey=\"".wfMsg('accesskey-diff')."\"".
786 " title=\"".wfMsg('tooltip-diff')."\"/>
787 <em>{$cancel}</em> | <em>{$edithelp}</em>{$templates}" );
788 $wgOut->addWikiText( $copywarn );
789 $wgOut->addHTML( "
790 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
791 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
792 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n" );
793
794 if ( $wgUser->isLoggedIn() ) {
795 /**
796 * To make it harder for someone to slip a user a page
797 * which submits an edit form to the wiki without their
798 * knowledge, a random token is associated with the login
799 * session. If it's not passed back with the submission,
800 * we won't save the page, or render user JavaScript and
801 * CSS previews.
802 */
803 $token = htmlspecialchars( $wgUser->editToken() );
804 $wgOut->addHTML( "
805 <input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
806 }
807
808
809 if ( $isConflict ) {
810 require_once( "DifferenceEngine.php" );
811 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
812 DifferenceEngine::showDiff( $this->textbox2, $this->textbox1,
813 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
814
815 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
816 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
817 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) .
818 "
819 </textarea>" );
820 }
821 $wgOut->addHTML( "</form>\n" );
822 if ( $formtype == 'preview' && !$wgUser->getOption( 'previewontop' ) ) {
823 $wgOut->addHTML( '<div id="wikiPreview">' . $previewOutput . '</div>' );
824 }
825 if ( $formtype == 'diff' && !$wgUser->getOption( 'previewontop' ) ) {
826 #$wgOut->addHTML( '<div id="wikiPreview">' . $difftext . '</div>' );
827 $wgOut->addHTML( $this->getDiff() );
828 }
829 }
830
831 function getLastDelete() {
832 $dbr =& wfGetDB( DB_SLAVE );
833 $fname = 'EditPage::getLastDelete';
834 $res = $dbr->select(
835 array( 'logging', 'user' ),
836 array( 'log_type',
837 'log_action',
838 'log_timestamp',
839 'log_user',
840 'log_namespace',
841 'log_title',
842 'log_comment',
843 'log_params',
844 'user_name', ),
845 array( 'log_namespace="' . $this->mTitle->getNamespace() . '"',
846 'log_title="' . $this->mTitle->getDBkey() . '"',
847 'log_type="delete"',
848 'log_action="delete"',
849 'user_id=log_user' ),
850 $fname,
851 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
852
853 if($dbr->numRows($res) == 1) {
854 while ( $x = $dbr->fetchObject ( $res ) )
855 $data = $x;
856 $dbr->freeResult ( $res ) ;
857 } else {
858 $data = null;
859 }
860 return $data;
861 }
862
863 /**
864 * @todo document
865 */
866 function getPreviewText( $isConflict, $isCssJsSubpage ) {
867 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgAllowDiffPreview, $wgEnableDiffPreviewPreference;
868 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
869 "<p class='previewnote'>" . htmlspecialchars( wfMsg( 'previewnote' ) ) . "</p>\n";
870 if ( $isConflict ) {
871 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) .
872 "</h2>\n";
873 }
874
875 $parserOptions = ParserOptions::newFromUser( $wgUser );
876 $parserOptions->setEditSection( false );
877
878 # don't parse user css/js, show message about preview
879 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
880
881 if ( $isCssJsSubpage ) {
882 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
883 $previewtext = wfMsg('usercsspreview');
884 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
885 $previewtext = wfMsg('userjspreview');
886 }
887 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
888 $wgOut->addHTML( $parserOutput->mText );
889 return $previewhead;
890 } else {
891 # if user want to see preview when he edit an article
892 if( $wgUser->getOption('previewonfirst') and ($this->textbox1 == '')) {
893 $this->textbox1 = $this->mArticle->getContent(true);
894 }
895
896 $toparse = $this->textbox1;
897
898 # If we're adding a comment, we need to show the
899 # summary as the headline
900 if($this->section=="new" && $this->summary!="") {
901 $toparse="== {$this->summary} ==\n\n".$toparse;
902 }
903
904 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
905
906 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
907 $wgTitle, $parserOptions );
908
909 $previewHTML = $parserOutput->mText;
910
911 $wgOut->addCategoryLinks($parserOutput->getCategoryLinks());
912 $wgOut->addLanguageLinks($parserOutput->getLanguageLinks());
913 return $previewhead . $previewHTML;
914 }
915 }
916
917 /**
918 * @todo document
919 */
920 function blockedIPpage() {
921 global $wgOut, $wgUser, $wgContLang, $wgIP;
922
923 $wgOut->setPageTitle( wfMsg( 'blockedtitle' ) );
924 $wgOut->setRobotpolicy( 'noindex,nofollow' );
925 $wgOut->setArticleRelated( false );
926
927 $id = $wgUser->blockedBy();
928 $reason = $wgUser->blockedFor();
929 $ip = $wgIP;
930
931 if ( is_numeric( $id ) ) {
932 $name = User::whoIs( $id );
933 } else {
934 $name = $id;
935 }
936 $link = '[[' . $wgContLang->getNsText( NS_USER ) .
937 ":{$name}|{$name}]]";
938
939 $wgOut->addWikiText( wfMsg( 'blockedtext', $link, $reason, $ip, $name ) );
940 $wgOut->returnToMain( false );
941 }
942
943 /**
944 * @todo document
945 */
946 function userNotLoggedInPage() {
947 global $wgOut;
948
949 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
950 $wgOut->setRobotpolicy( 'noindex,nofollow' );
951 $wgOut->setArticleRelated( false );
952
953 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
954 $wgOut->returnToMain( false );
955 }
956
957 /**
958 * @todo document
959 */
960 function spamPage ( $match = false )
961 {
962 global $wgOut;
963 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
964 $wgOut->setRobotpolicy( 'noindex,nofollow' );
965 $wgOut->setArticleRelated( false );
966
967 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
968 if ( $match ) {
969 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
970 }
971 $wgOut->returnToMain( false );
972 }
973
974 /**
975 * Forks processes to scan the originating IP for an open proxy server
976 * MemCached can be used to skip IPs that have already been scanned
977 */
978 function proxyCheck() {
979 global $wgBlockOpenProxies, $wgProxyPorts, $wgProxyScriptPath;
980 global $wgIP, $wgUseMemCached, $wgMemc, $wgDBname, $wgProxyMemcExpiry;
981
982 if ( !$wgBlockOpenProxies ) {
983 return;
984 }
985
986 # Get MemCached key
987 $skip = false;
988 if ( $wgUseMemCached ) {
989 $mcKey = $wgDBname.':proxy:ip:'.$wgIP;
990 $mcValue = $wgMemc->get( $mcKey );
991 if ( $mcValue ) {
992 $skip = true;
993 }
994 }
995
996 # Fork the processes
997 if ( !$skip ) {
998 $title = Title::makeTitle( NS_SPECIAL, 'Blockme' );
999 $iphash = md5( $wgIP . $wgProxyKey );
1000 $url = $title->getFullURL( 'ip='.$iphash );
1001
1002 foreach ( $wgProxyPorts as $port ) {
1003 $params = implode( ' ', array(
1004 escapeshellarg( $wgProxyScriptPath ),
1005 escapeshellarg( $wgIP ),
1006 escapeshellarg( $port ),
1007 escapeshellarg( $url )
1008 ));
1009 exec( "php $params &>/dev/null &" );
1010 }
1011 # Set MemCached key
1012 if ( $wgUseMemCached ) {
1013 $wgMemc->set( $mcKey, 1, $wgProxyMemcExpiry );
1014 }
1015 }
1016 }
1017
1018 /**
1019 * @access private
1020 * @todo document
1021 */
1022 function mergeChangesInto( &$editText ){
1023 $fname = 'EditPage::mergeChangesInto';
1024 wfProfileIn( $fname );
1025
1026 $db =& wfGetDB( DB_MASTER );
1027
1028 // This is the revision the editor started from
1029 $baseRevision = Revision::loadFromTimestamp(
1030 $db, $this->mArticle->mTitle, $this->edittime );
1031 if( is_null( $baseRevision ) ) {
1032 wfProfileOut( $fname );
1033 return false;
1034 }
1035 $baseText = $baseRevision->getText();
1036
1037 // The current state, we want to merge updates into it
1038 $currentRevision = Revision::loadFromTitle(
1039 $db, $this->mArticle->mTitle );
1040 if( is_null( $currentRevision ) ) {
1041 wfProfileOut( $fname );
1042 return false;
1043 }
1044 $currentText = $currentRevision->getText();
1045
1046 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1047 $editText = $result;
1048 wfProfileOut( $fname );
1049 return true;
1050 } else {
1051 wfProfileOut( $fname );
1052 return false;
1053 }
1054 }
1055
1056
1057 function checkUnicodeCompliantBrowser() {
1058 global $wgBrowserBlackList;
1059 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1060 foreach ( $wgBrowserBlackList as $browser ) {
1061 if ( preg_match($browser, $currentbrowser) ) {
1062 return false;
1063 }
1064 }
1065 return true;
1066 }
1067
1068 /**
1069 * Format an anchor fragment as it would appear for a given section name
1070 * @param string $text
1071 * @return string
1072 * @access private
1073 */
1074 function sectionAnchor( $text ) {
1075 $headline = Sanitizer::decodeCharReferences( $text );
1076 # strip out HTML
1077 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1078 $headline = trim( $headline );
1079 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1080 $replacearray = array(
1081 '%3A' => ':',
1082 '%' => '.'
1083 );
1084 return str_replace(
1085 array_keys( $replacearray ),
1086 array_values( $replacearray ),
1087 $sectionanchor );
1088 }
1089
1090 /**
1091 * Shows a bulletin board style toolbar for common editing functions.
1092 * It can be disabled in the user preferences.
1093 * The necessary JavaScript code can be found in style/wikibits.js.
1094 */
1095 function getEditToolbar() {
1096 global $wgStylePath, $wgLang, $wgMimeType, $wgJsMimeType;
1097
1098 /**
1099 * toolarray an array of arrays which each include the filename of
1100 * the button image (without path), the opening tag, the closing tag,
1101 * and optionally a sample text that is inserted between the two when no
1102 * selection is highlighted.
1103 * The tip text is shown when the user moves the mouse over the button.
1104 *
1105 * Already here are accesskeys (key), which are not used yet until someone
1106 * can figure out a way to make them work in IE. However, we should make
1107 * sure these keys are not defined on the edit page.
1108 */
1109 $toolarray=array(
1110 array( 'image'=>'button_bold.png',
1111 'open' => "\'\'\'",
1112 'close' => "\'\'\'",
1113 'sample'=> wfMsg('bold_sample'),
1114 'tip' => wfMsg('bold_tip'),
1115 'key' => 'B'
1116 ),
1117 array( 'image'=>'button_italic.png',
1118 'open' => "\'\'",
1119 'close' => "\'\'",
1120 'sample'=> wfMsg('italic_sample'),
1121 'tip' => wfMsg('italic_tip'),
1122 'key' => 'I'
1123 ),
1124 array( 'image'=>'button_link.png',
1125 'open' => '[[',
1126 'close' => ']]',
1127 'sample'=> wfMsg('link_sample'),
1128 'tip' => wfMsg('link_tip'),
1129 'key' => 'L'
1130 ),
1131 array( 'image'=>'button_extlink.png',
1132 'open' => '[',
1133 'close' => ']',
1134 'sample'=> wfMsg('extlink_sample'),
1135 'tip' => wfMsg('extlink_tip'),
1136 'key' => 'X'
1137 ),
1138 array( 'image'=>'button_headline.png',
1139 'open' => "\\n== ",
1140 'close' => " ==\\n",
1141 'sample'=> wfMsg('headline_sample'),
1142 'tip' => wfMsg('headline_tip'),
1143 'key' => 'H'
1144 ),
1145 array( 'image'=>'button_image.png',
1146 'open' => '[['.$wgLang->getNsText(NS_IMAGE).":",
1147 'close' => ']]',
1148 'sample'=> wfMsg('image_sample'),
1149 'tip' => wfMsg('image_tip'),
1150 'key' => 'D'
1151 ),
1152 array( 'image' =>'button_media.png',
1153 'open' => '[['.$wgLang->getNsText(NS_MEDIA).':',
1154 'close' => ']]',
1155 'sample'=> wfMsg('media_sample'),
1156 'tip' => wfMsg('media_tip'),
1157 'key' => 'M'
1158 ),
1159 array( 'image' =>'button_math.png',
1160 'open' => "\\<math\\>",
1161 'close' => "\\</math\\>",
1162 'sample'=> wfMsg('math_sample'),
1163 'tip' => wfMsg('math_tip'),
1164 'key' => 'C'
1165 ),
1166 array( 'image' =>'button_nowiki.png',
1167 'open' => "\\<nowiki\\>",
1168 'close' => "\\</nowiki\\>",
1169 'sample'=> wfMsg('nowiki_sample'),
1170 'tip' => wfMsg('nowiki_tip'),
1171 'key' => 'N'
1172 ),
1173 array( 'image' =>'button_sig.png',
1174 'open' => '--~~~~',
1175 'close' => '',
1176 'sample'=> '',
1177 'tip' => wfMsg('sig_tip'),
1178 'key' => 'Y'
1179 ),
1180 array( 'image' =>'button_hr.png',
1181 'open' => "\\n----\\n",
1182 'close' => '',
1183 'sample'=> '',
1184 'tip' => wfMsg('hr_tip'),
1185 'key' => 'R'
1186 )
1187 );
1188 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1189
1190 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1191 foreach($toolarray as $tool) {
1192
1193 $image=$wgStylePath.'/common/images/'.$tool['image'];
1194 $open=$tool['open'];
1195 $close=$tool['close'];
1196 $sample = wfEscapeJsString( $tool['sample'] );
1197
1198 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1199 // Older browsers show a "speedtip" type message only for ALT.
1200 // Ideally these should be different, realistically they
1201 // probably don't need to be.
1202 $tip = wfEscapeJsString( $tool['tip'] );
1203
1204 #$key = $tool["key"];
1205
1206 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1207 }
1208
1209 $toolbar.="addInfobox('" . wfEscapeJsString( wfMsg( "infobox" ) ) .
1210 "','" . wfEscapeJsString( wfMsg( "infobox_alert" ) ) . "');\n";
1211 $toolbar.="document.writeln(\"</div>\");\n";
1212
1213 $toolbar.="/*]]>*/\n</script>";
1214 return $toolbar;
1215 }
1216
1217 /**
1218 * Output preview text only. This can be sucked into the edit page
1219 * via JavaScript, and saves the server time rendering the skin as
1220 * well as theoretically being more robust on the client (doesn't
1221 * disturb the edit box's undo history, won't eat your text on
1222 * failure, etc).
1223 *
1224 * @todo This doesn't include category or interlanguage links.
1225 * Would need to enhance it a bit, maybe wrap them in XML
1226 * or something... that might also require more skin
1227 * initialization, so check whether that's a problem.
1228 */
1229 function livePreview() {
1230 global $wgOut;
1231 $wgOut->disable();
1232 header( 'Content-type: text/xml' );
1233 header( 'Cache-control: no-cache' );
1234 # FIXME
1235 echo $this->getPreviewText( false, false );
1236 }
1237
1238
1239 /**
1240 * Get a diff between the current contents of the edit box and the
1241 * version of the page we're editing from.
1242 *
1243 * If this is a section edit, we'll replace the section as for final
1244 * save and then make a comparison.
1245 *
1246 * @return string HTML
1247 */
1248 function getDiff() {
1249 require_once( 'DifferenceEngine.php' );
1250 $oldtext = $this->mArticle->fetchContent();
1251 $newtext = $this->mArticle->getTextOfLastEditWithSectionReplacedOrAdded(
1252 $this->section, $this->textbox1, $this->summary, $this->edittime );
1253 $oldtitle = wfMsg( 'currentrev' );
1254 $newtitle = wfMsg( 'yourtext' );
1255 if ( $oldtext != wfMsg( 'noarticletext' ) || $newtext != '' ) {
1256 $difftext = DifferenceEngine::getDiff( $oldtext, $newtext, $oldtitle, $newtitle );
1257 }
1258
1259 return '<div id="wikiDiff">' . $difftext . '</div>';
1260 }
1261
1262 /**
1263 * Filter an input field through a Unicode de-armoring process if it
1264 * came from an old browser with known broken Unicode editing issues.
1265 *
1266 * @param WebRequest $request
1267 * @param string $field
1268 * @return string
1269 * @access private
1270 */
1271 function safeUnicodeInput( $request, $field ) {
1272 $text = rtrim( $request->getText( $field ) );
1273 return $request->getBool( 'safemode' )
1274 ? $this->unmakesafe( $text )
1275 : $text;
1276 }
1277
1278 /**
1279 * Filter an output field through a Unicode armoring process if it is
1280 * going to an old browser with known broken Unicode editing issues.
1281 *
1282 * @param string $text
1283 * @return string
1284 * @access private
1285 */
1286 function safeUnicodeOutput( $text ) {
1287 global $wgContLang;
1288 $codedText = $wgContLang->recodeForEdit( $text );
1289 return $this->checkUnicodeCompliantBrowser()
1290 ? $codedText
1291 : $this->makesafe( $codedText );
1292 }
1293
1294 /**
1295 * A number of web browsers are known to corrupt non-ASCII characters
1296 * in a UTF-8 text editing environment. To protect against this,
1297 * detected browsers will be served an armored version of the text,
1298 * with non-ASCII chars converted to numeric HTML character references.
1299 *
1300 * Preexisting such character references will have a 0 added to them
1301 * to ensure that round-trips do not alter the original data.
1302 *
1303 * @param string $invalue
1304 * @return string
1305 * @access private
1306 */
1307 function makesafe( $invalue ) {
1308 // Armor existing references for reversability.
1309 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1310
1311 $bytesleft = 0;
1312 $result = "";
1313 $working = 0;
1314 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1315 $bytevalue = ord( $invalue{$i} );
1316 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1317 $result .= chr( $bytevalue );
1318 $bytesleft = 0;
1319 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1320 $working = $working << 6;
1321 $working += ($bytevalue & 0x3F);
1322 $bytesleft--;
1323 if( $bytesleft <= 0 ) {
1324 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1325 }
1326 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1327 $working = $bytevalue & 0x1F;
1328 $bytesleft = 1;
1329 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1330 $working = $bytevalue & 0x0F;
1331 $bytesleft = 2;
1332 } else { //1111 0xxx
1333 $working = $bytevalue & 0x07;
1334 $bytesleft = 3;
1335 }
1336 }
1337 return $result;
1338 }
1339
1340 /**
1341 * Reverse the previously applied transliteration of non-ASCII characters
1342 * back to UTF-8. Used to protect data from corruption by broken web browsers
1343 * as listed in $wgBrowserBlackList.
1344 *
1345 * @param string $invalue
1346 * @return string
1347 * @access private
1348 */
1349 function unmakesafe( $invalue ) {
1350 $result = "";
1351 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1352 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
1353 $i += 3;
1354 $hexstring = "";
1355 do {
1356 $hexstring .= $invalue{$i};
1357 $i++;
1358 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1359
1360 // Do some sanity checks. These aren't needed for reversability,
1361 // but should help keep the breakage down if the editor
1362 // breaks one of the entities whilst editing.
1363 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1364 $codepoint = hexdec($hexstring);
1365 $result .= codepointToUtf8( $codepoint );
1366 } else {
1367 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1368 }
1369 } else {
1370 $result .= substr( $invalue, $i, 1 );
1371 }
1372 }
1373 // reverse the transform that we made for reversability reasons.
1374 return strtr( $result, array( "&#x0" => "&#x" ) );
1375 }
1376
1377
1378 }
1379
1380 ?>