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