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