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