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