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