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