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