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