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