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