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