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