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