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