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