3e8c46e0c459d9ad088e90be34258be0be477fa1
[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 var $isConflict = false;
21 var $isCssJsSubpage = false;
22 var $deletedSinceEdit = false;
23 var $formtype;
24 var $firsttime;
25 var $lastDelete;
26 var $mTokenOk = true;
27 var $tooBig = false;
28 var $kblength = false;
29 var $missingComment = false;
30 var $missingSummary = false;
31 var $allowBlankSummary = false;
32 var $autoSumm = '';
33
34 # Form values
35 var $save = false, $preview = false, $diff = false;
36 var $minoredit = false, $watchthis = false, $recreate = false;
37 var $textbox1 = '', $textbox2 = '', $summary = '';
38 var $edittime = '', $section = '', $starttime = '';
39 var $oldid = 0, $editintro = '', $scrolltop = null;
40
41 /**
42 * @todo document
43 * @param $article
44 */
45 function EditPage( $article ) {
46 $this->mArticle =& $article;
47 global $wgTitle;
48 $this->mTitle =& $wgTitle;
49 }
50
51 /**
52 * This is the function that extracts metadata from the article body on the first view.
53 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
54 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
55 */
56 function extractMetaDataFromArticle () {
57 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
58 $this->mMetaData = '' ;
59 if ( !$wgUseMetadataEdit ) return ;
60 if ( $wgMetadataWhitelist == '' ) return ;
61 $s = '' ;
62 $t = $this->mArticle->getContent();
63
64 # MISSING : <nowiki> filtering
65
66 # Categories and language links
67 $t = explode ( "\n" , $t ) ;
68 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY ) ) ;
69 $cat = $ll = array() ;
70 foreach ( $t AS $key => $x )
71 {
72 $y = trim ( strtolower ( $x ) ) ;
73 while ( substr ( $y , 0 , 2 ) == '[[' )
74 {
75 $y = explode ( ']]' , trim ( $x ) ) ;
76 $first = array_shift ( $y ) ;
77 $first = explode ( ':' , $first ) ;
78 $ns = array_shift ( $first ) ;
79 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
80 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
81 {
82 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
83 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
84 else $ll[] = $add ;
85 $x = implode ( ']]' , $y ) ;
86 $t[$key] = $x ;
87 $y = trim ( strtolower ( $x ) ) ;
88 }
89 }
90 }
91 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
92 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
93 $t = implode ( "\n" , $t ) ;
94
95 # Load whitelist
96 $sat = array () ; # stand-alone-templates; must be lowercase
97 $wl_title = Title::newFromText ( $wgMetadataWhitelist ) ;
98 $wl_article = new Article ( $wl_title ) ;
99 $wl = explode ( "\n" , $wl_article->getContent() ) ;
100 foreach ( $wl AS $x )
101 {
102 $isentry = false ;
103 $x = trim ( $x ) ;
104 while ( substr ( $x , 0 , 1 ) == '*' )
105 {
106 $isentry = true ;
107 $x = trim ( substr ( $x , 1 ) ) ;
108 }
109 if ( $isentry )
110 {
111 $sat[] = strtolower ( $x ) ;
112 }
113
114 }
115
116 # Templates, but only some
117 $t = explode ( '{{' , $t ) ;
118 $tl = array () ;
119 foreach ( $t AS $key => $x )
120 {
121 $y = explode ( '}}' , $x , 2 ) ;
122 if ( count ( $y ) == 2 )
123 {
124 $z = $y[0] ;
125 $z = explode ( '|' , $z ) ;
126 $tn = array_shift ( $z ) ;
127 if ( in_array ( strtolower ( $tn ) , $sat ) )
128 {
129 $tl[] = '{{' . $y[0] . '}}' ;
130 $t[$key] = $y[1] ;
131 $y = explode ( '}}' , $y[1] , 2 ) ;
132 }
133 else $t[$key] = '{{' . $x ;
134 }
135 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
136 else $t[$key] = $x ;
137 }
138 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
139 $t = implode ( '' , $t ) ;
140
141 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
142 $this->mArticle->mContent = $t ;
143 $this->mMetaData = $s ;
144 }
145
146 function submit() {
147 $this->edit();
148 }
149
150 /**
151 * This is the function that gets called for "action=edit". It
152 * sets up various member variables, then passes execution to
153 * another function, usually showEditForm()
154 *
155 * The edit form is self-submitting, so that when things like
156 * preview and edit conflicts occur, we get the same form back
157 * with the extra stuff added. Only when the final submission
158 * is made and all is well do we actually save and redirect to
159 * the newly-edited page.
160 */
161 function edit() {
162 global $wgOut, $wgUser, $wgRequest, $wgTitle;
163 global $wgEmailConfirmToEdit;
164
165 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
166 return;
167
168 $fname = 'EditPage::edit';
169 wfProfileIn( $fname );
170 wfDebug( "$fname: enter\n" );
171
172 // this is not an article
173 $wgOut->setArticleFlag(false);
174
175 $this->importFormData( $wgRequest );
176 $this->firsttime = false;
177
178 if( $this->live ) {
179 $this->livePreview();
180 wfProfileOut( $fname );
181 return;
182 }
183
184 if ( ! $this->mTitle->userCanEdit() ) {
185 wfDebug( "$fname: user can't edit\n" );
186 $wgOut->readOnlyPage( $this->mArticle->getContent(), true );
187 wfProfileOut( $fname );
188 return;
189 }
190 wfDebug( "$fname: Checking blocks\n" );
191 if ( !$this->preview && !$this->diff && $wgUser->isBlockedFrom( $this->mTitle, !$this->save ) ) {
192 # When previewing, don't check blocked state - will get caught at save time.
193 # Also, check when starting edition is done against slave to improve performance.
194 wfDebug( "$fname: user is blocked\n" );
195 $wgOut->blockedPage();
196 wfProfileOut( $fname );
197 return;
198 }
199 if ( !$wgUser->isAllowed('edit') ) {
200 if ( $wgUser->isAnon() ) {
201 wfDebug( "$fname: user must log in\n" );
202 $this->userNotLoggedInPage();
203 wfProfileOut( $fname );
204 return;
205 } else {
206 wfDebug( "$fname: read-only page\n" );
207 $wgOut->readOnlyPage( $this->mArticle->getContent(), true );
208 wfProfileOut( $fname );
209 return;
210 }
211 }
212 if ($wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed()) {
213 wfDebug("$fname: user must confirm e-mail address\n");
214 $this->userNotConfirmedPage();
215 wfProfileOut($fname);
216 return;
217 }
218 if ( !$this->mTitle->userCan( 'create' ) && !$this->mTitle->exists() ) {
219 wfDebug( "$fname: no create permission\n" );
220 $this->noCreatePermission();
221 wfProfileOut( $fname );
222 return;
223 }
224 if ( wfReadOnly() ) {
225 wfDebug( "$fname: read-only mode is engaged\n" );
226 if( $this->save || $this->preview ) {
227 $this->formtype = 'preview';
228 } else if ( $this->diff ) {
229 $this->formtype = 'diff';
230 } else {
231 $wgOut->readOnlyPage( $this->mArticle->getContent() );
232 wfProfileOut( $fname );
233 return;
234 }
235 } else {
236 if ( $this->save ) {
237 $this->formtype = 'save';
238 } else if ( $this->preview ) {
239 $this->formtype = 'preview';
240 } else if ( $this->diff ) {
241 $this->formtype = 'diff';
242 } else { # First time through
243 $this->firsttime = true;
244 if( $this->previewOnOpen() ) {
245 $this->formtype = 'preview';
246 } else {
247 $this->extractMetaDataFromArticle () ;
248 $this->formtype = 'initial';
249 }
250 }
251 }
252
253 wfProfileIn( "$fname-business-end" );
254
255 $this->isConflict = false;
256 // css / js subpages of user pages get a special treatment
257 $this->isCssJsSubpage = $wgTitle->isCssJsSubpage();
258 $this->isValidCssJsSubpage = $wgTitle->isValidCssJsSubpage();
259
260 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
261 * no matter it's current state
262 */
263 $this->deletedSinceEdit = false;
264 if ( $this->edittime != '' ) {
265 /* Note that we rely on logging table, which hasn't been always there,
266 * but that doesn't matter, because this only applies to brand new
267 * deletes. This is done on every preview and save request. Move it further down
268 * to only perform it on saves
269 */
270 if ( $this->mTitle->isDeleted() ) {
271 $this->lastDelete = $this->getLastDelete();
272 if ( !is_null($this->lastDelete) ) {
273 $deletetime = $this->lastDelete->log_timestamp;
274 if ( ($deletetime - $this->starttime) > 0 ) {
275 $this->deletedSinceEdit = true;
276 }
277 }
278 }
279 }
280
281 if(!$this->mTitle->getArticleID() && ('initial' == $this->formtype || $this->firsttime )) { # new article
282 $this->showIntro();
283 }
284 if( $this->mTitle->isTalkPage() ) {
285 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
286 }
287
288 # Attempt submission here. This will check for edit conflicts,
289 # and redundantly check for locked database, blocked IPs, etc.
290 # that edit() already checked just in case someone tries to sneak
291 # in the back door with a hand-edited submission URL.
292
293 if ( 'save' == $this->formtype ) {
294 if ( !$this->attemptSave() ) {
295 wfProfileOut( "$fname-business-end" );
296 wfProfileOut( $fname );
297 return;
298 }
299 }
300
301 # First time through: get contents, set time for conflict
302 # checking, etc.
303 if ( 'initial' == $this->formtype || $this->firsttime ) {
304 $this->initialiseForm();
305 }
306
307 $this->showEditForm();
308 wfProfileOut( "$fname-business-end" );
309 wfProfileOut( $fname );
310 }
311
312 /**
313 * Return true if this page should be previewed when the edit form
314 * is initially opened.
315 * @return bool
316 * @access private
317 */
318 function previewOnOpen() {
319 global $wgUser;
320 return $this->section != 'new' &&
321 ( ( $wgUser->getOption( 'previewonfirst' ) && $this->mTitle->exists() ) ||
322 ( $this->mTitle->getNamespace() == NS_CATEGORY &&
323 !$this->mTitle->exists() ) );
324 }
325
326 /**
327 * @todo document
328 */
329 function importFormData( &$request ) {
330 global $wgLang ;
331 $fname = 'EditPage::importFormData';
332 wfProfileIn( $fname );
333
334 if( $request->wasPosted() ) {
335 # These fields need to be checked for encoding.
336 # Also remove trailing whitespace, but don't remove _initial_
337 # whitespace from the text boxes. This may be significant formatting.
338 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
339 $this->textbox2 = $this->safeUnicodeInput( $request, 'wpTextbox2' );
340 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
341 # Truncate for whole multibyte characters. +5 bytes for ellipsis
342 $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
343
344 $this->edittime = $request->getVal( 'wpEdittime' );
345 $this->starttime = $request->getVal( 'wpStarttime' );
346
347 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
348
349 if( is_null( $this->edittime ) ) {
350 # If the form is incomplete, force to preview.
351 wfDebug( "$fname: Form data appears to be incomplete\n" );
352 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
353 $this->preview = true;
354 } else {
355 /* Fallback for live preview */
356 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
357 $this->diff = $request->getCheck( 'wpDiff' );
358
359 if( !$this->preview ) {
360 if ( $this->tokenOk( $request ) ) {
361 # Some browsers will not report any submit button
362 # if the user hits enter in the comment box.
363 # The unmarked state will be assumed to be a save,
364 # if the form seems otherwise complete.
365 wfDebug( "$fname: Passed token check.\n" );
366 } else {
367 # Page might be a hack attempt posted from
368 # an external site. Preview instead of saving.
369 wfDebug( "$fname: Failed token check; forcing preview\n" );
370 $this->preview = true;
371 }
372 }
373 }
374 $this->save = ! ( $this->preview OR $this->diff );
375 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
376 $this->edittime = null;
377 }
378
379 if( !preg_match( '/^\d{14}$/', $this->starttime )) {
380 $this->starttime = null;
381 }
382
383 $this->recreate = $request->getCheck( 'wpRecreate' );
384
385 $this->minoredit = $request->getCheck( 'wpMinoredit' );
386 $this->watchthis = $request->getCheck( 'wpWatchthis' );
387 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' );
388 $this->autoSumm = $request->getText( 'wpAutoSummary' );
389 } else {
390 # Not a posted form? Start with nothing.
391 wfDebug( "$fname: Not a posted form.\n" );
392 $this->textbox1 = '';
393 $this->textbox2 = '';
394 $this->mMetaData = '';
395 $this->summary = '';
396 $this->edittime = '';
397 $this->starttime = wfTimestampNow();
398 $this->preview = false;
399 $this->save = false;
400 $this->diff = false;
401 $this->minoredit = false;
402 $this->watchthis = false;
403 $this->recreate = false;
404 }
405
406 $this->oldid = $request->getInt( 'oldid' );
407
408 # Section edit can come from either the form or a link
409 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
410
411 $this->live = $request->getCheck( 'live' );
412 $this->editintro = $request->getText( 'editintro' );
413
414 wfProfileOut( $fname );
415 }
416
417 /**
418 * Make sure the form isn't faking a user's credentials.
419 *
420 * @param WebRequest $request
421 * @return bool
422 * @access private
423 */
424 function tokenOk( &$request ) {
425 global $wgUser;
426 if( $wgUser->isAnon() ) {
427 # Anonymous users may not have a session
428 # open. Don't tokenize.
429 $this->mTokenOk = true;
430 } else {
431 $this->mTokenOk = $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
432 }
433 return $this->mTokenOk;
434 }
435
436 function showIntro() {
437 global $wgOut, $wgUser;
438 $addstandardintro=true;
439 if($this->editintro) {
440 $introtitle=Title::newFromText($this->editintro);
441 if(isset($introtitle) && $introtitle->userCanRead()) {
442 $rev=Revision::newFromTitle($introtitle);
443 if($rev) {
444 $wgOut->addSecondaryWikiText($rev->getText());
445 $addstandardintro=false;
446 }
447 }
448 }
449 if($addstandardintro) {
450 if ( $wgUser->isLoggedIn() )
451 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
452 else
453 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
454 }
455 }
456
457 /**
458 * Attempt submission
459 * @return bool false if output is done, true if the rest of the form should be displayed
460 */
461 function attemptSave() {
462 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
463 global $wgMaxArticleSize;
464
465 $fname = 'EditPage::attemptSave';
466 wfProfileIn( $fname );
467 wfProfileIn( "$fname-checks" );
468
469 # Reintegrate metadata
470 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
471 $this->mMetaData = '' ;
472
473 # Check for spam
474 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
475 $this->spamPage ( $matches[0] );
476 wfProfileOut( "$fname-checks" );
477 wfProfileOut( $fname );
478 return false;
479 }
480 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
481 # Error messages or other handling should be performed by the filter function
482 wfProfileOut( $fname );
483 wfProfileOut( "$fname-checks" );
484 return false;
485 }
486 if ( !wfRunHooks( 'EditFilter', array( &$this, $this->textbox1, $this->section ) ) ) {
487 # Error messages or other handling should be performed by the filter function
488 wfProfileOut( $fname );
489 wfProfileOut( "$fname-checks" );
490 return false;
491 }
492 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
493 # Check block state against master, thus 'false'.
494 $this->blockedIPpage();
495 wfProfileOut( "$fname-checks" );
496 wfProfileOut( $fname );
497 return false;
498 }
499 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
500 if ( $this->kblength > $wgMaxArticleSize ) {
501 // Error will be displayed by showEditForm()
502 $this->tooBig = true;
503 wfProfileOut( "$fname-checks" );
504 wfProfileOut( $fname );
505 return true;
506 }
507
508 if ( !$wgUser->isAllowed('edit') ) {
509 if ( $wgUser->isAnon() ) {
510 $this->userNotLoggedInPage();
511 wfProfileOut( "$fname-checks" );
512 wfProfileOut( $fname );
513 return false;
514 }
515 else {
516 $wgOut->readOnlyPage();
517 wfProfileOut( "$fname-checks" );
518 wfProfileOut( $fname );
519 return false;
520 }
521 }
522
523 if ( wfReadOnly() ) {
524 $wgOut->readOnlyPage();
525 wfProfileOut( "$fname-checks" );
526 wfProfileOut( $fname );
527 return false;
528 }
529 if ( $wgUser->pingLimiter() ) {
530 $wgOut->rateLimited();
531 wfProfileOut( "$fname-checks" );
532 wfProfileOut( $fname );
533 return false;
534 }
535
536 # If the article has been deleted while editing, don't save it without
537 # confirmation
538 if ( $this->deletedSinceEdit && !$this->recreate ) {
539 wfProfileOut( "$fname-checks" );
540 wfProfileOut( $fname );
541 return true;
542 }
543
544 wfProfileOut( "$fname-checks" );
545
546 # If article is new, insert it.
547 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
548 if ( 0 == $aid ) {
549 // Late check for create permission, just in case *PARANOIA*
550 if ( !$this->mTitle->userCan( 'create' ) ) {
551 wfDebug( "$fname: no create permission\n" );
552 $this->noCreatePermission();
553 wfProfileOut( $fname );
554 return;
555 }
556
557 # Don't save a new article if it's blank.
558 if ( ( '' == $this->textbox1 ) ) {
559 $wgOut->redirect( $this->mTitle->getFullURL() );
560 wfProfileOut( $fname );
561 return false;
562 }
563
564 $isComment=($this->section=='new');
565 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
566 $this->minoredit, $this->watchthis, false, $isComment);
567
568 wfProfileOut( $fname );
569 return false;
570 }
571
572 # Article exists. Check for edit conflict.
573
574 $this->mArticle->clear(); # Force reload of dates, etc.
575 $this->mArticle->forUpdate( true ); # Lock the article
576
577 if( $this->mArticle->getTimestamp() != $this->edittime ) {
578 $this->isConflict = true;
579 if( $this->section == 'new' ) {
580 if( $this->mArticle->getUserText() == $wgUser->getName() &&
581 $this->mArticle->getComment() == $this->summary ) {
582 // Probably a duplicate submission of a new comment.
583 // This can happen when squid resends a request after
584 // a timeout but the first one actually went through.
585 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
586 } else {
587 // New comment; suppress conflict.
588 $this->isConflict = false;
589 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
590 }
591 }
592 }
593 $userid = $wgUser->getID();
594
595 if ( $this->isConflict) {
596 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
597 $this->mArticle->getTimestamp() . "'\n" );
598 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
599 }
600 else {
601 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
602 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
603 }
604 if( is_null( $text ) ) {
605 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
606 $this->isConflict = true;
607 $text = $this->textbox1;
608 }
609
610 # Suppress edit conflict with self, except for section edits where merging is required.
611 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
612 wfDebug( "Suppressing edit conflict, same user.\n" );
613 $this->isConflict = false;
614 } else {
615 # switch from section editing to normal editing in edit conflict
616 if($this->isConflict) {
617 # Attempt merge
618 if( $this->mergeChangesInto( $text ) ){
619 // Successful merge! Maybe we should tell the user the good news?
620 $this->isConflict = false;
621 wfDebug( "Suppressing edit conflict, successful merge.\n" );
622 } else {
623 $this->section = '';
624 $this->textbox1 = $text;
625 wfDebug( "Keeping edit conflict, failed merge.\n" );
626 }
627 }
628 }
629
630 if ( $this->isConflict ) {
631 wfProfileOut( $fname );
632 return true;
633 }
634
635 # Handle the user preference to force summaries here
636 if( $this->section != 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary' ) ) {
637 if( md5( $this->summary ) == $this->autoSumm ) {
638 $this->missingSummary = true;
639 wfProfileOut( $fname );
640 return( true );
641 }
642 }
643
644 # All's well
645 wfProfileIn( "$fname-sectionanchor" );
646 $sectionanchor = '';
647 if( $this->section == 'new' ) {
648 if ( $this->textbox1 == '' ) {
649 $this->missingComment = true;
650 return true;
651 }
652 if( $this->summary != '' ) {
653 $sectionanchor = $this->sectionAnchor( $this->summary );
654 }
655 } elseif( $this->section != '' ) {
656 # Try to get a section anchor from the section source, redirect to edited section if header found
657 # XXX: might be better to integrate this into Article::replaceSection
658 # for duplicate heading checking and maybe parsing
659 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
660 # we can't deal with anchors, includes, html etc in the header for now,
661 # headline would need to be parsed to improve this
662 if($hasmatch and strlen($matches[2]) > 0) {
663 $sectionanchor = $this->sectionAnchor( $matches[2] );
664 }
665 }
666 wfProfileOut( "$fname-sectionanchor" );
667
668 // Save errors may fall down to the edit form, but we've now
669 // merged the section into full text. Clear the section field
670 // so that later submission of conflict forms won't try to
671 // replace that into a duplicated mess.
672 $this->textbox1 = $text;
673 $this->section = '';
674
675 // Check for length errors again now that the section is merged in
676 $this->kblength = (int)(strlen( $text ) / 1024);
677 if ( $this->kblength > $wgMaxArticleSize ) {
678 $this->tooBig = true;
679 wfProfileOut( $fname );
680 return true;
681 }
682
683 # update the article here
684 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
685 $this->watchthis, '', $sectionanchor ) ) {
686 wfProfileOut( $fname );
687 return false;
688 } else {
689 $this->isConflict = true;
690 }
691 wfProfileOut( $fname );
692 return true;
693 }
694
695 /**
696 * Initialise form fields in the object
697 * Called on the first invocation, e.g. when a user clicks an edit link
698 */
699 function initialiseForm() {
700 $this->edittime = $this->mArticle->getTimestamp();
701 $this->textbox1 = $this->mArticle->getContent();
702 $this->summary = '';
703 if ( !$this->mArticle->exists() && $this->mArticle->mTitle->getNamespace() == NS_MEDIAWIKI )
704 $this->textbox1 = wfMsgWeirdKey ( $this->mArticle->mTitle->getText() ) ;
705 wfProxyCheck();
706 }
707
708 /**
709 * Send the edit form and related headers to $wgOut
710 * @param $formCallback Optional callable that takes an OutputPage
711 * parameter; will be called during form output
712 * near the top, for captchas and the like.
713 */
714 function showEditForm( $formCallback=null ) {
715 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
716
717 $fname = 'EditPage::showEditForm';
718 wfProfileIn( $fname );
719
720 $sk =& $wgUser->getSkin();
721
722 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
723
724 $wgOut->setRobotpolicy( 'noindex,nofollow' );
725
726 # Enabled article-related sidebar, toplinks, etc.
727 $wgOut->setArticleRelated( true );
728
729 if ( $this->isConflict ) {
730 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
731 $wgOut->setPageTitle( $s );
732 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
733
734 $this->textbox2 = $this->textbox1;
735 $this->textbox1 = $this->mArticle->getContent();
736 $this->edittime = $this->mArticle->getTimestamp();
737 } else {
738
739 if( $this->section != '' ) {
740 if( $this->section == 'new' ) {
741 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
742 } else {
743 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
744 if( !$this->preview && !$this->diff ) {
745 preg_match( "/^(=+)(.+)\\1/mi",
746 $this->textbox1,
747 $matches );
748 if( !empty( $matches[2] ) ) {
749 $this->summary = "/* ". trim($matches[2])." */ ";
750 }
751 }
752 }
753 } else {
754 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
755 }
756 $wgOut->setPageTitle( $s );
757
758 if ( $this->missingComment ) {
759 $wgOut->addWikiText( wfMsg( 'missingcommenttext' ) );
760 }
761
762 if( $this->missingSummary ) {
763 $wgOut->addWikiText( wfMsg( 'missingsummary' ) );
764 }
765
766 if ( !$this->checkUnicodeCompliantBrowser() ) {
767 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
768 }
769 if ( isset( $this->mArticle )
770 && isset( $this->mArticle->mRevision )
771 && !$this->mArticle->mRevision->isCurrent() ) {
772 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
773 $wgOut->addWikiText( wfMsg( 'editingold' ) );
774 }
775 }
776
777 if( wfReadOnly() ) {
778 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
779 } elseif( $wgUser->isAnon() && $this->formtype != 'preview' ) {
780 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
781 } else {
782 if( $this->isCssJsSubpage && $this->formtype != 'preview' ) {
783 # Check the skin exists
784 if( $this->isValidCssJsSubpage ) {
785 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
786 } else {
787 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $this->mTitle->getSkinFromCssJsSubpage() ) );
788 }
789 }
790 }
791
792 if( $this->mTitle->isProtected( 'edit' ) ) {
793 if( $this->mTitle->isSemiProtected() ) {
794 $notice = wfMsg( 'semiprotectedpagewarning' );
795 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) || $notice == '-' ) {
796 $notice = '';
797 }
798 } else {
799 $notice = wfMsg( 'protectedpagewarning' );
800 }
801 $wgOut->addWikiText( $notice );
802 }
803
804 if ( $this->kblength === false ) {
805 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
806 }
807 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
808 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize ) );
809 } elseif( $this->kblength > 29 ) {
810 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ) );
811 }
812
813 $rows = $wgUser->getOption( 'rows' );
814 $cols = $wgUser->getOption( 'cols' );
815
816 $ew = $wgUser->getOption( 'editwidth' );
817 if ( $ew ) $ew = " style=\"width:100%\"";
818 else $ew = '';
819
820 $q = 'action=submit';
821 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
822 $action = $this->mTitle->escapeLocalURL( $q );
823
824 $summary = wfMsg('summary');
825 $subject = wfMsg('subject');
826 $minor = wfMsg('minoredit');
827 $watchthis = wfMsg ('watchthis');
828
829 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
830 wfMsg('cancel') );
831 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsg( 'edithelppage' ));
832 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
833 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
834 htmlspecialchars( wfMsg( 'newwindow' ) );
835
836 global $wgRightsText;
837 $copywarn = "<div id=\"editpage-copywarn\">\n" .
838 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
839 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
840 $wgRightsText ) . "\n</div>";
841
842 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
843 # prepare toolbar for edit buttons
844 $toolbar = $this->getEditToolbar();
845 } else {
846 $toolbar = '';
847 }
848
849 // activate checkboxes if user wants them to be always active
850 if( !$this->preview && !$this->diff ) {
851 # Sort out the "watch" checkbox
852 if( $wgUser->getOption( 'watchdefault' ) ) {
853 # Watch all edits
854 $this->watchthis = true;
855 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
856 # Watch creations
857 $this->watchthis = true;
858 } elseif( $this->mTitle->userIsWatching() ) {
859 # Already watched
860 $this->watchthis = true;
861 }
862
863 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
864 }
865
866 $minoredithtml = '';
867
868 if ( $wgUser->isAllowed('minoredit') ) {
869 $minoredithtml =
870 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
871 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
872 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
873 }
874
875 $watchhtml = '';
876
877 if ( $wgUser->isLoggedIn() ) {
878 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
879 ($this->watchthis?" checked='checked'":"").
880 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />".
881 "<label for='wpWatchthis' title=\"" .
882 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>";
883 }
884
885 $checkboxhtml = $minoredithtml . $watchhtml;
886
887 if ( $wgUser->getOption( 'previewontop' ) ) {
888
889 if ( 'preview' == $this->formtype ) {
890 $this->showPreview();
891 } else {
892 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
893 }
894
895 if ( 'diff' == $this->formtype ) {
896 $wgOut->addHTML( $this->getDiff() );
897 }
898 }
899
900
901 # if this is a comment, show a subject line at the top, which is also the edit summary.
902 # Otherwise, show a summary field at the bottom
903 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
904 if( $this->section == 'new' ) {
905 $commentsubject="<span id='wpSummaryLabel'><label for='wpSummary'>{$subject}:</label></span> <div class='editOptions'><input tabindex='1' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
906 $editsummary = '';
907 } else {
908 $commentsubject = '';
909 $editsummary="<span id='wpSummaryLabel'><label for='wpSummary'>{$summary}:</label></span> <div class='editOptions'><input tabindex='2' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
910 }
911
912 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
913 if( !$this->preview && !$this->diff ) {
914 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
915 }
916 $templates = $this->formatTemplates();
917
918 global $wgUseMetadataEdit ;
919 if ( $wgUseMetadataEdit ) {
920 $metadata = $this->mMetaData ;
921 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
922 $helppage = Title::newFromText( wfMsg( "metadata_page" ) ) ;
923 $top = wfMsg( 'metadata', $helppage->getLocalURL() );
924 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
925 }
926 else $metadata = "" ;
927
928 $hidden = '';
929 $recreate = '';
930 if ($this->deletedSinceEdit) {
931 if ( 'save' != $this->formtype ) {
932 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
933 } else {
934 // Hide the toolbar and edit area, use can click preview to get it back
935 // Add an confirmation checkbox and explanation.
936 $toolbar = '';
937 $hidden = 'type="hidden" style="display:none;"';
938 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
939 $recreate .=
940 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
941 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
942 }
943 }
944
945 $temp = array(
946 'id' => 'wpSave',
947 'name' => 'wpSave',
948 'type' => 'submit',
949 'tabindex' => '5',
950 'value' => wfMsg('savearticle'),
951 'accesskey' => wfMsg('accesskey-save'),
952 'title' => wfMsg('tooltip-save'),
953 );
954 $buttons['save'] = wfElement('input', $temp, '');
955 $temp = array(
956 'id' => 'wpDiff',
957 'name' => 'wpDiff',
958 'type' => 'submit',
959 'tabindex' => '7',
960 'value' => wfMsg('showdiff'),
961 'accesskey' => wfMsg('accesskey-diff'),
962 'title' => wfMsg('tooltip-diff'),
963 );
964 $buttons['diff'] = wfElement('input', $temp, '');
965
966 global $wgLivePreview;
967 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
968 $temp = array(
969 'id' => 'wpPreview',
970 'name' => 'wpPreview',
971 'type' => 'submit',
972 'tabindex' => '6',
973 'value' => wfMsg('showpreview'),
974 'accesskey' => '',
975 'title' => wfMsg('tooltip-preview'),
976 'style' => 'display: none;',
977 );
978 $buttons['preview'] = wfElement('input', $temp, '');
979 $temp = array(
980 'id' => 'wpLivePreview',
981 'name' => 'wpLivePreview',
982 'type' => 'submit',
983 'tabindex' => '6',
984 'value' => wfMsg('showlivepreview'),
985 'accesskey' => wfMsg('accesskey-preview'),
986 'title' => '',
987 'onclick' => $this->doLivePreviewScript(),
988 );
989 $buttons['live'] = wfElement('input', $temp, '');
990 } else {
991 $temp = array(
992 'id' => 'wpPreview',
993 'name' => 'wpPreview',
994 'type' => 'submit',
995 'tabindex' => '6',
996 'value' => wfMsg('showpreview'),
997 'accesskey' => wfMsg('accesskey-preview'),
998 'title' => wfMsg('tooltip-preview'),
999 );
1000 $buttons['preview'] = wfElement('input', $temp, '');
1001 $buttons['live'] = '';
1002 }
1003
1004 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1005 ? ""
1006 : "<input type='hidden' name=\"safemode\" value='1' />\n";
1007
1008 $wgOut->addHTML( <<<END
1009 {$toolbar}
1010 <form id="editform" name="editform" method="post" action="$action"
1011 enctype="multipart/form-data">
1012 END
1013 );
1014
1015 if( is_callable( $formCallback ) ) {
1016 call_user_func_array( $formCallback, array( &$wgOut ) );
1017 }
1018
1019 // Put these up at the top to ensure they aren't lost on early form submission
1020 $wgOut->addHTML( "
1021 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1022 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1023 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1024 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1025
1026 $wgOut->addHTML( <<<END
1027 $recreate
1028 {$commentsubject}
1029 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1030 cols='{$cols}'{$ew} $hidden>
1031 END
1032 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
1033 "
1034 </textarea>
1035 " );
1036
1037 $wgOut->addWikiText( $copywarn );
1038 $wgOut->addHTML( "
1039 {$metadata}
1040 {$editsummary}
1041 {$checkboxhtml}
1042 {$safemodehtml}
1043 ");
1044
1045 $wgOut->addHTML("
1046 <div class='editButtons'>
1047 {$buttons['save']}
1048 {$buttons['preview']}
1049 {$buttons['live']}
1050 {$buttons['diff']}
1051 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1052 </div><!-- editButtons -->
1053 </div><!-- editOptions -->");
1054
1055 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1056
1057 $wgOut->addHTML( "
1058 <div class='templatesUsed'>
1059 {$templates}
1060 </div>
1061 " );
1062
1063 if ( $wgUser->isLoggedIn() ) {
1064 /**
1065 * To make it harder for someone to slip a user a page
1066 * which submits an edit form to the wiki without their
1067 * knowledge, a random token is associated with the login
1068 * session. If it's not passed back with the submission,
1069 * we won't save the page, or render user JavaScript and
1070 * CSS previews.
1071 */
1072 $token = htmlspecialchars( $wgUser->editToken() );
1073 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1074 }
1075
1076 # If a blank edit summary was previously provided, and the appropriate
1077 # user preference is active, pass a hidden tag here. This will stop the
1078 # user being bounced back more than once in the event that a summary
1079 # is not required.
1080 if( $this->missingSummary ) {
1081 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1082 }
1083
1084 # For a bit more sophisticated detection of blank summaries, hash the
1085 # automatic one and pass that in a hidden field.
1086 $autosumm = md5( $this->summary );
1087 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpAutoSummary\" value=\"$autosumm\" />\n" );
1088
1089 if ( $this->isConflict ) {
1090 require_once( "DifferenceEngine.php" );
1091 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1092
1093 $de = new DifferenceEngine( $this->mTitle );
1094 $de->setText( $this->textbox2, $this->textbox1 );
1095 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1096
1097 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1098 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1099 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1100 }
1101 $wgOut->addHTML( "</form>\n" );
1102 if ( !$wgUser->getOption( 'previewontop' ) ) {
1103
1104 if ( $this->formtype == 'preview') {
1105 $this->showPreview();
1106 } else {
1107 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1108 }
1109
1110 if ( $this->formtype == 'diff') {
1111 $wgOut->addHTML( $this->getDiff() );
1112 }
1113
1114 }
1115
1116 wfProfileOut( $fname );
1117 }
1118
1119 /**
1120 * Append preview output to $wgOut.
1121 * Includes category rendering if this is a category page.
1122 * @access private
1123 */
1124 function showPreview() {
1125 global $wgOut;
1126 $wgOut->addHTML( '<div id="wikiPreview">' );
1127 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1128 $this->mArticle->openShowCategory();
1129 }
1130 $previewOutput = $this->getPreviewText();
1131 $wgOut->addHTML( $previewOutput );
1132 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1133 $this->mArticle->closeShowCategory();
1134 }
1135 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
1136 $wgOut->addHTML( '</div>' );
1137 }
1138
1139 /**
1140 * Prepare a list of templates used by this page. Returns HTML.
1141 */
1142 function formatTemplates() {
1143 global $wgUser;
1144
1145 $fname = 'EditPage::formatTemplates';
1146 wfProfileIn( $fname );
1147
1148 $sk =& $wgUser->getSkin();
1149
1150 $outText = '';
1151 $templates = $this->mArticle->getUsedTemplates();
1152 if ( count( $templates ) > 0 ) {
1153 # Do a batch existence check
1154 $batch = new LinkBatch;
1155 foreach( $templates as $title ) {
1156 $batch->addObj( $title );
1157 }
1158 $batch->execute();
1159
1160 # Construct the HTML
1161 $outText = '<br />'. wfMsg( 'templatesused' ) . '<ul>';
1162 foreach ( $templates as $titleObj ) {
1163 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
1164 }
1165 $outText .= '</ul>';
1166 }
1167 wfProfileOut( $fname );
1168 return $outText;
1169 }
1170
1171 /**
1172 * Live Preview lets us fetch rendered preview page content and
1173 * add it to the page without refreshing the whole page.
1174 * If not supported by the browser it will fall through to the normal form
1175 * submission method.
1176 *
1177 * This function outputs a script tag to support live preview, and
1178 * returns an onclick handler which should be added to the attributes
1179 * of the preview button
1180 */
1181 function doLivePreviewScript() {
1182 global $wgStylePath, $wgJsMimeType, $wgOut, $wgTitle;
1183 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1184 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
1185 '"></script>' . "\n" );
1186 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1187 return "return !livePreview(" .
1188 "getElementById('wikiPreview')," .
1189 "editform.wpTextbox1.value," .
1190 '"' . $liveAction . '"' . ")";
1191 }
1192
1193 function getLastDelete() {
1194 $dbr =& wfGetDB( DB_SLAVE );
1195 $fname = 'EditPage::getLastDelete';
1196 $res = $dbr->select(
1197 array( 'logging', 'user' ),
1198 array( 'log_type',
1199 'log_action',
1200 'log_timestamp',
1201 'log_user',
1202 'log_namespace',
1203 'log_title',
1204 'log_comment',
1205 'log_params',
1206 'user_name', ),
1207 array( 'log_namespace' => $this->mTitle->getNamespace(),
1208 'log_title' => $this->mTitle->getDBkey(),
1209 'log_type' => 'delete',
1210 'log_action' => 'delete',
1211 'user_id=log_user' ),
1212 $fname,
1213 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1214
1215 if($dbr->numRows($res) == 1) {
1216 while ( $x = $dbr->fetchObject ( $res ) )
1217 $data = $x;
1218 $dbr->freeResult ( $res ) ;
1219 } else {
1220 $data = null;
1221 }
1222 return $data;
1223 }
1224
1225 /**
1226 * @todo document
1227 */
1228 function getPreviewText() {
1229 global $wgOut, $wgUser, $wgTitle, $wgParser;
1230
1231 $fname = 'EditPage::getPreviewText';
1232 wfProfileIn( $fname );
1233
1234 if ( $this->mTokenOk ) {
1235 $msg = 'previewnote';
1236 } else {
1237 $msg = 'session_fail_preview';
1238 }
1239 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1240 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1241 if ( $this->isConflict ) {
1242 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1243 }
1244
1245 $parserOptions = ParserOptions::newFromUser( $wgUser );
1246 $parserOptions->setEditSection( false );
1247
1248 # don't parse user css/js, show message about preview
1249 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1250
1251 if ( $this->isCssJsSubpage ) {
1252 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1253 $previewtext = wfMsg('usercsspreview');
1254 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1255 $previewtext = wfMsg('userjspreview');
1256 }
1257 $parserOptions->setTidy(true);
1258 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1259 $wgOut->addHTML( $parserOutput->mText );
1260 wfProfileOut( $fname );
1261 return $previewhead;
1262 } else {
1263 # if user want to see preview when he edit an article
1264 if( $wgUser->getOption('previewonfirst') and ($this->textbox1 == '')) {
1265 $this->textbox1 = $this->mArticle->getContent();
1266 }
1267
1268 $toparse = $this->textbox1;
1269
1270 # If we're adding a comment, we need to show the
1271 # summary as the headline
1272 if($this->section=="new" && $this->summary!="") {
1273 $toparse="== {$this->summary} ==\n\n".$toparse;
1274 }
1275
1276 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1277 $parserOptions->setTidy(true);
1278 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1279 $wgTitle, $parserOptions );
1280
1281 $previewHTML = $parserOutput->getText();
1282 $wgOut->addParserOutputNoText( $parserOutput );
1283
1284 wfProfileOut( $fname );
1285 return $previewhead . $previewHTML;
1286 }
1287 }
1288
1289 /**
1290 * @todo document
1291 */
1292 function blockedIPpage() {
1293 global $wgOut;
1294 $wgOut->blockedPage();
1295 }
1296
1297 /**
1298 * @todo document
1299 */
1300 function userNotLoggedInPage() {
1301 global $wgOut;
1302
1303 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1304 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1305 $wgOut->setArticleRelated( false );
1306
1307 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
1308 $wgOut->returnToMain( false );
1309 }
1310
1311 /**
1312 * Creates a basic error page which informs the user that
1313 * they have to validate their email address before being
1314 * allowed to edit.
1315 */
1316 function userNotConfirmedPage() {
1317
1318 global $wgOut;
1319
1320 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1321 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1322 $wgOut->setArticleRelated( false );
1323 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1324 $wgOut->returnToMain( false );
1325 }
1326
1327 /**
1328 * @todo document
1329 */
1330 function spamPage ( $match = false )
1331 {
1332 global $wgOut;
1333 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1334 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1335 $wgOut->setArticleRelated( false );
1336
1337 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1338 if ( $match ) {
1339 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1340 }
1341 $wgOut->returnToMain( false );
1342 }
1343
1344 /**
1345 * @access private
1346 * @todo document
1347 */
1348 function mergeChangesInto( &$editText ){
1349 $fname = 'EditPage::mergeChangesInto';
1350 wfProfileIn( $fname );
1351
1352 $db =& wfGetDB( DB_MASTER );
1353
1354 // This is the revision the editor started from
1355 $baseRevision = Revision::loadFromTimestamp(
1356 $db, $this->mArticle->mTitle, $this->edittime );
1357 if( is_null( $baseRevision ) ) {
1358 wfProfileOut( $fname );
1359 return false;
1360 }
1361 $baseText = $baseRevision->getText();
1362
1363 // The current state, we want to merge updates into it
1364 $currentRevision = Revision::loadFromTitle(
1365 $db, $this->mArticle->mTitle );
1366 if( is_null( $currentRevision ) ) {
1367 wfProfileOut( $fname );
1368 return false;
1369 }
1370 $currentText = $currentRevision->getText();
1371
1372 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1373 $editText = $result;
1374 wfProfileOut( $fname );
1375 return true;
1376 } else {
1377 wfProfileOut( $fname );
1378 return false;
1379 }
1380 }
1381
1382 /**
1383 * Check if the browser is on a blacklist of user-agents known to
1384 * mangle UTF-8 data on form submission. Returns true if Unicode
1385 * should make it through, false if it's known to be a problem.
1386 * @return bool
1387 * @access private
1388 */
1389 function checkUnicodeCompliantBrowser() {
1390 global $wgBrowserBlackList;
1391 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1392 // No User-Agent header sent? Trust it by default...
1393 return true;
1394 }
1395 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1396 foreach ( $wgBrowserBlackList as $browser ) {
1397 if ( preg_match($browser, $currentbrowser) ) {
1398 return false;
1399 }
1400 }
1401 return true;
1402 }
1403
1404 /**
1405 * Format an anchor fragment as it would appear for a given section name
1406 * @param string $text
1407 * @return string
1408 * @access private
1409 */
1410 function sectionAnchor( $text ) {
1411 $headline = Sanitizer::decodeCharReferences( $text );
1412 # strip out HTML
1413 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1414 $headline = trim( $headline );
1415 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1416 $replacearray = array(
1417 '%3A' => ':',
1418 '%' => '.'
1419 );
1420 return str_replace(
1421 array_keys( $replacearray ),
1422 array_values( $replacearray ),
1423 $sectionanchor );
1424 }
1425
1426 /**
1427 * Shows a bulletin board style toolbar for common editing functions.
1428 * It can be disabled in the user preferences.
1429 * The necessary JavaScript code can be found in style/wikibits.js.
1430 */
1431 function getEditToolbar() {
1432 global $wgStylePath, $wgContLang, $wgJsMimeType;
1433
1434 /**
1435 * toolarray an array of arrays which each include the filename of
1436 * the button image (without path), the opening tag, the closing tag,
1437 * and optionally a sample text that is inserted between the two when no
1438 * selection is highlighted.
1439 * The tip text is shown when the user moves the mouse over the button.
1440 *
1441 * Already here are accesskeys (key), which are not used yet until someone
1442 * can figure out a way to make them work in IE. However, we should make
1443 * sure these keys are not defined on the edit page.
1444 */
1445 $toolarray=array(
1446 array( 'image'=>'button_bold.png',
1447 'open' => "\'\'\'",
1448 'close' => "\'\'\'",
1449 'sample'=> wfMsg('bold_sample'),
1450 'tip' => wfMsg('bold_tip'),
1451 'key' => 'B'
1452 ),
1453 array( 'image'=>'button_italic.png',
1454 'open' => "\'\'",
1455 'close' => "\'\'",
1456 'sample'=> wfMsg('italic_sample'),
1457 'tip' => wfMsg('italic_tip'),
1458 'key' => 'I'
1459 ),
1460 array( 'image'=>'button_link.png',
1461 'open' => '[[',
1462 'close' => ']]',
1463 'sample'=> wfMsg('link_sample'),
1464 'tip' => wfMsg('link_tip'),
1465 'key' => 'L'
1466 ),
1467 array( 'image'=>'button_extlink.png',
1468 'open' => '[',
1469 'close' => ']',
1470 'sample'=> wfMsg('extlink_sample'),
1471 'tip' => wfMsg('extlink_tip'),
1472 'key' => 'X'
1473 ),
1474 array( 'image'=>'button_headline.png',
1475 'open' => "\\n== ",
1476 'close' => " ==\\n",
1477 'sample'=> wfMsg('headline_sample'),
1478 'tip' => wfMsg('headline_tip'),
1479 'key' => 'H'
1480 ),
1481 array( 'image'=>'button_image.png',
1482 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).":",
1483 'close' => ']]',
1484 'sample'=> wfMsg('image_sample'),
1485 'tip' => wfMsg('image_tip'),
1486 'key' => 'D'
1487 ),
1488 array( 'image' =>'button_media.png',
1489 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1490 'close' => ']]',
1491 'sample'=> wfMsg('media_sample'),
1492 'tip' => wfMsg('media_tip'),
1493 'key' => 'M'
1494 ),
1495 array( 'image' =>'button_math.png',
1496 'open' => "\\<math\\>",
1497 'close' => "\\</math\\>",
1498 'sample'=> wfMsg('math_sample'),
1499 'tip' => wfMsg('math_tip'),
1500 'key' => 'C'
1501 ),
1502 array( 'image' =>'button_nowiki.png',
1503 'open' => "\\<nowiki\\>",
1504 'close' => "\\</nowiki\\>",
1505 'sample'=> wfMsg('nowiki_sample'),
1506 'tip' => wfMsg('nowiki_tip'),
1507 'key' => 'N'
1508 ),
1509 array( 'image' =>'button_sig.png',
1510 'open' => '--~~~~',
1511 'close' => '',
1512 'sample'=> '',
1513 'tip' => wfMsg('sig_tip'),
1514 'key' => 'Y'
1515 ),
1516 array( 'image' =>'button_hr.png',
1517 'open' => "\\n----\\n",
1518 'close' => '',
1519 'sample'=> '',
1520 'tip' => wfMsg('hr_tip'),
1521 'key' => 'R'
1522 )
1523 );
1524 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1525
1526 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1527 foreach($toolarray as $tool) {
1528
1529 $image=$wgStylePath.'/common/images/'.$tool['image'];
1530 $open=$tool['open'];
1531 $close=$tool['close'];
1532 $sample = wfEscapeJsString( $tool['sample'] );
1533
1534 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1535 // Older browsers show a "speedtip" type message only for ALT.
1536 // Ideally these should be different, realistically they
1537 // probably don't need to be.
1538 $tip = wfEscapeJsString( $tool['tip'] );
1539
1540 #$key = $tool["key"];
1541
1542 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1543 }
1544
1545 $toolbar.="document.writeln(\"</div>\");\n";
1546 $toolbar.="/*]]>*/\n</script>";
1547 return $toolbar;
1548 }
1549
1550 /**
1551 * Output preview text only. This can be sucked into the edit page
1552 * via JavaScript, and saves the server time rendering the skin as
1553 * well as theoretically being more robust on the client (doesn't
1554 * disturb the edit box's undo history, won't eat your text on
1555 * failure, etc).
1556 *
1557 * @todo This doesn't include category or interlanguage links.
1558 * Would need to enhance it a bit, maybe wrap them in XML
1559 * or something... that might also require more skin
1560 * initialization, so check whether that's a problem.
1561 */
1562 function livePreview() {
1563 global $wgOut;
1564 $wgOut->disable();
1565 header( 'Content-type: text/xml' );
1566 header( 'Cache-control: no-cache' );
1567 # FIXME
1568 echo $this->getPreviewText( );
1569 /* To not shake screen up and down between preview and live-preview */
1570 echo "<br style=\"clear:both;\" />\n";
1571 }
1572
1573
1574 /**
1575 * Get a diff between the current contents of the edit box and the
1576 * version of the page we're editing from.
1577 *
1578 * If this is a section edit, we'll replace the section as for final
1579 * save and then make a comparison.
1580 *
1581 * @return string HTML
1582 */
1583 function getDiff() {
1584 require_once( 'DifferenceEngine.php' );
1585 $oldtext = $this->mArticle->fetchContent();
1586 $newtext = $this->mArticle->replaceSection(
1587 $this->section, $this->textbox1, $this->summary, $this->edittime );
1588 $oldtitle = wfMsg( 'currentrev' );
1589 $newtitle = wfMsg( 'yourtext' );
1590 if ( $oldtext !== false || $newtext != '' ) {
1591 $de = new DifferenceEngine( $this->mTitle );
1592 $de->setText( $oldtext, $newtext );
1593 $difftext = $de->getDiff( $oldtitle, $newtitle );
1594 } else {
1595 $difftext = '';
1596 }
1597
1598 return '<div id="wikiDiff">' . $difftext . '</div>';
1599 }
1600
1601 /**
1602 * Filter an input field through a Unicode de-armoring process if it
1603 * came from an old browser with known broken Unicode editing issues.
1604 *
1605 * @param WebRequest $request
1606 * @param string $field
1607 * @return string
1608 * @access private
1609 */
1610 function safeUnicodeInput( $request, $field ) {
1611 $text = rtrim( $request->getText( $field ) );
1612 return $request->getBool( 'safemode' )
1613 ? $this->unmakesafe( $text )
1614 : $text;
1615 }
1616
1617 /**
1618 * Filter an output field through a Unicode armoring process if it is
1619 * going to an old browser with known broken Unicode editing issues.
1620 *
1621 * @param string $text
1622 * @return string
1623 * @access private
1624 */
1625 function safeUnicodeOutput( $text ) {
1626 global $wgContLang;
1627 $codedText = $wgContLang->recodeForEdit( $text );
1628 return $this->checkUnicodeCompliantBrowser()
1629 ? $codedText
1630 : $this->makesafe( $codedText );
1631 }
1632
1633 /**
1634 * A number of web browsers are known to corrupt non-ASCII characters
1635 * in a UTF-8 text editing environment. To protect against this,
1636 * detected browsers will be served an armored version of the text,
1637 * with non-ASCII chars converted to numeric HTML character references.
1638 *
1639 * Preexisting such character references will have a 0 added to them
1640 * to ensure that round-trips do not alter the original data.
1641 *
1642 * @param string $invalue
1643 * @return string
1644 * @access private
1645 */
1646 function makesafe( $invalue ) {
1647 // Armor existing references for reversability.
1648 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1649
1650 $bytesleft = 0;
1651 $result = "";
1652 $working = 0;
1653 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1654 $bytevalue = ord( $invalue{$i} );
1655 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1656 $result .= chr( $bytevalue );
1657 $bytesleft = 0;
1658 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1659 $working = $working << 6;
1660 $working += ($bytevalue & 0x3F);
1661 $bytesleft--;
1662 if( $bytesleft <= 0 ) {
1663 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1664 }
1665 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1666 $working = $bytevalue & 0x1F;
1667 $bytesleft = 1;
1668 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1669 $working = $bytevalue & 0x0F;
1670 $bytesleft = 2;
1671 } else { //1111 0xxx
1672 $working = $bytevalue & 0x07;
1673 $bytesleft = 3;
1674 }
1675 }
1676 return $result;
1677 }
1678
1679 /**
1680 * Reverse the previously applied transliteration of non-ASCII characters
1681 * back to UTF-8. Used to protect data from corruption by broken web browsers
1682 * as listed in $wgBrowserBlackList.
1683 *
1684 * @param string $invalue
1685 * @return string
1686 * @access private
1687 */
1688 function unmakesafe( $invalue ) {
1689 $result = "";
1690 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1691 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
1692 $i += 3;
1693 $hexstring = "";
1694 do {
1695 $hexstring .= $invalue{$i};
1696 $i++;
1697 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1698
1699 // Do some sanity checks. These aren't needed for reversability,
1700 // but should help keep the breakage down if the editor
1701 // breaks one of the entities whilst editing.
1702 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1703 $codepoint = hexdec($hexstring);
1704 $result .= codepointToUtf8( $codepoint );
1705 } else {
1706 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1707 }
1708 } else {
1709 $result .= substr( $invalue, $i, 1 );
1710 }
1711 }
1712 // reverse the transform that we made for reversability reasons.
1713 return strtr( $result, array( "&#x0" => "&#x" ) );
1714 }
1715
1716 function noCreatePermission() {
1717 global $wgOut;
1718 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
1719 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
1720 }
1721
1722 }
1723
1724 ?>