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