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