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