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