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