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