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