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