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