* Replace wfMungeToUtf8 and do_html_entity_decode with a single function
[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
21 # Form values
22 var $save = false, $preview = false, $diff = false;
23 var $minoredit = false, $watchthis = false;
24 var $textbox1 = '', $textbox2 = '', $summary = '';
25 var $edittime = '', $section = '';
26 var $oldid = 0;
27
28 /**
29 * @todo document
30 * @param $article
31 */
32 function EditPage( $article ) {
33 $this->mArticle =& $article;
34 global $wgTitle;
35 $this->mTitle =& $wgTitle;
36 }
37
38 /**
39 * This is the function that extracts metadata from the article body on the first view.
40 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
41 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
42 */
43 function extractMetaDataFromArticle ()
44 {
45 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
46 $this->mMetaData = '' ;
47 if ( !$wgUseMetadataEdit ) return ;
48 if ( $wgMetadataWhitelist == "" ) return ;
49 $s = '' ;
50 $t = $this->mArticle->getContent ( true ) ;
51
52 # MISSING : <nowiki> filtering
53
54 # Categories and language links
55 $t = explode ( "\n" , $t ) ;
56 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY ) ) ;
57 $cat = $ll = array() ;
58 foreach ( $t AS $key => $x )
59 {
60 $y = trim ( strtolower ( $x ) ) ;
61 while ( substr ( $y , 0 , 2 ) == "[[" )
62 {
63 $y = explode ( "]]" , trim ( $x ) ) ;
64 $first = array_shift ( $y ) ;
65 $first = explode ( ":" , $first ) ;
66 $ns = array_shift ( $first ) ;
67 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
68 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
69 {
70 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
71 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
72 else $ll[] = $add ;
73 $x = implode ( ']]' , $y ) ;
74 $t[$key] = $x ;
75 $y = trim ( strtolower ( $x ) ) ;
76 }
77 }
78 }
79 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
80 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
81 $t = implode ( "\n" , $t ) ;
82
83 # Load whitelist
84 $sat = array () ; # stand-alone-templates; must be lowercase
85 $wl_title = Title::newFromText ( $wgMetadataWhitelist ) ;
86 $wl_article = new Article ( $wl_title ) ;
87 $wl = explode ( "\n" , $wl_article->getContent(true) ) ;
88 foreach ( $wl AS $x )
89 {
90 $isentry = false ;
91 $x = trim ( $x ) ;
92 while ( substr ( $x , 0 , 1 ) == '*' )
93 {
94 $isentry = true ;
95 $x = trim ( substr ( $x , 1 ) ) ;
96 }
97 if ( $isentry )
98 {
99 $sat[] = strtolower ( $x ) ;
100 }
101
102 }
103
104 # Templates, but only some
105 $t = explode ( '{{' , $t ) ;
106 $tl = array () ;
107 foreach ( $t AS $key => $x )
108 {
109 $y = explode ( '}}' , $x , 2 ) ;
110 if ( count ( $y ) == 2 )
111 {
112 $z = $y[0] ;
113 $z = explode ( '|' , $z ) ;
114 $tn = array_shift ( $z ) ;
115 if ( in_array ( strtolower ( $tn ) , $sat ) )
116 {
117 $tl[] = '{{' . $y[0] . '}}' ;
118 $t[$key] = $y[1] ;
119 $y = explode ( '}}' , $y[1] , 2 ) ;
120 }
121 else $t[$key] = '{{' . $x ;
122 }
123 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
124 else $t[$key] = $x ;
125 }
126 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
127 $t = implode ( '' , $t ) ;
128
129 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
130 $this->mArticle->mContent = $t ;
131 $this->mMetaData = $s ;
132 }
133
134 /**
135 * This is the function that gets called for "action=edit".
136 */
137 function edit() {
138 global $wgOut, $wgUser, $wgWhitelistEdit, $wgRequest;
139 // this is not an article
140 $wgOut->setArticleFlag(false);
141
142 $this->importFormData( $wgRequest );
143
144 if( $this->live ) {
145 $this->livePreview();
146 return;
147 }
148
149 if ( ! $this->mTitle->userCanEdit() ) {
150 $wgOut->readOnlyPage( $this->mArticle->getContent( true ), true );
151 return;
152 }
153 if ( !$this->preview && !$this->diff && $wgUser->isBlocked( !$this->save ) ) {
154 # When previewing, don't check blocked state - will get caught at save time.
155 # Also, check when starting edition is done against slave to improve performance.
156 $this->blockedIPpage();
157 return;
158 }
159 if ( $wgUser->isAnon() && $wgWhitelistEdit ) {
160 $this->userNotLoggedInPage();
161 return;
162 }
163 if ( wfReadOnly() ) {
164 if( $this->save || $this->preview ) {
165 $this->editForm( 'preview' );
166 } else if ( $this->diff ) {
167 $this->editForm( 'diff' );
168 } else {
169 $wgOut->readOnlyPage( $this->mArticle->getContent( true ) );
170 }
171 return;
172 }
173 if ( $this->save ) {
174 $this->editForm( 'save' );
175 } else if ( $this->preview ) {
176 $this->editForm( 'preview' );
177 } else if ( $this->diff ) {
178 $this->editForm( 'diff' );
179 } else { # First time through
180 if( $wgUser->getOption('previewonfirst') ) {
181 $this->editForm( 'preview', true );
182 } else {
183 $this->extractMetaDataFromArticle () ;
184 $this->editForm( 'initial', true );
185 }
186 }
187 }
188
189 /**
190 * @todo document
191 */
192 function importFormData( &$request ) {
193 if( $request->wasPosted() ) {
194 # These fields need to be checked for encoding.
195 # Also remove trailing whitespace, but don't remove _initial_
196 # whitespace from the text boxes. This may be significant formatting.
197 $this->textbox1 = rtrim( $request->getText( 'wpTextbox1' ) );
198 $this->textbox2 = rtrim( $request->getText( 'wpTextbox2' ) );
199 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
200 $this->summary = trim( $request->getText( 'wpSummary' ) );
201
202 $this->edittime = $request->getVal( 'wpEdittime' );
203 if( is_null( $this->edittime ) ) {
204 # If the form is incomplete, force to preview.
205 $this->preview = true;
206 } else {
207 if( $this->tokenOk( $request ) ) {
208 # Some browsers will not report any submit button
209 # if the user hits enter in the comment box.
210 # The unmarked state will be assumed to be a save,
211 # if the form seems otherwise complete.
212 $this->preview = $request->getCheck( 'wpPreview' );
213 $this->diff = $request->getCheck( 'wpDiff' );
214 } else {
215 # Page might be a hack attempt posted from
216 # an external site. Preview instead of saving.
217 $this->preview = true;
218 }
219 }
220 $this->save = ! ( $this->preview OR $this->diff );
221 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
222 $this->edittime = null;
223 }
224
225 $this->minoredit = $request->getCheck( 'wpMinoredit' );
226 $this->watchthis = $request->getCheck( 'wpWatchthis' );
227 } else {
228 # Not a posted form? Start with nothing.
229 $this->textbox1 = '';
230 $this->textbox2 = '';
231 $this->mMetaData = '';
232 $this->summary = '';
233 $this->edittime = '';
234 $this->preview = false;
235 $this->save = false;
236 $this->diff = false;
237 $this->minoredit = false;
238 $this->watchthis = false;
239 }
240
241 $this->oldid = $request->getInt( 'oldid' );
242
243 # Section edit can come from either the form or a link
244 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
245
246 $this->live = $request->getCheck( 'live' );
247 }
248
249 /**
250 * Make sure the form isn't faking a user's credentials.
251 *
252 * @param WebRequest $request
253 * @return bool
254 * @access private
255 */
256 function tokenOk( &$request ) {
257 global $wgUser;
258 if( $wgUser->isAnon() ) {
259 # Anonymous users may not have a session
260 # open. Don't tokenize.
261 return true;
262 } else {
263 return $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
264 }
265 }
266
267 function submit() {
268 $this->edit();
269 }
270
271 /**
272 * The edit form is self-submitting, so that when things like
273 * preview and edit conflicts occur, we get the same form back
274 * with the extra stuff added. Only when the final submission
275 * is made and all is well do we actually save and redirect to
276 * the newly-edited page.
277 *
278 * @param string $formtype Type of form either : save, initial, diff or preview
279 * @param bool $firsttime True to load form data from db
280 */
281 function editForm( $formtype, $firsttime = false ) {
282 global $wgOut, $wgUser;
283 global $wgLang, $wgContLang, $wgParser, $wgTitle;
284 global $wgAllowAnonymousMinor;
285 global $wgWhitelistEdit;
286 global $wgSpamRegex, $wgFilterCallback;
287
288 $sk = $wgUser->getSkin();
289 $isConflict = false;
290 // css / js subpages of user pages get a special treatment
291 $isCssJsSubpage = $wgTitle->isCssJsSubpage();
292
293
294 if(!$this->mTitle->getArticleID()) { # new article
295 $wgOut->addWikiText(wfmsg('newarticletext'));
296 }
297
298 if( $this->mTitle->isTalkPage() ) {
299 $wgOut->addWikiText(wfmsg('talkpagetext'));
300 }
301
302 # Attempt submission here. This will check for edit conflicts,
303 # and redundantly check for locked database, blocked IPs, etc.
304 # that edit() already checked just in case someone tries to sneak
305 # in the back door with a hand-edited submission URL.
306
307 if ( 'save' == $formtype ) {
308 # Reintegrate metadata
309 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
310 $this->mMetaData = '' ;
311
312 # Check for spam
313 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
314 $this->spamPage ( $matches[0] );
315 return;
316 }
317 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
318 # Error messages or other handling should be performed by the filter function
319 return;
320 }
321 if ( $wgUser->isBlocked( false ) ) {
322 # Check block state against master, thus 'false'.
323 $this->blockedIPpage();
324 return;
325 }
326 if ( $wgUser->isAnon() && $wgWhitelistEdit ) {
327 $this->userNotLoggedInPage();
328 return;
329 }
330 if ( wfReadOnly() ) {
331 $wgOut->readOnlyPage();
332 return;
333 }
334 if ( $wgUser->pingLimiter() ) {
335 $wgOut->rateLimited();
336 return;
337 }
338
339 # If article is new, insert it.
340 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
341 if ( 0 == $aid ) {
342 # Don't save a new article if it's blank.
343 if ( ( '' == $this->textbox1 ) ||
344 ( wfMsg( 'newarticletext' ) == $this->textbox1 ) ) {
345 $wgOut->redirect( $this->mTitle->getFullURL() );
346 return;
347 }
348 if (wfRunHooks('ArticleSave', array(&$this->mArticle, &$wgUser, &$this->textbox1,
349 &$this->summary, &$this->minoredit, &$this->watchthis, NULL)))
350 {
351 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
352 $this->minoredit, $this->watchthis );
353 wfRunHooks('ArticleSaveComplete', array(&$this->mArticle, &$wgUser, $this->textbox1,
354 $this->summary, $this->minoredit,
355 $this->watchthis, NULL));
356 }
357 return;
358 }
359
360 # Article exists. Check for edit conflict.
361
362 $this->mArticle->clear(); # Force reload of dates, etc.
363 $this->mArticle->forUpdate( true ); # Lock the article
364
365 if( ( $this->section != 'new' ) &&
366 ($this->mArticle->getTimestamp() != $this->edittime ) ) {
367 $isConflict = true;
368 }
369 $userid = $wgUser->getID();
370
371 if ( $isConflict) {
372 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime'\n" );
373 $text = $this->mArticle->getTextOfLastEditWithSectionReplacedOrAdded(
374 $this->section, $this->textbox1, $this->summary, $this->edittime);
375 }
376 else {
377 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
378 $text = $this->mArticle->getTextOfLastEditWithSectionReplacedOrAdded(
379 $this->section, $this->textbox1, $this->summary);
380 }
381 # Suppress edit conflict with self
382
383 if ( ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
384 $isConflict = false;
385 } else {
386 # switch from section editing to normal editing in edit conflict
387 if($isConflict) {
388 # Attempt merge
389 if( $this->mergeChangesInto( $text ) ){
390 // Successful merge! Maybe we should tell the user the good news?
391 $isConflict = false;
392 } else {
393 $this->section = '';
394 $this->textbox1 = $text;
395 }
396 }
397 }
398 if ( ! $isConflict ) {
399 # All's well
400 $sectionanchor = '';
401 if( $this->section == 'new' ) {
402 if( $this->summary != '' ) {
403 $sectionanchor = $this->sectionAnchor( $this->summary );
404 }
405 } elseif( $this->section != '' ) {
406 # Try to get a section anchor from the section source, redirect to edited section if header found
407 # XXX: might be better to integrate this into Article::getTextOfLastEditWithSectionReplacedOrAdded
408 # for duplicate heading checking and maybe parsing
409 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
410 # we can't deal with anchors, includes, html etc in the header for now,
411 # headline would need to be parsed to improve this
412 #if($hasmatch and strlen($matches[2]) > 0 and !preg_match( "/[\\['{<>]/", $matches[2])) {
413 if($hasmatch and strlen($matches[2]) > 0) {
414 $sectionanchor = $this->sectionAnchor( $matches[2] );
415 }
416 }
417
418 if (wfRunHooks('ArticleSave', array(&$this->mArticle, &$wgUser, &$text,
419 &$this->summary, &$this->minoredit,
420 &$this->watchthis, &$sectionanchor)))
421 {
422 # update the article here
423 if($this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
424 $this->watchthis, '', $sectionanchor ))
425 {
426 wfRunHooks('ArticleSaveComplete', array(&$this->mArticle, &$wgUser, $text,
427 $this->summary, $this->minoredit,
428 $this->watchthis, $sectionanchor));
429 return;
430 }
431 else
432 $isConflict = true;
433 }
434 }
435 }
436 # First time through: get contents, set time for conflict
437 # checking, etc.
438
439 if ( 'initial' == $formtype || $firsttime ) {
440 $this->edittime = $this->mArticle->getTimestamp();
441 $this->textbox1 = $this->mArticle->getContent( true );
442 $this->summary = '';
443 $this->proxyCheck();
444 }
445 $wgOut->setRobotpolicy( 'noindex,nofollow' );
446
447 # Enabled article-related sidebar, toplinks, etc.
448 $wgOut->setArticleRelated( true );
449
450 if ( $isConflict ) {
451 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
452 $wgOut->setPageTitle( $s );
453 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
454
455 $this->textbox2 = $this->textbox1;
456 $this->textbox1 = $this->mArticle->getContent( true );
457 $this->edittime = $this->mArticle->getTimestamp();
458 } else {
459
460 if( $this->section != '' ) {
461 if( $this->section == 'new' ) {
462 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
463 } else {
464 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
465 }
466 if(!$this->preview) {
467 preg_match( "/^(=+)(.+)\\1/mi",
468 $this->textbox1,
469 $matches );
470 if( !empty( $matches[2] ) ) {
471 $this->summary = "/* ". trim($matches[2])." */ ";
472 }
473 }
474 } else {
475 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
476 }
477 $wgOut->setPageTitle( $s );
478 if ( !$this->checkUnicodeCompliantBrowser() ) {
479 $this->mArticle->setOldSubtitle();
480 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
481 }
482 if ( $this->oldid ) {
483 $this->mArticle->setOldSubtitle();
484 $wgOut->addWikiText( wfMsg( 'editingold' ) );
485 }
486 }
487
488 if( wfReadOnly() ) {
489 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
490 } else if ( $isCssJsSubpage and 'preview' != $formtype) {
491 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ));
492 }
493 if( $this->mTitle->isProtected('edit') ) {
494 $wgOut->addWikiText( wfMsg( 'protectedpagewarning' ) );
495 }
496
497 $kblength = (int)(strlen( $this->textbox1 ) / 1024);
498 if( $kblength > 29 ) {
499 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $kblength ) ) );
500 }
501
502 $rows = $wgUser->getOption( 'rows' );
503 $cols = $wgUser->getOption( 'cols' );
504
505 $ew = $wgUser->getOption( 'editwidth' );
506 if ( $ew ) $ew = " style=\"width:100%\"";
507 else $ew = '';
508
509 $q = 'action=submit';
510 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
511 $action = $this->mTitle->escapeLocalURL( $q );
512
513 $summary = wfMsg('summary');
514 $subject = wfMsg('subject');
515 $minor = wfMsg('minoredit');
516 $watchthis = wfMsg ('watchthis');
517 $save = wfMsg('savearticle');
518 $prev = wfMsg('showpreview');
519 $diff = wfMsg('showdiff');
520
521 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
522 wfMsg('cancel') );
523 $edithelpurl = $sk->makeUrl( wfMsg( 'edithelppage' ));
524 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
525 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
526 htmlspecialchars( wfMsg( 'newwindow' ) );
527
528 global $wgRightsText;
529 $copywarn = "<div id=\"editpage-copywarn\">\n" .
530 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
531 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
532 $wgRightsText ) . "\n</div>";
533
534 if( $wgUser->getOption('showtoolbar') and !$isCssJsSubpage ) {
535 # prepare toolbar for edit buttons
536 $toolbar = $this->getEditToolbar();
537 } else {
538 $toolbar = '';
539 }
540
541 // activate checkboxes if user wants them to be always active
542 if( !$this->preview && !$this->diff ) {
543 if( $wgUser->getOption( 'watchdefault' ) ) $this->watchthis = true;
544 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
545
546 // activate checkbox also if user is already watching the page,
547 // require wpWatchthis to be unset so that second condition is not
548 // checked unnecessarily
549 if( !$this->watchthis && $this->mTitle->userIsWatching() ) $this->watchthis = true;
550 }
551
552 $minoredithtml = '';
553
554 if ( $wgUser->isLoggedIn() || $wgAllowAnonymousMinor ) {
555 $minoredithtml =
556 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
557 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
558 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
559 }
560
561 $watchhtml = '';
562
563 if ( $wgUser->isLoggedIn() ) {
564 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".($this->watchthis?" checked='checked'":"").
565 " accesskey='".wfMsg('accesskey-watch')."' id='wpWatchthis' />".
566 "<label for='wpWatchthis' title='".wfMsg('tooltip-watch')."'>{$watchthis}</label>";
567 }
568
569 $checkboxhtml = $minoredithtml . $watchhtml . '<br />';
570
571 $wgOut->addHTML( '<div id="wikiPreview">' );
572 if ( 'preview' == $formtype) {
573 $previewOutput = $this->getPreviewText( $isConflict, $isCssJsSubpage );
574 if ( $wgUser->getOption('previewontop' ) ) {
575 $wgOut->addHTML( $previewOutput );
576 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
577 }
578 }
579 $wgOut->addHTML( '</div>' );
580 if ( 'diff' == $formtype ) {
581 if ( $wgUser->getOption('previewontop' ) ) {
582 $wgOut->addHTML( $this->getDiff() );
583 }
584 }
585
586
587 # if this is a comment, show a subject line at the top, which is also the edit summary.
588 # Otherwise, show a summary field at the bottom
589 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
590 if( $this->section == 'new' ) {
591 $commentsubject="{$subject}: <input tabindex='1' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
592 $editsummary = '';
593 } else {
594 $commentsubject = '';
595 $editsummary="{$summary}: <input tabindex='2' type='text' value=\"$summarytext\" name=\"wpSummary\" maxlength='200' size='60' /><br />";
596 }
597
598 if( !$this->preview && !$this->diff ) {
599 # Don't select the edit box on preview; this interferes with seeing what's going on.
600 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
601 }
602 # Prepare a list of templates used by this page
603 $templates = '';
604 $articleTemplates = $this->mArticle->getUsedTemplates();
605 if ( count( $articleTemplates ) > 0 ) {
606 $templates = '<br />'. wfMsg( 'templatesused' ) . '<ul>';
607 foreach ( $articleTemplates as $tpl ) {
608 if ( $titleObj = Title::makeTitle( NS_TEMPLATE, $tpl ) ) {
609 $templates .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
610 }
611 }
612 $templates .= '</ul>';
613 }
614
615 global $wgLivePreview, $wgStylePath;
616 /**
617 * Live Preview lets us fetch rendered preview page content and
618 * add it to the page without refreshing the whole page.
619 * Set up the button for it; if not supported by the browser
620 * it will fall through to the normal form submission method.
621 */
622 if( $wgLivePreview ) {
623 global $wgJsMimeType;
624 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
625 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
626 '"></script>' . "\n" );
627 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
628 $liveOnclick = 'onclick="return !livePreview('.
629 'getElementById(\'wikiPreview\'),' .
630 'editform.wpTextbox1.value,' .
631 htmlspecialchars( '"' . $liveAction . '"' ) . ')"';
632 } else {
633 $liveOnclick = '';
634 }
635
636 global $wgUseMetadataEdit ;
637 if ( $wgUseMetadataEdit )
638 {
639 $metadata = $this->mMetaData ;
640 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
641 $helppage = Title::newFromText ( wfmsg("metadata_page") ) ;
642 $top = str_replace ( "$1" , $helppage->getInternalURL() , wfmsg("metadata") ) ;
643 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
644 }
645 else $metadata = "" ;
646
647
648 $wgOut->addHTML( <<<END
649 {$toolbar}
650 <form id="editform" name="editform" method="post" action="$action"
651 enctype="multipart/form-data">
652 {$commentsubject}
653 <textarea tabindex='1' accesskey="," name="wpTextbox1" rows='{$rows}'
654 cols='{$cols}'{$ew}>
655 END
656 . htmlspecialchars( $wgContLang->recodeForEdit( $this->textbox1 ) ) .
657 "
658 </textarea>
659 {$metadata}
660 <br />{$editsummary}
661 {$checkboxhtml}
662 <input tabindex='5' id='wpSave' type='submit' value=\"{$save}\" name=\"wpSave\" accesskey=\"".wfMsg('accesskey-save')."\"".
663 " title=\"".wfMsg('tooltip-save')."\"/>
664 <input tabindex='6' id='wpPreview' type='submit' $liveOnclick value=\"{$prev}\" name=\"wpPreview\" accesskey=\"".wfMsg('accesskey-preview')."\"".
665 " title=\"".wfMsg('tooltip-preview')."\"/>
666 <input tabindex='7' id='wpDiff' type='submit' value=\"{$diff}\" name=\"wpDiff\" accesskey=\"".wfMsg('accesskey-diff')."\"".
667 " title=\"".wfMsg('tooltip-diff')."\"/>
668 <em>{$cancel}</em> | <em>{$edithelp}</em>{$templates}" );
669 $wgOut->addWikiText( $copywarn );
670 $wgOut->addHTML( "
671 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
672 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n" );
673
674 if ( $wgUser->isLoggedIn() ) {
675 /**
676 * To make it harder for someone to slip a user a page
677 * which submits an edit form to the wiki without their
678 * knowledge, a random token is associated with the login
679 * session. If it's not passed back with the submission,
680 * we won't save the page, or render user JavaScript and
681 * CSS previews.
682 */
683 $token = htmlspecialchars( $wgUser->editToken() );
684 $wgOut->addHTML( "
685 <input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
686 }
687
688
689 if ( $isConflict ) {
690 require_once( "DifferenceEngine.php" );
691 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
692 DifferenceEngine::showDiff( $this->textbox2, $this->textbox1,
693 wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
694
695 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
696 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
697 . htmlspecialchars( $wgContLang->recodeForEdit( $this->textbox2 ) ) .
698 "
699 </textarea>" );
700 }
701 $wgOut->addHTML( "</form>\n" );
702 if ( $formtype == 'preview' && !$wgUser->getOption( 'previewontop' ) ) {
703 $wgOut->addHTML( '<div id="wikiPreview">' . $previewOutput . '</div>' );
704 }
705 if ( $formtype == 'diff' && !$wgUser->getOption( 'previewontop' ) ) {
706 #$wgOut->addHTML( '<div id="wikiPreview">' . $difftext . '</div>' );
707 $wgOut->addHTML( $this->getDiff() );
708 }
709 }
710
711 /**
712 * @todo document
713 */
714 function getPreviewText( $isConflict, $isCssJsSubpage ) {
715 global $wgOut, $wgUser, $wgTitle, $wgParser, $wgAllowDiffPreview, $wgEnableDiffPreviewPreference;
716 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
717 "<p class='previewnote'>" . htmlspecialchars( wfMsg( 'previewnote' ) ) . "</p>\n";
718 if ( $isConflict ) {
719 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) .
720 "</h2>\n";
721 }
722
723 $parserOptions = ParserOptions::newFromUser( $wgUser );
724 $parserOptions->setEditSection( false );
725
726 # don't parse user css/js, show message about preview
727 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
728
729 if ( $isCssJsSubpage ) {
730 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
731 $previewtext = wfMsg('usercsspreview');
732 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
733 $previewtext = wfMsg('userjspreview');
734 }
735 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
736 $wgOut->addHTML( $parserOutput->mText );
737 return $previewhead;
738 } else {
739 # if user want to see preview when he edit an article
740 if( $wgUser->getOption('previewonfirst') and ($this->textbox1 == '')) {
741 $this->textbox1 = $this->mArticle->getContent(true);
742 }
743
744 $toparse = $this->textbox1 ;
745 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
746
747 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
748 $wgTitle, $parserOptions );
749
750 $previewHTML = $parserOutput->mText;
751
752 $wgOut->addCategoryLinks($parserOutput->getCategoryLinks());
753 $wgOut->addLanguageLinks($parserOutput->getLanguageLinks());
754 return $previewhead . $previewHTML;
755 }
756 }
757
758 /**
759 * @todo document
760 */
761 function blockedIPpage() {
762 global $wgOut, $wgUser, $wgContLang, $wgIP;
763
764 $wgOut->setPageTitle( wfMsg( 'blockedtitle' ) );
765 $wgOut->setRobotpolicy( 'noindex,nofollow' );
766 $wgOut->setArticleRelated( false );
767
768 $id = $wgUser->blockedBy();
769 $reason = $wgUser->blockedFor();
770 $ip = $wgIP;
771
772 if ( is_numeric( $id ) ) {
773 $name = User::whoIs( $id );
774 } else {
775 $name = $id;
776 }
777 $link = '[[' . $wgContLang->getNsText( NS_USER ) .
778 ":{$name}|{$name}]]";
779
780 $wgOut->addWikiText( wfMsg( 'blockedtext', $link, $reason, $ip, $name ) );
781 $wgOut->returnToMain( false );
782 }
783
784 /**
785 * @todo document
786 */
787 function userNotLoggedInPage() {
788 global $wgOut;
789
790 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
791 $wgOut->setRobotpolicy( 'noindex,nofollow' );
792 $wgOut->setArticleRelated( false );
793
794 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
795 $wgOut->returnToMain( false );
796 }
797
798 /**
799 * @todo document
800 */
801 function spamPage ( $match = false )
802 {
803 global $wgOut;
804 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
805 $wgOut->setRobotpolicy( 'noindex,nofollow' );
806 $wgOut->setArticleRelated( false );
807
808 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
809 if ( $match ) {
810 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
811 }
812 $wgOut->returnToMain( false );
813 }
814
815 /**
816 * Forks processes to scan the originating IP for an open proxy server
817 * MemCached can be used to skip IPs that have already been scanned
818 */
819 function proxyCheck() {
820 global $wgBlockOpenProxies, $wgProxyPorts, $wgProxyScriptPath;
821 global $wgIP, $wgUseMemCached, $wgMemc, $wgDBname, $wgProxyMemcExpiry;
822
823 if ( !$wgBlockOpenProxies ) {
824 return;
825 }
826
827 # Get MemCached key
828 $skip = false;
829 if ( $wgUseMemCached ) {
830 $mcKey = $wgDBname.':proxy:ip:'.$wgIP;
831 $mcValue = $wgMemc->get( $mcKey );
832 if ( $mcValue ) {
833 $skip = true;
834 }
835 }
836
837 # Fork the processes
838 if ( !$skip ) {
839 $title = Title::makeTitle( NS_SPECIAL, 'Blockme' );
840 $iphash = md5( $wgIP . $wgProxyKey );
841 $url = $title->getFullURL( 'ip='.$iphash );
842
843 foreach ( $wgProxyPorts as $port ) {
844 $params = implode( ' ', array(
845 escapeshellarg( $wgProxyScriptPath ),
846 escapeshellarg( $wgIP ),
847 escapeshellarg( $port ),
848 escapeshellarg( $url )
849 ));
850 exec( "php $params &>/dev/null &" );
851 }
852 # Set MemCached key
853 if ( $wgUseMemCached ) {
854 $wgMemc->set( $mcKey, 1, $wgProxyMemcExpiry );
855 }
856 }
857 }
858
859 /**
860 * @access private
861 * @todo document
862 */
863 function mergeChangesInto( &$text ){
864 $yourtext = $this->mArticle->fetchRevisionText();
865
866 $db =& wfGetDB( DB_MASTER );
867 $oldText = $this->mArticle->fetchRevisionText(
868 $db->timestamp( $this->edittime ),
869 'rev_timestamp' );
870
871 if(wfMerge($oldText, $text, $yourtext, $result)){
872 $text = $result;
873 return true;
874 } else {
875 return false;
876 }
877 }
878
879
880 function checkUnicodeCompliantBrowser() {
881 global $wgBrowserBlackList;
882 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
883 foreach ( $wgBrowserBlackList as $browser ) {
884 if ( preg_match($browser, $currentbrowser) ) {
885 return false;
886 }
887 }
888 return true;
889 }
890
891 /**
892 * Format an anchor fragment as it would appear for a given section name
893 * @param string $text
894 * @return string
895 * @access private
896 */
897 function sectionAnchor( $text ) {
898 $headline = Sanitizer::decodeCharReferences( $text );
899 # strip out HTML
900 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
901 $headline = trim( $headline );
902 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
903 $replacearray = array(
904 '%3A' => ':',
905 '%' => '.'
906 );
907 return str_replace(
908 array_keys( $replacearray ),
909 array_values( $replacearray ),
910 $sectionanchor );
911 }
912
913 /**
914 * Shows a bulletin board style toolbar for common editing functions.
915 * It can be disabled in the user preferences.
916 * The necessary JavaScript code can be found in style/wikibits.js.
917 */
918 function getEditToolbar() {
919 global $wgStylePath, $wgLang, $wgMimeType, $wgJsMimeType;
920
921 /**
922 * toolarray an array of arrays which each include the filename of
923 * the button image (without path), the opening tag, the closing tag,
924 * and optionally a sample text that is inserted between the two when no
925 * selection is highlighted.
926 * The tip text is shown when the user moves the mouse over the button.
927 *
928 * Already here are accesskeys (key), which are not used yet until someone
929 * can figure out a way to make them work in IE. However, we should make
930 * sure these keys are not defined on the edit page.
931 */
932 $toolarray=array(
933 array( 'image'=>'button_bold.png',
934 'open' => "\'\'\'",
935 'close' => "\'\'\'",
936 'sample'=> wfMsg('bold_sample'),
937 'tip' => wfMsg('bold_tip'),
938 'key' => 'B'
939 ),
940 array( 'image'=>'button_italic.png',
941 'open' => "\'\'",
942 'close' => "\'\'",
943 'sample'=> wfMsg('italic_sample'),
944 'tip' => wfMsg('italic_tip'),
945 'key' => 'I'
946 ),
947 array( 'image'=>'button_link.png',
948 'open' => '[[',
949 'close' => ']]',
950 'sample'=> wfMsg('link_sample'),
951 'tip' => wfMsg('link_tip'),
952 'key' => 'L'
953 ),
954 array( 'image'=>'button_extlink.png',
955 'open' => '[',
956 'close' => ']',
957 'sample'=> wfMsg('extlink_sample'),
958 'tip' => wfMsg('extlink_tip'),
959 'key' => 'X'
960 ),
961 array( 'image'=>'button_headline.png',
962 'open' => "\\n== ",
963 'close' => " ==\\n",
964 'sample'=> wfMsg('headline_sample'),
965 'tip' => wfMsg('headline_tip'),
966 'key' => 'H'
967 ),
968 array( 'image'=>'button_image.png',
969 'open' => '[['.$wgLang->getNsText(NS_IMAGE).":",
970 'close' => ']]',
971 'sample'=> wfMsg('image_sample'),
972 'tip' => wfMsg('image_tip'),
973 'key' => 'D'
974 ),
975 array( 'image' =>'button_media.png',
976 'open' => '[['.$wgLang->getNsText(NS_MEDIA).':',
977 'close' => ']]',
978 'sample'=> wfMsg('media_sample'),
979 'tip' => wfMsg('media_tip'),
980 'key' => 'M'
981 ),
982 array( 'image' =>'button_math.png',
983 'open' => "\\<math\\>",
984 'close' => "\\</math\\>",
985 'sample'=> wfMsg('math_sample'),
986 'tip' => wfMsg('math_tip'),
987 'key' => 'C'
988 ),
989 array( 'image' =>'button_nowiki.png',
990 'open' => "\\<nowiki\\>",
991 'close' => "\\</nowiki\\>",
992 'sample'=> wfMsg('nowiki_sample'),
993 'tip' => wfMsg('nowiki_tip'),
994 'key' => 'N'
995 ),
996 array( 'image' =>'button_sig.png',
997 'open' => '--~~~~',
998 'close' => '',
999 'sample'=> '',
1000 'tip' => wfMsg('sig_tip'),
1001 'key' => 'Y'
1002 ),
1003 array( 'image' =>'button_hr.png',
1004 'open' => "\\n----\\n",
1005 'close' => '',
1006 'sample'=> '',
1007 'tip' => wfMsg('hr_tip'),
1008 'key' => 'R'
1009 )
1010 );
1011 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1012
1013 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1014 foreach($toolarray as $tool) {
1015
1016 $image=$wgStylePath.'/common/images/'.$tool['image'];
1017 $open=$tool['open'];
1018 $close=$tool['close'];
1019 $sample = wfEscapeJsString( $tool['sample'] );
1020
1021 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1022 // Older browsers show a "speedtip" type message only for ALT.
1023 // Ideally these should be different, realistically they
1024 // probably don't need to be.
1025 $tip = wfEscapeJsString( $tool['tip'] );
1026
1027 #$key = $tool["key"];
1028
1029 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1030 }
1031
1032 $toolbar.="addInfobox('" . wfEscapeJsString( wfMsg( "infobox" ) ) .
1033 "','" . wfEscapeJsString( wfMsg( "infobox_alert" ) ) . "');\n";
1034 $toolbar.="document.writeln(\"</div>\");\n";
1035
1036 $toolbar.="/*]]>*/\n</script>";
1037 return $toolbar;
1038 }
1039
1040 /**
1041 * Output preview text only. This can be sucked into the edit page
1042 * via JavaScript, and saves the server time rendering the skin as
1043 * well as theoretically being more robust on the client (doesn't
1044 * disturb the edit box's undo history, won't eat your text on
1045 * failure, etc).
1046 *
1047 * @todo This doesn't include category or interlanguage links.
1048 * Would need to enhance it a bit, maybe wrap them in XML
1049 * or something... that might also require more skin
1050 * initialization, so check whether that's a problem.
1051 */
1052 function livePreview() {
1053 global $wgOut;
1054 $wgOut->disable();
1055 header( 'Content-type: text/xml' );
1056 header( 'Cache-control: no-cache' );
1057 # FIXME
1058 echo $this->getPreviewText( false, false );
1059 }
1060
1061
1062 /**
1063 * Get a diff between the current contents of the edit box and the
1064 * version of the page we're editing from.
1065 *
1066 * If this is a section edit, we'll replace the section as for final
1067 * save and then make a comparison.
1068 *
1069 * @return string HTML
1070 */
1071 function getDiff() {
1072 require_once( 'DifferenceEngine.php' );
1073 $oldtext = $this->mArticle->getContent( true );
1074 $newtext = $this->mArticle->getTextOfLastEditWithSectionReplacedOrAdded(
1075 $this->section, $this->textbox1, $this->summary, $this->edittime );
1076 $oldtitle = wfMsg( 'currentrev' );
1077 $newtitle = wfMsg( 'yourtext' );
1078 if ( $oldtext != wfMsg( 'noarticletext' ) || $newtext != '' ) {
1079 $difftext = DifferenceEngine::getDiff( $oldtext, $newtext, $oldtitle, $newtitle );
1080 }
1081
1082 return '<div id="wikiDiff">' . $difftext . '</div>';
1083 }
1084
1085 }
1086
1087 ?>