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