* (bug 12567) Fix for misformatted read-only messages on edit, protect.
[lhc/web/wiklou.git] / includes / EditPage.php
1 <?php
2 /**
3 * Contains the EditPage class
4 */
5
6 /**
7 * The edit page/HTML interface (split from Article)
8 * The actual database and text munging is still in Article,
9 * but it should get easier to call those from alternate
10 * interfaces.
11 *
12 * EditPage cares about two distinct titles:
13 * $wgTitle is the page that forms submit to, links point to,
14 * redirects go to, etc. $this->mTitle (as well as $mArticle) is the
15 * page in the database that is actually being edited. These are
16 * usually the same, but they are now allowed to be different.
17 */
18 class EditPage {
19 const AS_SUCCESS_UPDATE = 200;
20 const AS_SUCCESS_NEW_ARTICLE = 201;
21 const AS_HOOK_ERROR = 210;
22 const AS_FILTERING = 211;
23 const AS_HOOK_ERROR_EXPECTED = 212;
24 const AS_BLOCKED_PAGE_FOR_USER = 215;
25 const AS_CONTENT_TOO_BIG = 216;
26 const AS_USER_CANNOT_EDIT = 217;
27 const AS_READ_ONLY_PAGE_ANON = 218;
28 const AS_READ_ONLY_PAGE_LOGGED = 219;
29 const AS_READ_ONLY_PAGE = 220;
30 const AS_RATE_LIMITED = 221;
31 const AS_ARTICLE_WAS_DELETED = 222;
32 const AS_NO_CREATE_PERMISSION = 223;
33 const AS_BLANK_ARTICLE = 224;
34 const AS_CONFLICT_DETECTED = 225;
35 const AS_SUMMARY_NEEDED = 226;
36 const AS_TEXTBOX_EMPTY = 228;
37 const AS_MAX_ARTICLE_SIZE_EXCEDED = 229;
38 const AS_OK = 230;
39 const AS_END = 231;
40 const AS_SPAM_ERROR = 232;
41
42 var $mArticle;
43 var $mTitle;
44 var $mMetaData = '';
45 var $isConflict = false;
46 var $isCssJsSubpage = false;
47 var $deletedSinceEdit = false;
48 var $formtype;
49 var $firsttime;
50 var $lastDelete;
51 var $mTokenOk = false;
52 var $mTokenOkExceptSuffix = false;
53 var $mTriedSave = false;
54 var $tooBig = false;
55 var $kblength = false;
56 var $missingComment = false;
57 var $missingSummary = false;
58 var $allowBlankSummary = false;
59 var $autoSumm = '';
60 var $hookError = '';
61 var $mPreviewTemplates;
62
63 # Form values
64 var $save = false, $preview = false, $diff = false;
65 var $minoredit = false, $watchthis = false, $recreate = false;
66 var $textbox1 = '', $textbox2 = '', $summary = '';
67 var $edittime = '', $section = '', $starttime = '';
68 var $oldid = 0, $editintro = '', $scrolltop = null;
69
70 # Placeholders for text injection by hooks (must be HTML)
71 # extensions should take care to _append_ to the present value
72 public $editFormPageTop; // Before even the preview
73 public $editFormTextTop;
74 public $editFormTextBeforeContent;
75 public $editFormTextAfterWarn;
76 public $editFormTextAfterTools;
77 public $editFormTextBottom;
78
79 /* $didSave should be set to true whenever an article was succesfully altered. */
80 public $didSave = false;
81
82 public $suppressIntro = false;
83
84 /**
85 * @todo document
86 * @param $article
87 */
88 function EditPage( $article ) {
89 global $wgTitle;
90 $this->mArticle =& $article;
91 $this->mTitle = $article->getTitle();
92
93 # Placeholders for text injection by hooks (empty per default)
94 $this->editFormPageTop =
95 $this->editFormTextTop =
96 $this->editFormTextBeforeContent =
97 $this->editFormTextAfterWarn =
98 $this->editFormTextAfterTools =
99 $this->editFormTextBottom = "";
100 }
101
102 /**
103 * Fetch initial editing page content.
104 */
105 private function getContent( $def_text = '' ) {
106 global $wgOut, $wgRequest, $wgParser;
107
108 # Get variables from query string :P
109 $section = $wgRequest->getVal( 'section' );
110 $preload = $wgRequest->getVal( 'preload' );
111 $undoafter = $wgRequest->getVal( 'undoafter' );
112 $undo = $wgRequest->getVal( 'undo' );
113
114 wfProfileIn( __METHOD__ );
115
116 $text = '';
117 if( !$this->mTitle->exists() ) {
118 if ( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
119 # If this is a system message, get the default text.
120 $text = wfMsgWeirdKey ( $this->mTitle->getText() ) ;
121 } else {
122 # If requested, preload some text.
123 $text = $this->getPreloadedText( $preload );
124 }
125 # We used to put MediaWiki:Newarticletext here if
126 # $text was empty at this point.
127 # This is now shown above the edit box instead.
128 } else {
129 // FIXME: may be better to use Revision class directly
130 // But don't mess with it just yet. Article knows how to
131 // fetch the page record from the high-priority server,
132 // which is needed to guarantee we don't pick up lagged
133 // information.
134
135 $text = $this->mArticle->getContent();
136
137 if ($undo > 0 && $undoafter > 0 && $undo < $undoafter) {
138 # If they got undoafter and undo round the wrong way, switch them
139 list( $undo, $undoafter ) = array( $undoafter, $undo );
140 }
141
142 if ( $undo > 0 && $undo > $undoafter ) {
143 # Undoing a specific edit overrides section editing; section-editing
144 # doesn't work with undoing.
145 if ( $undoafter ) {
146 $undorev = Revision::newFromId($undo);
147 $oldrev = Revision::newFromId($undoafter);
148 } else {
149 $undorev = Revision::newFromId($undo);
150 $oldrev = $undorev ? $undorev->getPrevious() : null;
151 }
152
153 #Sanity check, make sure it's the right page.
154 # Otherwise, $text will be left as-is.
155 if ( !is_null($undorev) && !is_null($oldrev) && $undorev->getPage()==$oldrev->getPage() && $undorev->getPage()==$this->mArticle->getID() ) {
156 $undorev_text = $undorev->getText();
157 $oldrev_text = $oldrev->getText();
158 $currev_text = $text;
159
160 #No use doing a merge if it's just a straight revert.
161 if ( $currev_text != $undorev_text ) {
162 $result = wfMerge($undorev_text, $oldrev_text, $currev_text, $text);
163 } else {
164 $text = $oldrev_text;
165 $result = true;
166 }
167 } else {
168 // Failed basic sanity checks.
169 // Older revisions may have been removed since the link
170 // was created, or we may simply have got bogus input.
171 $result = false;
172 }
173
174 if( $result ) {
175 # Inform the user of our success and set an automatic edit summary
176 $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-success' ) );
177 $firstrev = $oldrev->getNext();
178 # If we just undid one rev, use an autosummary
179 if ( $firstrev->mId == $undo ) {
180 $this->summary = wfMsgForContent('undo-summary', $undo, $undorev->getUserText());
181 }
182 $this->formtype = 'diff';
183 } else {
184 # Warn the user that something went wrong
185 $this->editFormPageTop .= $wgOut->parse( wfMsgNoTrans( 'undo-failure' ) );
186 }
187 } else if( $section != '' ) {
188 if( $section == 'new' ) {
189 $text = $this->getPreloadedText( $preload );
190 } else {
191 $text = $wgParser->getSection( $text, $section, $def_text );
192 }
193 }
194 }
195
196 wfProfileOut( __METHOD__ );
197 return $text;
198 }
199
200 /**
201 * Get the contents of a page from its title and remove includeonly tags
202 *
203 * @param $preload String: the title of the page.
204 * @return string The contents of the page.
205 */
206 private function getPreloadedText($preload) {
207 if ( $preload === '' )
208 return '';
209 else {
210 $preloadTitle = Title::newFromText( $preload );
211 if ( isset( $preloadTitle ) && $preloadTitle->userCanRead() ) {
212 $rev=Revision::newFromTitle($preloadTitle);
213 if ( is_object( $rev ) ) {
214 $text = $rev->getText();
215 // TODO FIXME: AAAAAAAAAAA, this shouldn't be implementing
216 // its own mini-parser! -ævar
217 $text = preg_replace( '~</?includeonly>~', '', $text );
218 return $text;
219 } else
220 return '';
221 }
222 }
223 }
224
225 /**
226 * This is the function that extracts metadata from the article body on the first view.
227 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
228 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
229 */
230 function extractMetaDataFromArticle () {
231 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
232 $this->mMetaData = '' ;
233 if ( !$wgUseMetadataEdit ) return ;
234 if ( $wgMetadataWhitelist == '' ) return ;
235 $s = '' ;
236 $t = $this->getContent();
237
238 # MISSING : <nowiki> filtering
239
240 # Categories and language links
241 $t = explode ( "\n" , $t ) ;
242 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY ) ) ;
243 $cat = $ll = array() ;
244 foreach ( $t AS $key => $x )
245 {
246 $y = trim ( strtolower ( $x ) ) ;
247 while ( substr ( $y , 0 , 2 ) == '[[' )
248 {
249 $y = explode ( ']]' , trim ( $x ) ) ;
250 $first = array_shift ( $y ) ;
251 $first = explode ( ':' , $first ) ;
252 $ns = array_shift ( $first ) ;
253 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
254 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
255 {
256 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
257 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
258 else $ll[] = $add ;
259 $x = implode ( ']]' , $y ) ;
260 $t[$key] = $x ;
261 $y = trim ( strtolower ( $x ) ) ;
262 }
263 }
264 }
265 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
266 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
267 $t = implode ( "\n" , $t ) ;
268
269 # Load whitelist
270 $sat = array () ; # stand-alone-templates; must be lowercase
271 $wl_title = Title::newFromText ( $wgMetadataWhitelist ) ;
272 $wl_article = new Article ( $wl_title ) ;
273 $wl = explode ( "\n" , $wl_article->getContent() ) ;
274 foreach ( $wl AS $x )
275 {
276 $isentry = false ;
277 $x = trim ( $x ) ;
278 while ( substr ( $x , 0 , 1 ) == '*' )
279 {
280 $isentry = true ;
281 $x = trim ( substr ( $x , 1 ) ) ;
282 }
283 if ( $isentry )
284 {
285 $sat[] = strtolower ( $x ) ;
286 }
287
288 }
289
290 # Templates, but only some
291 $t = explode ( '{{' , $t ) ;
292 $tl = array () ;
293 foreach ( $t AS $key => $x )
294 {
295 $y = explode ( '}}' , $x , 2 ) ;
296 if ( count ( $y ) == 2 )
297 {
298 $z = $y[0] ;
299 $z = explode ( '|' , $z ) ;
300 $tn = array_shift ( $z ) ;
301 if ( in_array ( strtolower ( $tn ) , $sat ) )
302 {
303 $tl[] = '{{' . $y[0] . '}}' ;
304 $t[$key] = $y[1] ;
305 $y = explode ( '}}' , $y[1] , 2 ) ;
306 }
307 else $t[$key] = '{{' . $x ;
308 }
309 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
310 else $t[$key] = $x ;
311 }
312 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
313 $t = implode ( '' , $t ) ;
314
315 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
316 $this->mArticle->mContent = $t ;
317 $this->mMetaData = $s ;
318 }
319
320 function submit() {
321 $this->edit();
322 }
323
324 /**
325 * This is the function that gets called for "action=edit". It
326 * sets up various member variables, then passes execution to
327 * another function, usually showEditForm()
328 *
329 * The edit form is self-submitting, so that when things like
330 * preview and edit conflicts occur, we get the same form back
331 * with the extra stuff added. Only when the final submission
332 * is made and all is well do we actually save and redirect to
333 * the newly-edited page.
334 */
335 function edit() {
336 global $wgOut, $wgUser, $wgRequest, $wgTitle;
337
338 if ( !wfRunHooks( 'AlternateEdit', array( &$this ) ) )
339 return;
340
341 wfProfileIn( __METHOD__ );
342 wfDebug( __METHOD__.": enter\n" );
343
344 // this is not an article
345 $wgOut->setArticleFlag(false);
346
347 $this->importFormData( $wgRequest );
348 $this->firsttime = false;
349
350 if( $this->live ) {
351 $this->livePreview();
352 wfProfileOut( __METHOD__ );
353 return;
354 }
355
356 if( wfReadOnly() ) {
357 $wgOut->readOnlyPage( $this->getContent() );
358 wfProfileOut( __METHOD__ );
359 return;
360 }
361
362 $permErrors = $this->mTitle->getUserPermissionsErrors('edit', $wgUser);
363 if( !$this->mTitle->exists() ) {
364 # We can't use array_diff here, because that considers ANY TWO
365 # ARRAYS TO BE EQUAL. Thanks, PHP.
366 $createErrors = $this->mTitle->getUserPermissionsErrors('create', $wgUser);
367 foreach( $createErrors as $error ) {
368 # in_array() actually *does* work as expected.
369 if( !in_array( $error, $permErrors ) ) {
370 $permErrors[] = $error;
371 }
372 }
373 }
374
375 # Ignore some permissions errors.
376 $remove = array();
377 foreach( $permErrors as $error ) {
378 if ($this->preview || $this->diff &&
379 ($error[0] == 'blockedtext' || $error[0] == 'autoblockedtext'))
380 {
381 // Don't worry about blocks when previewing/diffing
382 $remove[] = $error;
383 }
384
385 if ($error[0] == 'readonlytext')
386 {
387 if ($this->edit) {
388 $this->formtype = 'preview';
389 } elseif ($this->save || $this->preview || $this->diff) {
390 $remove[] = $error;
391 }
392 }
393 }
394 $permErrors = array_diff( $permErrors, $remove );
395
396 if ( !empty($permErrors) ) {
397 wfDebug( __METHOD__.": User can't edit\n" );
398 $wgOut->readOnlyPage( $this->getContent(), true, $permErrors );
399 wfProfileOut( __METHOD__ );
400 return;
401 } else {
402 if ( $this->save ) {
403 $this->formtype = 'save';
404 } else if ( $this->preview ) {
405 $this->formtype = 'preview';
406 } else if ( $this->diff ) {
407 $this->formtype = 'diff';
408 } else { # First time through
409 $this->firsttime = true;
410 if( $this->previewOnOpen() ) {
411 $this->formtype = 'preview';
412 } else {
413 $this->extractMetaDataFromArticle () ;
414 $this->formtype = 'initial';
415 }
416 }
417 }
418
419 wfProfileIn( __METHOD__."-business-end" );
420
421 $this->isConflict = false;
422 // css / js subpages of user pages get a special treatment
423 $this->isCssJsSubpage = $this->mTitle->isCssJsSubpage();
424 $this->isValidCssJsSubpage = $this->mTitle->isValidCssJsSubpage();
425
426 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
427 * no matter it's current state
428 */
429 $this->deletedSinceEdit = false;
430 if ( $this->edittime != '' ) {
431 /* Note that we rely on logging table, which hasn't been always there,
432 * but that doesn't matter, because this only applies to brand new
433 * deletes. This is done on every preview and save request. Move it further down
434 * to only perform it on saves
435 */
436 if ( $this->mTitle->isDeleted() ) {
437 $this->lastDelete = $this->getLastDelete();
438 if ( !is_null($this->lastDelete) ) {
439 $deletetime = $this->lastDelete->log_timestamp;
440 if ( ($deletetime - $this->starttime) > 0 ) {
441 $this->deletedSinceEdit = true;
442 }
443 }
444 }
445 }
446
447 # Show applicable editing introductions
448 if( $this->formtype == 'initial' || $this->firsttime )
449 $this->showIntro();
450
451 if( $this->mTitle->isTalkPage() ) {
452 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
453 }
454
455 # Attempt submission here. This will check for edit conflicts,
456 # and redundantly check for locked database, blocked IPs, etc.
457 # that edit() already checked just in case someone tries to sneak
458 # in the back door with a hand-edited submission URL.
459
460 if ( 'save' == $this->formtype ) {
461 if ( !$this->attemptSave() ) {
462 wfProfileOut( __METHOD__."-business-end" );
463 wfProfileOut( __METHOD__ );
464 return;
465 }
466 }
467
468 # First time through: get contents, set time for conflict
469 # checking, etc.
470 if ( 'initial' == $this->formtype || $this->firsttime ) {
471 if ($this->initialiseForm() === false) {
472 $this->noSuchSectionPage();
473 wfProfileOut( __METHOD__."-business-end" );
474 wfProfileOut( __METHOD__ );
475 return;
476 }
477 if( !$this->mTitle->getArticleId() )
478 wfRunHooks( 'EditFormPreloadText', array( &$this->textbox1, &$this->mTitle ) );
479 }
480
481 $this->showEditForm();
482 wfProfileOut( __METHOD__."-business-end" );
483 wfProfileOut( __METHOD__ );
484 }
485
486 /**
487 * Should we show a preview when the edit form is first shown?
488 *
489 * @return bool
490 */
491 private function previewOnOpen() {
492 global $wgRequest, $wgUser;
493 if( $wgRequest->getVal( 'preview' ) == 'yes' ) {
494 // Explicit override from request
495 return true;
496 } elseif( $wgRequest->getVal( 'preview' ) == 'no' ) {
497 // Explicit override from request
498 return false;
499 } elseif( $this->section == 'new' ) {
500 // Nothing *to* preview for new sections
501 return false;
502 } elseif( ( $wgRequest->getVal( 'preload' ) !== '' || $this->mTitle->exists() ) && $wgUser->getOption( 'previewonfirst' ) ) {
503 // Standard preference behaviour
504 return true;
505 } elseif( !$this->mTitle->exists() && $this->mTitle->getNamespace() == NS_CATEGORY ) {
506 // Categories are special
507 return true;
508 } else {
509 return false;
510 }
511 }
512
513 /**
514 * @todo document
515 * @param $request
516 */
517 function importFormData( &$request ) {
518 global $wgLang, $wgUser;
519 $fname = 'EditPage::importFormData';
520 wfProfileIn( $fname );
521
522 if( $request->wasPosted() ) {
523 # These fields need to be checked for encoding.
524 # Also remove trailing whitespace, but don't remove _initial_
525 # whitespace from the text boxes. This may be significant formatting.
526 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
527 $this->textbox2 = $this->safeUnicodeInput( $request, 'wpTextbox2' );
528 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
529 # Truncate for whole multibyte characters. +5 bytes for ellipsis
530 $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
531
532 $this->edittime = $request->getVal( 'wpEdittime' );
533 $this->starttime = $request->getVal( 'wpStarttime' );
534
535 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
536
537 if( is_null( $this->edittime ) ) {
538 # If the form is incomplete, force to preview.
539 wfDebug( "$fname: Form data appears to be incomplete\n" );
540 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
541 $this->preview = true;
542 } else {
543 /* Fallback for live preview */
544 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
545 $this->diff = $request->getCheck( 'wpDiff' );
546
547 // Remember whether a save was requested, so we can indicate
548 // if we forced preview due to session failure.
549 $this->mTriedSave = !$this->preview;
550
551 if ( $this->tokenOk( $request ) ) {
552 # Some browsers will not report any submit button
553 # if the user hits enter in the comment box.
554 # The unmarked state will be assumed to be a save,
555 # if the form seems otherwise complete.
556 wfDebug( "$fname: Passed token check.\n" );
557 } else if ( $this->diff ) {
558 # Failed token check, but only requested "Show Changes".
559 wfDebug( "$fname: Failed token check; Show Changes requested.\n" );
560 } else {
561 # Page might be a hack attempt posted from
562 # an external site. Preview instead of saving.
563 wfDebug( "$fname: Failed token check; forcing preview\n" );
564 $this->preview = true;
565 }
566 }
567 $this->save = ! ( $this->preview OR $this->diff );
568 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
569 $this->edittime = null;
570 }
571
572 if( !preg_match( '/^\d{14}$/', $this->starttime )) {
573 $this->starttime = null;
574 }
575
576 $this->recreate = $request->getCheck( 'wpRecreate' );
577
578 $this->minoredit = $request->getCheck( 'wpMinoredit' );
579 $this->watchthis = $request->getCheck( 'wpWatchthis' );
580
581 # Don't force edit summaries when a user is editing their own user or talk page
582 if( ( $this->mTitle->mNamespace == NS_USER || $this->mTitle->mNamespace == NS_USER_TALK ) && $this->mTitle->getText() == $wgUser->getName() ) {
583 $this->allowBlankSummary = true;
584 } else {
585 $this->allowBlankSummary = $request->getBool( 'wpIgnoreBlankSummary' );
586 }
587
588 $this->autoSumm = $request->getText( 'wpAutoSummary' );
589 } else {
590 # Not a posted form? Start with nothing.
591 wfDebug( "$fname: Not a posted form.\n" );
592 $this->textbox1 = '';
593 $this->textbox2 = '';
594 $this->mMetaData = '';
595 $this->summary = '';
596 $this->edittime = '';
597 $this->starttime = wfTimestampNow();
598 $this->edit = false;
599 $this->preview = false;
600 $this->save = false;
601 $this->diff = false;
602 $this->minoredit = false;
603 $this->watchthis = false;
604 $this->recreate = false;
605 }
606
607 $this->oldid = $request->getInt( 'oldid' );
608
609 # Section edit can come from either the form or a link
610 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
611
612 $this->live = $request->getCheck( 'live' );
613 $this->editintro = $request->getText( 'editintro' );
614
615 wfProfileOut( $fname );
616 }
617
618 /**
619 * Make sure the form isn't faking a user's credentials.
620 *
621 * @param $request WebRequest
622 * @return bool
623 * @private
624 */
625 function tokenOk( &$request ) {
626 global $wgUser;
627 $token = $request->getVal( 'wpEditToken' );
628 $this->mTokenOk = $wgUser->matchEditToken( $token );
629 $this->mTokenOkExceptSuffix = $wgUser->matchEditTokenNoSuffix( $token );
630 return $this->mTokenOk;
631 }
632
633 /**
634 * Show all applicable editing introductions
635 */
636 private function showIntro() {
637 global $wgOut, $wgUser;
638 if( $this->suppressIntro )
639 return;
640
641 # Show a warning message when someone creates/edits a user (talk) page but the user does not exists
642 if( $this->mTitle->getNamespace() == NS_USER || $this->mTitle->getNamespace() == NS_USER_TALK ) {
643 $parts = explode( '/', $this->mTitle->getText(), 2 );
644 $username = $parts[0];
645 $id = User::idFromName( $username );
646 $ip = User::isIP( $username );
647
648 if ( $id == 0 && !$ip ) {
649 $wgOut->addWikiText( '<div class="mw-userpage-userdoesnotexist error">' . wfMsg( 'userpage-userdoesnotexist', $username ) . '</div>' );
650 }
651 }
652
653 if( !$this->showCustomIntro() && !$this->mTitle->exists() ) {
654 if( $wgUser->isLoggedIn() ) {
655 $wgOut->addWikiText( '<div class="mw-newarticletext">' . wfMsg( 'newarticletext' ) . '</div>' );
656 } else {
657 $wgOut->addWikiText( '<div class="mw-newarticletextanon">' . wfMsg( 'newarticletextanon' ) . '</div>' );
658 }
659 $this->showDeletionLog( $wgOut );
660 }
661 }
662
663 /**
664 * Attempt to show a custom editing introduction, if supplied
665 *
666 * @return bool
667 */
668 private function showCustomIntro() {
669 if( $this->editintro ) {
670 $title = Title::newFromText( $this->editintro );
671 if( $title instanceof Title && $title->exists() && $title->userCanRead() ) {
672 global $wgOut;
673 $revision = Revision::newFromTitle( $title );
674 $wgOut->addSecondaryWikiText( $revision->getText() );
675 return true;
676 } else {
677 return false;
678 }
679 } else {
680 return false;
681 }
682 }
683
684 /**
685 * Attempt submission (no UI)
686 * @return one of the constants describing the result
687 */
688 function internalAttemptSave( &$result, $bot = false ) {
689 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut, $wgParser;
690 global $wgMaxArticleSize, $wgTitle;
691
692 $fname = 'EditPage::attemptSave';
693 wfProfileIn( $fname );
694 wfProfileIn( "$fname-checks" );
695
696 if( !wfRunHooks( 'EditPage::attemptSave', array( &$this ) ) )
697 {
698 wfDebug( "Hook 'EditPage::attemptSave' aborted article saving" );
699 return self::AS_HOOK_ERROR;
700 }
701
702 # Reintegrate metadata
703 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
704 $this->mMetaData = '' ;
705
706 # Check for spam
707 $matches = array();
708 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
709 $result['spam'] = $matches[0];
710 wfProfileOut( "$fname-checks" );
711 wfProfileOut( $fname );
712 return self::AS_SPAM_ERROR;
713 }
714 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
715 # Error messages or other handling should be performed by the filter function
716 wfProfileOut( "$fname-checks" );
717 wfProfileOut( $fname );
718 return self::AS_FILTERING;
719 }
720 if ( !wfRunHooks( 'EditFilter', array( $this, $this->textbox1, $this->section, &$this->hookError ) ) ) {
721 # Error messages etc. could be handled within the hook...
722 wfProfileOut( "$fname-checks" );
723 wfProfileOut( $fname );
724 return self::AS_HOOK_ERROR;
725 } elseif( $this->hookError != '' ) {
726 # ...or the hook could be expecting us to produce an error
727 wfProfileOut( "$fname-checks" );
728 wfProfileOut( $fname );
729 return self::AS_HOOK_ERROR_EXPECTED;
730 }
731 if ( $wgUser->isBlockedFrom( $wgTitle, false ) ) {
732 # Check block state against master, thus 'false'.
733 wfProfileOut( "$fname-checks" );
734 wfProfileOut( $fname );
735 return self::AS_BLOCKED_PAGE_FOR_USER;
736 }
737 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
738 if ( $this->kblength > $wgMaxArticleSize ) {
739 // Error will be displayed by showEditForm()
740 $this->tooBig = true;
741 wfProfileOut( "$fname-checks" );
742 wfProfileOut( $fname );
743 return self::AS_CONTENT_TOO_BIG;
744 }
745
746 if ( !$wgUser->isAllowed('edit') ) {
747 if ( $wgUser->isAnon() ) {
748 wfProfileOut( "$fname-checks" );
749 wfProfileOut( $fname );
750 return self::AS_READ_ONLY_PAGE_ANON;
751 }
752 else {
753 wfProfileOut( "$fname-checks" );
754 wfProfileOut( $fname );
755 return self::AS_READ_ONLY_PAGE_LOGGED;
756 }
757 }
758
759 if ( wfReadOnly() ) {
760 wfProfileOut( "$fname-checks" );
761 wfProfileOut( $fname );
762 return self::AS_READ_ONLY_PAGE;
763 }
764 if ( $wgUser->pingLimiter() ) {
765 wfProfileOut( "$fname-checks" );
766 wfProfileOut( $fname );
767 return self::AS_RATE_LIMITED;
768 }
769
770 # If the article has been deleted while editing, don't save it without
771 # confirmation
772 if ( $this->deletedSinceEdit && !$this->recreate ) {
773 wfProfileOut( "$fname-checks" );
774 wfProfileOut( $fname );
775 return self::AS_ARTICLE_WAS_DELETED;
776 }
777
778 wfProfileOut( "$fname-checks" );
779
780 # If article is new, insert it.
781 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
782 if ( 0 == $aid ) {
783
784 // Late check for create permission, just in case *PARANOIA*
785 if ( !$this->mTitle->userCan( 'create' ) ) {
786 wfDebug( "$fname: no create permission\n" );
787 wfProfileOut( $fname );
788 return self::AS_NO_CREATE_PERMISSION;
789 }
790
791 # Don't save a new article if it's blank.
792 if ( ( '' == $this->textbox1 ) ) {
793 wfProfileOut( $fname );
794 return self::AS_BLANK_ARTICLE;
795 }
796
797 // Run post-section-merge edit filter
798 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $this->textbox1, &$this->hookError ) ) ) {
799 # Error messages etc. could be handled within the hook...
800 wfProfileOut( $fname );
801 return false;
802 }
803
804 $isComment = ( $this->section == 'new' );
805
806 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
807 $this->minoredit, $this->watchthis, false, $isComment, $bot);
808
809 wfProfileOut( $fname );
810 return self::AS_SUCCESS_NEW_ARTICLE;
811 }
812
813 # Article exists. Check for edit conflict.
814
815 $this->mArticle->clear(); # Force reload of dates, etc.
816 $this->mArticle->forUpdate( true ); # Lock the article
817
818 wfDebug("timestamp: {$this->mArticle->getTimestamp()}, edittime: {$this->edittime}\n");
819
820 if( $this->mArticle->getTimestamp() != $this->edittime ) {
821 $this->isConflict = true;
822 if( $this->section == 'new' ) {
823 if( $this->mArticle->getUserText() == $wgUser->getName() &&
824 $this->mArticle->getComment() == $this->summary ) {
825 // Probably a duplicate submission of a new comment.
826 // This can happen when squid resends a request after
827 // a timeout but the first one actually went through.
828 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
829 } else {
830 // New comment; suppress conflict.
831 $this->isConflict = false;
832 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
833 }
834 }
835 }
836 $userid = $wgUser->getID();
837
838 if ( $this->isConflict) {
839 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
840 $this->mArticle->getTimestamp() . "')\n" );
841 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
842 }
843 else {
844 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
845 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
846 }
847 if( is_null( $text ) ) {
848 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
849 $this->isConflict = true;
850 $text = $this->textbox1;
851 }
852
853 # Suppress edit conflict with self, except for section edits where merging is required.
854 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
855 wfDebug( "EditPage::editForm Suppressing edit conflict, same user.\n" );
856 $this->isConflict = false;
857 } else {
858 # switch from section editing to normal editing in edit conflict
859 if($this->isConflict) {
860 # Attempt merge
861 if( $this->mergeChangesInto( $text ) ){
862 // Successful merge! Maybe we should tell the user the good news?
863 $this->isConflict = false;
864 wfDebug( "EditPage::editForm Suppressing edit conflict, successful merge.\n" );
865 } else {
866 $this->section = '';
867 $this->textbox1 = $text;
868 wfDebug( "EditPage::editForm Keeping edit conflict, failed merge.\n" );
869 }
870 }
871 }
872
873 if ( $this->isConflict ) {
874 wfProfileOut( $fname );
875 return self::AS_CONFLICT_DETECTED;
876 }
877
878 $oldtext = $this->mArticle->getContent();
879
880 // Run post-section-merge edit filter
881 if ( !wfRunHooks( 'EditFilterMerged', array( $this, $text, &$this->hookError ) ) ) {
882 # Error messages etc. could be handled within the hook...
883 wfProfileOut( $fname );
884 return false;
885 }
886
887 # Handle the user preference to force summaries here, but not for null edits
888 if( $this->section != 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary')
889 && 0 != strcmp($oldtext, $text) && !Article::getRedirectAutosummary( $text )) {
890 if( md5( $this->summary ) == $this->autoSumm ) {
891 $this->missingSummary = true;
892 wfProfileOut( $fname );
893 return self::AS_SUMMARY_NEEDED;
894 }
895 }
896
897 #And a similar thing for new sections
898 if( $this->section == 'new' && !$this->allowBlankSummary && $wgUser->getOption( 'forceeditsummary' ) ) {
899 if (trim($this->summary) == '') {
900 $this->missingSummary = true;
901 wfProfileOut( $fname );
902 return self::AS_SUMMARY_NEEDED;
903 }
904 }
905
906 # All's well
907 wfProfileIn( "$fname-sectionanchor" );
908 $sectionanchor = '';
909 if( $this->section == 'new' ) {
910 if ( $this->textbox1 == '' ) {
911 $this->missingComment = true;
912 return self::AS_TEXTBOX_EMPTY;
913 }
914 if( $this->summary != '' ) {
915 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $this->summary );
916 # This is a new section, so create a link to the new section
917 # in the revision summary.
918 $cleanSummary = $wgParser->stripSectionName( $this->summary );
919 $this->summary = wfMsgForContent( 'newsectionsummary', $cleanSummary );
920 }
921 } elseif( $this->section != '' ) {
922 # Try to get a section anchor from the section source, redirect to edited section if header found
923 # XXX: might be better to integrate this into Article::replaceSection
924 # for duplicate heading checking and maybe parsing
925 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
926 # we can't deal with anchors, includes, html etc in the header for now,
927 # headline would need to be parsed to improve this
928 if($hasmatch and strlen($matches[2]) > 0) {
929 $sectionanchor = $wgParser->guessSectionNameFromWikiText( $matches[2] );
930 }
931 }
932 wfProfileOut( "$fname-sectionanchor" );
933
934 // Save errors may fall down to the edit form, but we've now
935 // merged the section into full text. Clear the section field
936 // so that later submission of conflict forms won't try to
937 // replace that into a duplicated mess.
938 $this->textbox1 = $text;
939 $this->section = '';
940
941 // Check for length errors again now that the section is merged in
942 $this->kblength = (int)(strlen( $text ) / 1024);
943 if ( $this->kblength > $wgMaxArticleSize ) {
944 $this->tooBig = true;
945 wfProfileOut( $fname );
946 return self::AS_MAX_ARTICLE_SIZE_EXCEDED;
947 }
948
949 # update the article here
950 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
951 $this->watchthis, $bot, $sectionanchor ) ) {
952 wfProfileOut( $fname );
953 return self::AS_SUCCESS_UPDATE;
954 } else {
955 $this->isConflict = true;
956 }
957 wfProfileOut( $fname );
958 return self::AS_END;
959 }
960
961 /**
962 * Initialise form fields in the object
963 * Called on the first invocation, e.g. when a user clicks an edit link
964 */
965 function initialiseForm() {
966 $this->edittime = $this->mArticle->getTimestamp();
967 $this->summary = '';
968 $this->textbox1 = $this->getContent(false);
969 if ($this->textbox1 === false) return false;
970
971 if ( !$this->mArticle->exists() && $this->mTitle->getNamespace() == NS_MEDIAWIKI )
972 $this->textbox1 = wfMsgWeirdKey( $this->mTitle->getText() );
973 wfProxyCheck();
974 return true;
975 }
976
977 /**
978 * Send the edit form and related headers to $wgOut
979 * @param $formCallback Optional callable that takes an OutputPage
980 * parameter; will be called during form output
981 * near the top, for captchas and the like.
982 */
983 function showEditForm( $formCallback=null ) {
984 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize, $wgTitle;
985
986 $fname = 'EditPage::showEditForm';
987 wfProfileIn( $fname );
988
989 $sk = $wgUser->getSkin();
990
991 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
992
993 $wgOut->setRobotpolicy( 'noindex,nofollow' );
994
995 # Enabled article-related sidebar, toplinks, etc.
996 $wgOut->setArticleRelated( true );
997
998 if ( $this->formtype == 'preview' ) {
999 $wgOut->setPageTitleActionText( wfMsg( 'preview' ) );
1000 }
1001
1002 if ( $this->isConflict ) {
1003 $s = wfMsg( 'editconflict', $wgTitle->getPrefixedText() );
1004 $wgOut->setPageTitle( $s );
1005 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
1006
1007 $this->textbox2 = $this->textbox1;
1008 $this->textbox1 = $this->getContent();
1009 $this->edittime = $this->mArticle->getTimestamp();
1010 } else {
1011 if( $this->section != '' ) {
1012 if( $this->section == 'new' ) {
1013 $s = wfMsg('editingcomment', $wgTitle->getPrefixedText() );
1014 } else {
1015 $s = wfMsg('editingsection', $wgTitle->getPrefixedText() );
1016 $matches = array();
1017 if( !$this->summary && !$this->preview && !$this->diff ) {
1018 preg_match( "/^(=+)(.+)\\1/mi",
1019 $this->textbox1,
1020 $matches );
1021 if( !empty( $matches[2] ) ) {
1022 global $wgParser;
1023 $this->summary = "/* " .
1024 $wgParser->stripSectionName(trim($matches[2])) .
1025 " */ ";
1026 }
1027 }
1028 }
1029 } else {
1030 $s = wfMsg( 'editing', $wgTitle->getPrefixedText() );
1031 }
1032 $wgOut->setPageTitle( $s );
1033
1034 if ( $this->missingComment ) {
1035 $wgOut->addWikiText( '<div id="mw-missingcommenttext">' . wfMsg( 'missingcommenttext' ) . '</div>' );
1036 }
1037
1038 if( $this->missingSummary && $this->section != 'new' ) {
1039 $wgOut->addWikiText( '<div id="mw-missingsummary">' . wfMsg( 'missingsummary' ) . '</div>' );
1040 }
1041
1042 if( $this->missingSummary && $this->section == 'new' ) {
1043 $wgOut->addWikiText( '<div id="mw-missingcommentheader">' . wfMsg( 'missingcommentheader' ) . '</div>' );
1044 }
1045
1046 if( $this->hookError !== '' ) {
1047 $wgOut->addWikiText( $this->hookError );
1048 }
1049
1050 if ( !$this->checkUnicodeCompliantBrowser() ) {
1051 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
1052 }
1053 if ( isset( $this->mArticle ) && isset( $this->mArticle->mRevision ) ) {
1054 // Let sysop know that this will make private content public if saved
1055
1056 if( !$this->mArticle->mRevision->userCan( Revision::DELETED_TEXT ) ) {
1057 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-permission' ) );
1058 } else if( $this->mArticle->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
1059 $wgOut->addWikiText( wfMsg( 'rev-deleted-text-view' ) );
1060 }
1061
1062 if( !$this->mArticle->mRevision->isCurrent() ) {
1063 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
1064 $wgOut->addWikiText( wfMsg( 'editingold' ) );
1065 }
1066 }
1067 }
1068
1069 if( wfReadOnly() ) {
1070 $wgOut->addHTML( '<div id="mw-read-only-warning">'.wfMsgWikiHTML( 'readonlywarning' ).'</div>' );
1071 } elseif( $wgUser->isAnon() && $this->formtype != 'preview' ) {
1072 $wgOut->addHTML( '<div id="mw-anon-edit-warning">'.wfMsgWikiHTML( 'anoneditwarning' ).'</div>' );
1073 } else {
1074 if( $this->isCssJsSubpage && $this->formtype != 'preview' ) {
1075 # Check the skin exists
1076 if( $this->isValidCssJsSubpage ) {
1077 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ) );
1078 } else {
1079 $wgOut->addWikiText( wfMsg( 'userinvalidcssjstitle', $wgTitle->getSkinFromCssJsSubpage() ) );
1080 }
1081 }
1082 }
1083
1084 if( $this->mTitle->getNamespace() == NS_MEDIAWIKI ) {
1085 # Show a warning if editing an interface message
1086 $wgOut->addWikiText( wfMsg( 'editinginterface' ) );
1087 } elseif( $this->mTitle->isProtected( 'edit' ) ) {
1088 # Is the title semi-protected?
1089 if( $this->mTitle->isSemiProtected() ) {
1090 $notice = wfMsg( 'semiprotectedpagewarning' );
1091 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) || $notice == '-' )
1092 $notice = '';
1093 } else {
1094 # Then it must be protected based on static groups (regular)
1095 $notice = wfMsg( 'protectedpagewarning' );
1096 }
1097 $wgOut->addWikiText( $notice );
1098 }
1099 if ( $this->mTitle->isCascadeProtected() ) {
1100 # Is this page under cascading protection from some source pages?
1101 list($cascadeSources, /* $restrictions */) = $this->mTitle->getCascadeProtectionSources();
1102 if ( count($cascadeSources) > 0 ) {
1103 # Explain, and list the titles responsible
1104 $notice = wfMsgExt( 'cascadeprotectedwarning', array('parsemag'), count($cascadeSources) ) . "\n";
1105 foreach( $cascadeSources as $page ) {
1106 $notice .= '* [[:' . $page->getPrefixedText() . "]]\n";
1107 }
1108 }
1109 $wgOut->addWikiText( $notice );
1110 }
1111 if( !$this->mTitle->exists() && $this->mTitle->getRestrictions( 'create' ) != array() ){
1112 $wgOut->addWikiText( wfMsg( 'titleprotectedwarning' ) );
1113 }
1114
1115 if ( $this->kblength === false ) {
1116 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
1117 }
1118 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
1119 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize ) );
1120 } elseif( $this->kblength > 29 ) {
1121 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ) );
1122 }
1123
1124 #need to parse the preview early so that we know which templates are used,
1125 #otherwise users with "show preview after edit box" will get a blank list
1126 if ( $this->formtype == 'preview' ) {
1127 $previewOutput = $this->getPreviewText();
1128 }
1129
1130 $rows = $wgUser->getIntOption( 'rows' );
1131 $cols = $wgUser->getIntOption( 'cols' );
1132
1133 $ew = $wgUser->getOption( 'editwidth' );
1134 if ( $ew ) $ew = " style=\"width:100%\"";
1135 else $ew = '';
1136
1137 $q = 'action=submit';
1138 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
1139 $action = $wgTitle->escapeLocalURL( $q );
1140
1141 $summary = wfMsg('summary');
1142 $subject = wfMsg('subject');
1143
1144 $cancel = $sk->makeKnownLink( $wgTitle->getPrefixedText(),
1145 wfMsgExt('cancel', array('parseinline')) );
1146 $edithelpurl = Skin::makeInternalOrExternalUrl( wfMsgForContent( 'edithelppage' ));
1147 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
1148 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
1149 htmlspecialchars( wfMsg( 'newwindow' ) );
1150
1151 global $wgRightsText;
1152 $copywarn = "<div id=\"editpage-copywarn\">\n" .
1153 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
1154 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
1155 $wgRightsText ) . "\n</div>";
1156
1157 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
1158 # prepare toolbar for edit buttons
1159 $toolbar = $this->getEditToolbar();
1160 } else {
1161 $toolbar = '';
1162 }
1163
1164 // activate checkboxes if user wants them to be always active
1165 if( !$this->preview && !$this->diff ) {
1166 # Sort out the "watch" checkbox
1167 if( $wgUser->getOption( 'watchdefault' ) ) {
1168 # Watch all edits
1169 $this->watchthis = true;
1170 } elseif( $wgUser->getOption( 'watchcreations' ) && !$this->mTitle->exists() ) {
1171 # Watch creations
1172 $this->watchthis = true;
1173 } elseif( $this->mTitle->userIsWatching() ) {
1174 # Already watched
1175 $this->watchthis = true;
1176 }
1177
1178 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
1179 }
1180
1181 $wgOut->addHTML( $this->editFormPageTop );
1182
1183 if ( $wgUser->getOption( 'previewontop' ) ) {
1184
1185 if ( 'preview' == $this->formtype ) {
1186 $this->showPreview( $previewOutput );
1187 } else {
1188 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1189 }
1190
1191 if ( 'diff' == $this->formtype ) {
1192 $this->showDiff();
1193 }
1194 }
1195
1196
1197 $wgOut->addHTML( $this->editFormTextTop );
1198
1199 # if this is a comment, show a subject line at the top, which is also the edit summary.
1200 # Otherwise, show a summary field at the bottom
1201 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
1202 if( $this->section == 'new' ) {
1203 $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 />";
1204 $editsummary = '';
1205 $subjectpreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('subject-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1206 $summarypreview = '';
1207 } else {
1208 $commentsubject = '';
1209 $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 />";
1210 $summarypreview = $summarytext && $this->preview ? "<div class=\"mw-summary-preview\">".wfMsg('summary-preview').':'.$sk->commentBlock( $this->summary, $this->mTitle )."</div>\n" : '';
1211 $subjectpreview = '';
1212 }
1213
1214 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
1215 if( !$this->preview && !$this->diff ) {
1216 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
1217 }
1218 $templates = ($this->preview || $this->section != '') ? $this->mPreviewTemplates : $this->mArticle->getUsedTemplates();
1219 $formattedtemplates = $sk->formatTemplates( $templates, $this->preview, $this->section != '');
1220
1221 global $wgUseMetadataEdit ;
1222 if ( $wgUseMetadataEdit ) {
1223 $metadata = $this->mMetaData ;
1224 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
1225 $top = wfMsgWikiHtml( 'metadata_help' );
1226 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
1227 }
1228 else $metadata = "" ;
1229
1230 $hidden = '';
1231 $recreate = '';
1232 if ($this->deletedSinceEdit) {
1233 if ( 'save' != $this->formtype ) {
1234 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
1235 } else {
1236 // Hide the toolbar and edit area, use can click preview to get it back
1237 // Add an confirmation checkbox and explanation.
1238 $toolbar = '';
1239 $hidden = 'type="hidden" style="display:none;"';
1240 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
1241 $recreate .=
1242 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
1243 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
1244 }
1245 }
1246
1247 $tabindex = 2;
1248
1249 $checkboxes = self::getCheckboxes( $tabindex, $sk,
1250 array( 'minor' => $this->minoredit, 'watch' => $this->watchthis ) );
1251
1252 $checkboxhtml = implode( $checkboxes, "\n" );
1253
1254 $buttons = $this->getEditButtons( $tabindex );
1255 $buttonshtml = implode( $buttons, "\n" );
1256
1257 $safemodehtml = $this->checkUnicodeCompliantBrowser()
1258 ? '' : Xml::hidden( 'safemode', '1' );
1259
1260 $wgOut->addHTML( <<<END
1261 {$toolbar}
1262 <form id="editform" name="editform" method="post" action="$action" enctype="multipart/form-data">
1263 END
1264 );
1265
1266 if( is_callable( $formCallback ) ) {
1267 call_user_func_array( $formCallback, array( &$wgOut ) );
1268 }
1269
1270 wfRunHooks( 'EditPage::showEditForm:fields', array( &$this, &$wgOut ) );
1271
1272 // Put these up at the top to ensure they aren't lost on early form submission
1273 $wgOut->addHTML( "
1274 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
1275 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
1276 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
1277 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
1278
1279 $wgOut->addHTML( <<<END
1280 $recreate
1281 {$commentsubject}
1282 {$subjectpreview}
1283 {$this->editFormTextBeforeContent}
1284 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
1285 cols='{$cols}'{$ew} $hidden>
1286 END
1287 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
1288 "
1289 </textarea>
1290 " );
1291
1292 $wgOut->addWikiText( $copywarn );
1293 $wgOut->addHTML( $this->editFormTextAfterWarn );
1294 $wgOut->addHTML( "
1295 {$metadata}
1296 {$editsummary}
1297 {$summarypreview}
1298 {$checkboxhtml}
1299 {$safemodehtml}
1300 ");
1301
1302 $wgOut->addHTML(
1303 "<div class='editButtons'>
1304 {$buttonshtml}
1305 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1306 </div><!-- editButtons -->
1307 </div><!-- editOptions -->");
1308
1309 $wgOut->addHtml( '<div class="mw-editTools">' );
1310 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1311 $wgOut->addHtml( '</div>' );
1312
1313 $wgOut->addHTML( $this->editFormTextAfterTools );
1314
1315 $wgOut->addHTML( "
1316 <div class='templatesUsed'>
1317 {$formattedtemplates}
1318 </div>
1319 " );
1320
1321 /**
1322 * To make it harder for someone to slip a user a page
1323 * which submits an edit form to the wiki without their
1324 * knowledge, a random token is associated with the login
1325 * session. If it's not passed back with the submission,
1326 * we won't save the page, or render user JavaScript and
1327 * CSS previews.
1328 *
1329 * For anon editors, who may not have a session, we just
1330 * include the constant suffix to prevent editing from
1331 * broken text-mangling proxies.
1332 */
1333 $token = htmlspecialchars( $wgUser->editToken() );
1334 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1335
1336
1337 # If a blank edit summary was previously provided, and the appropriate
1338 # user preference is active, pass a hidden tag here. This will stop the
1339 # user being bounced back more than once in the event that a summary
1340 # is not required.
1341 if( $this->missingSummary ) {
1342 $wgOut->addHTML( "<input type=\"hidden\" name=\"wpIgnoreBlankSummary\" value=\"1\" />\n" );
1343 }
1344
1345 # For a bit more sophisticated detection of blank summaries, hash the
1346 # automatic one and pass that in a hidden field.
1347 $autosumm = $this->autoSumm ? $this->autoSumm : md5( $this->summary );
1348 $wgOut->addHtml( wfHidden( 'wpAutoSummary', $autosumm ) );
1349
1350 if ( $this->isConflict ) {
1351 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1352
1353 $de = new DifferenceEngine( $this->mTitle );
1354 $de->setText( $this->textbox2, $this->textbox1 );
1355 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1356
1357 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1358 $wgOut->addHTML( "<textarea tabindex='6' id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}'>"
1359 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1360 }
1361 $wgOut->addHTML( $this->editFormTextBottom );
1362 $wgOut->addHTML( "</form>\n" );
1363 if ( !$wgUser->getOption( 'previewontop' ) ) {
1364
1365 if ( $this->formtype == 'preview') {
1366 $this->showPreview( $previewOutput );
1367 } else {
1368 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1369 }
1370
1371 if ( $this->formtype == 'diff') {
1372 $this->showDiff();
1373 }
1374
1375 }
1376
1377 wfProfileOut( $fname );
1378 }
1379
1380 /**
1381 * Append preview output to $wgOut.
1382 * Includes category rendering if this is a category page.
1383 *
1384 * @param string $text The HTML to be output for the preview.
1385 */
1386 private function showPreview( $text ) {
1387 global $wgOut;
1388
1389 $wgOut->addHTML( '<div id="wikiPreview">' );
1390 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1391 $this->mArticle->openShowCategory();
1392 }
1393 wfRunHooks( 'OutputPageBeforeHTML',array( &$wgOut, &$text ) );
1394 $wgOut->addHTML( $text );
1395 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1396 $this->mArticle->closeShowCategory();
1397 }
1398 $wgOut->addHTML( '</div>' );
1399 }
1400
1401 /**
1402 * Live Preview lets us fetch rendered preview page content and
1403 * add it to the page without refreshing the whole page.
1404 * If not supported by the browser it will fall through to the normal form
1405 * submission method.
1406 *
1407 * This function outputs a script tag to support live preview, and
1408 * returns an onclick handler which should be added to the attributes
1409 * of the preview button
1410 */
1411 function doLivePreviewScript() {
1412 global $wgStylePath, $wgJsMimeType, $wgStyleVersion, $wgOut, $wgTitle;
1413 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1414 htmlspecialchars( "$wgStylePath/common/preview.js?$wgStyleVersion" ) .
1415 '"></script>' . "\n" );
1416 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1417 return "return !lpDoPreview(" .
1418 "editform.wpTextbox1.value," .
1419 '"' . $liveAction . '"' . ")";
1420 }
1421
1422 function getLastDelete() {
1423 $dbr = wfGetDB( DB_SLAVE );
1424 $fname = 'EditPage::getLastDelete';
1425 $res = $dbr->select(
1426 array( 'logging', 'user' ),
1427 array( 'log_type',
1428 'log_action',
1429 'log_timestamp',
1430 'log_user',
1431 'log_namespace',
1432 'log_title',
1433 'log_comment',
1434 'log_params',
1435 'user_name', ),
1436 array( 'log_namespace' => $this->mTitle->getNamespace(),
1437 'log_title' => $this->mTitle->getDBkey(),
1438 'log_type' => 'delete',
1439 'log_action' => 'delete',
1440 'user_id=log_user' ),
1441 $fname,
1442 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1443
1444 if($dbr->numRows($res) == 1) {
1445 while ( $x = $dbr->fetchObject ( $res ) )
1446 $data = $x;
1447 $dbr->freeResult ( $res ) ;
1448 } else {
1449 $data = null;
1450 }
1451 return $data;
1452 }
1453
1454 /**
1455 * @todo document
1456 */
1457 function getPreviewText() {
1458 global $wgOut, $wgUser, $wgTitle, $wgParser;
1459
1460 $fname = 'EditPage::getPreviewText';
1461 wfProfileIn( $fname );
1462
1463 if ( $this->mTriedSave && !$this->mTokenOk ) {
1464 if ( $this->mTokenOkExceptSuffix ) {
1465 $note = wfMsg( 'token_suffix_mismatch' );
1466 } else {
1467 $note = wfMsg( 'session_fail_preview' );
1468 }
1469 } else {
1470 $note = wfMsg( 'previewnote' );
1471 }
1472
1473 $parserOptions = ParserOptions::newFromUser( $wgUser );
1474 $parserOptions->setEditSection( false );
1475
1476 global $wgRawHtml;
1477 if( $wgRawHtml && !$this->mTokenOk ) {
1478 // Could be an offsite preview attempt. This is very unsafe if
1479 // HTML is enabled, as it could be an attack.
1480 return $wgOut->parse( "<div class='previewnote'>" .
1481 wfMsg( 'session_fail_preview_html' ) . "</div>" );
1482 }
1483
1484 # don't parse user css/js, show message about preview
1485 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1486
1487 if ( $this->isCssJsSubpage ) {
1488 if(preg_match("/\\.css$/", $this->mTitle->getText() ) ) {
1489 $previewtext = wfMsg('usercsspreview');
1490 } else if(preg_match("/\\.js$/", $this->mTitle->getText() ) ) {
1491 $previewtext = wfMsg('userjspreview');
1492 }
1493 $parserOptions->setTidy(true);
1494 $parserOutput = $wgParser->parse( $previewtext , $this->mTitle, $parserOptions );
1495 $wgOut->addHTML( $parserOutput->mText );
1496 $previewHTML = '';
1497 } else {
1498 $toparse = $this->textbox1;
1499
1500 # If we're adding a comment, we need to show the
1501 # summary as the headline
1502 if($this->section=="new" && $this->summary!="") {
1503 $toparse="== {$this->summary} ==\n\n".$toparse;
1504 }
1505
1506 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1507 $parserOptions->setTidy(true);
1508 $parserOptions->enableLimitReport();
1509 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1510 $this->mTitle, $parserOptions );
1511
1512 $previewHTML = $parserOutput->getText();
1513 $wgOut->addParserOutputNoText( $parserOutput );
1514
1515 # ParserOutput might have altered the page title, so reset it
1516 $wgOut->setPageTitle( wfMsg( 'editing', $wgTitle->getPrefixedText() ) );
1517
1518 foreach ( $parserOutput->getTemplates() as $ns => $template)
1519 foreach ( array_keys( $template ) as $dbk)
1520 $this->mPreviewTemplates[] = Title::makeTitle($ns, $dbk);
1521
1522 if ( count( $parserOutput->getWarnings() ) ) {
1523 $note .= "\n\n" . implode( "\n\n", $parserOutput->getWarnings() );
1524 }
1525 }
1526
1527 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1528 "<div class='previewnote'>" . $wgOut->parse( $note ) . "</div>\n";
1529 if ( $this->isConflict ) {
1530 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1531 }
1532
1533 wfProfileOut( $fname );
1534 return $previewhead . $previewHTML;
1535 }
1536
1537 /**
1538 * Call the stock "user is blocked" page
1539 */
1540 function blockedPage() {
1541 global $wgOut, $wgUser;
1542 $wgOut->blockedPage( false ); # Standard block notice on the top, don't 'return'
1543
1544 # If the user made changes, preserve them when showing the markup
1545 # (This happens when a user is blocked during edit, for instance)
1546 $first = $this->firsttime || ( !$this->save && $this->textbox1 == '' );
1547 if( $first ) {
1548 $source = $this->mTitle->exists() ? $this->getContent() : false;
1549 } else {
1550 $source = $this->textbox1;
1551 }
1552
1553 # Spit out the source or the user's modified version
1554 if( $source !== false ) {
1555 $rows = $wgUser->getOption( 'rows' );
1556 $cols = $wgUser->getOption( 'cols' );
1557 $attribs = array( 'id' => 'wpTextbox1', 'name' => 'wpTextbox1', 'cols' => $cols, 'rows' => $rows, 'readonly' => 'readonly' );
1558 $wgOut->addHtml( '<hr />' );
1559 $wgOut->addWikiText( wfMsg( $first ? 'blockedoriginalsource' : 'blockededitsource', $this->mTitle->getPrefixedText() ) );
1560 $wgOut->addHtml( wfOpenElement( 'textarea', $attribs ) . htmlspecialchars( $source ) . wfCloseElement( 'textarea' ) );
1561 }
1562 }
1563
1564 /**
1565 * Produce the stock "please login to edit pages" page
1566 */
1567 function userNotLoggedInPage() {
1568 global $wgUser, $wgOut, $wgTitle;
1569 $skin = $wgUser->getSkin();
1570
1571 $loginTitle = SpecialPage::getTitleFor( 'Userlogin' );
1572 $loginLink = $skin->makeKnownLinkObj( $loginTitle, wfMsgHtml( 'loginreqlink' ), 'returnto=' . $wgTitle->getPrefixedUrl() );
1573
1574 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1575 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1576 $wgOut->setArticleRelated( false );
1577
1578 $wgOut->addHtml( wfMsgWikiHtml( 'whitelistedittext', $loginLink ) );
1579 $wgOut->returnToMain( false, $wgTitle );
1580 }
1581
1582 /**
1583 * Creates a basic error page which informs the user that
1584 * they have attempted to edit a nonexistant section.
1585 */
1586 function noSuchSectionPage() {
1587 global $wgOut, $wgTitle;
1588
1589 $wgOut->setPageTitle( wfMsg( 'nosuchsectiontitle' ) );
1590 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1591 $wgOut->setArticleRelated( false );
1592
1593 $wgOut->addWikiText( wfMsg( 'nosuchsectiontext', $this->section ) );
1594 $wgOut->returnToMain( false, $wgTitle );
1595 }
1596
1597 /**
1598 * Produce the stock "your edit contains spam" page
1599 *
1600 * @param $match Text which triggered one or more filters
1601 */
1602 function spamPage( $match = false ) {
1603 global $wgOut, $wgTitle;
1604
1605 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1606 $wgOut->setRobotPolicy( 'noindex,nofollow' );
1607 $wgOut->setArticleRelated( false );
1608
1609 $wgOut->addHtml( '<div id="spamprotected">' );
1610 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1611 if ( $match )
1612 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch',wfEscapeWikiText( $match ) ) );
1613 $wgOut->addHtml( '</div>' );
1614
1615 $wgOut->returnToMain( false, $wgTitle );
1616 }
1617
1618 /**
1619 * @private
1620 * @todo document
1621 */
1622 function mergeChangesInto( &$editText ){
1623 $fname = 'EditPage::mergeChangesInto';
1624 wfProfileIn( $fname );
1625
1626 $db = wfGetDB( DB_MASTER );
1627
1628 // This is the revision the editor started from
1629 $baseRevision = Revision::loadFromTimestamp(
1630 $db, $this->mTitle, $this->edittime );
1631 if( is_null( $baseRevision ) ) {
1632 wfProfileOut( $fname );
1633 return false;
1634 }
1635 $baseText = $baseRevision->getText();
1636
1637 // The current state, we want to merge updates into it
1638 $currentRevision = Revision::loadFromTitle(
1639 $db, $this->mTitle );
1640 if( is_null( $currentRevision ) ) {
1641 wfProfileOut( $fname );
1642 return false;
1643 }
1644 $currentText = $currentRevision->getText();
1645
1646 $result = '';
1647 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1648 $editText = $result;
1649 wfProfileOut( $fname );
1650 return true;
1651 } else {
1652 wfProfileOut( $fname );
1653 return false;
1654 }
1655 }
1656
1657 /**
1658 * Check if the browser is on a blacklist of user-agents known to
1659 * mangle UTF-8 data on form submission. Returns true if Unicode
1660 * should make it through, false if it's known to be a problem.
1661 * @return bool
1662 * @private
1663 */
1664 function checkUnicodeCompliantBrowser() {
1665 global $wgBrowserBlackList;
1666 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1667 // No User-Agent header sent? Trust it by default...
1668 return true;
1669 }
1670 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1671 foreach ( $wgBrowserBlackList as $browser ) {
1672 if ( preg_match($browser, $currentbrowser) ) {
1673 return false;
1674 }
1675 }
1676 return true;
1677 }
1678
1679 /**
1680 * @deprecated use $wgParser->stripSectionName()
1681 */
1682 function pseudoParseSectionAnchor( $text ) {
1683 global $wgParser;
1684 return $wgParser->stripSectionName( $text );
1685 }
1686
1687 /**
1688 * Format an anchor fragment as it would appear for a given section name
1689 * @param string $text
1690 * @return string
1691 * @private
1692 */
1693 function sectionAnchor( $text ) {
1694 global $wgParser;
1695 return $wgParser->guessSectionNameFromWikiText( $text );
1696 }
1697
1698 /**
1699 * Shows a bulletin board style toolbar for common editing functions.
1700 * It can be disabled in the user preferences.
1701 * The necessary JavaScript code can be found in style/wikibits.js.
1702 */
1703 function getEditToolbar() {
1704 global $wgStylePath, $wgContLang, $wgJsMimeType;
1705
1706 /**
1707 * toolarray an array of arrays which each include the filename of
1708 * the button image (without path), the opening tag, the closing tag,
1709 * and optionally a sample text that is inserted between the two when no
1710 * selection is highlighted.
1711 * The tip text is shown when the user moves the mouse over the button.
1712 *
1713 * Already here are accesskeys (key), which are not used yet until someone
1714 * can figure out a way to make them work in IE. However, we should make
1715 * sure these keys are not defined on the edit page.
1716 */
1717 $toolarray = array(
1718 array( 'image' => 'button_bold.png',
1719 'id' => 'mw-editbutton-bold',
1720 'open' => '\\\'\\\'\\\'',
1721 'close' => '\\\'\\\'\\\'',
1722 'sample'=> wfMsg('bold_sample'),
1723 'tip' => wfMsg('bold_tip'),
1724 'key' => 'B'
1725 ),
1726 array( 'image' => 'button_italic.png',
1727 'id' => 'mw-editbutton-italic',
1728 'open' => '\\\'\\\'',
1729 'close' => '\\\'\\\'',
1730 'sample'=> wfMsg('italic_sample'),
1731 'tip' => wfMsg('italic_tip'),
1732 'key' => 'I'
1733 ),
1734 array( 'image' => 'button_link.png',
1735 'id' => 'mw-editbutton-link',
1736 'open' => '[[',
1737 'close' => ']]',
1738 'sample'=> wfMsg('link_sample'),
1739 'tip' => wfMsg('link_tip'),
1740 'key' => 'L'
1741 ),
1742 array( 'image' => 'button_extlink.png',
1743 'id' => 'mw-editbutton-extlink',
1744 'open' => '[',
1745 'close' => ']',
1746 'sample'=> wfMsg('extlink_sample'),
1747 'tip' => wfMsg('extlink_tip'),
1748 'key' => 'X'
1749 ),
1750 array( 'image' => 'button_headline.png',
1751 'id' => 'mw-editbutton-headline',
1752 'open' => "\\n== ",
1753 'close' => " ==\\n",
1754 'sample'=> wfMsg('headline_sample'),
1755 'tip' => wfMsg('headline_tip'),
1756 'key' => 'H'
1757 ),
1758 array( 'image' => 'button_image.png',
1759 'id' => 'mw-editbutton-image',
1760 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).":",
1761 'close' => ']]',
1762 'sample'=> wfMsg('image_sample'),
1763 'tip' => wfMsg('image_tip'),
1764 'key' => 'D'
1765 ),
1766 array( 'image' => 'button_media.png',
1767 'id' => 'mw-editbutton-media',
1768 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1769 'close' => ']]',
1770 'sample'=> wfMsg('media_sample'),
1771 'tip' => wfMsg('media_tip'),
1772 'key' => 'M'
1773 ),
1774 array( 'image' => 'button_math.png',
1775 'id' => 'mw-editbutton-math',
1776 'open' => "<math>",
1777 'close' => "<\\/math>",
1778 'sample'=> wfMsg('math_sample'),
1779 'tip' => wfMsg('math_tip'),
1780 'key' => 'C'
1781 ),
1782 array( 'image' => 'button_nowiki.png',
1783 'id' => 'mw-editbutton-nowiki',
1784 'open' => "<nowiki>",
1785 'close' => "<\\/nowiki>",
1786 'sample'=> wfMsg('nowiki_sample'),
1787 'tip' => wfMsg('nowiki_tip'),
1788 'key' => 'N'
1789 ),
1790 array( 'image' => 'button_sig.png',
1791 'id' => 'mw-editbutton-signature',
1792 'open' => '--~~~~',
1793 'close' => '',
1794 'sample'=> '',
1795 'tip' => wfMsg('sig_tip'),
1796 'key' => 'Y'
1797 ),
1798 array( 'image' => 'button_hr.png',
1799 'id' => 'mw-editbutton-hr',
1800 'open' => "\\n----\\n",
1801 'close' => '',
1802 'sample'=> '',
1803 'tip' => wfMsg('hr_tip'),
1804 'key' => 'R'
1805 )
1806 );
1807 $toolbar = "<div id='toolbar'>\n";
1808 $toolbar.="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1809
1810 foreach($toolarray as $tool) {
1811
1812 $cssId = $tool['id'];
1813 $image=$wgStylePath.'/common/images/'.$tool['image'];
1814 $open=$tool['open'];
1815 $close=$tool['close'];
1816 $sample = wfEscapeJsString( $tool['sample'] );
1817
1818 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1819 // Older browsers show a "speedtip" type message only for ALT.
1820 // Ideally these should be different, realistically they
1821 // probably don't need to be.
1822 $tip = wfEscapeJsString( $tool['tip'] );
1823
1824 #$key = $tool["key"];
1825
1826 $toolbar.="addButton('$image','$tip','$open','$close','$sample','$cssId');\n";
1827 }
1828
1829 $toolbar.="/*]]>*/\n</script>";
1830 $toolbar.="\n</div>";
1831 return $toolbar;
1832 }
1833
1834 /**
1835 * Returns an array of html code of the following checkboxes:
1836 * minor and watch
1837 *
1838 * @param $tabindex Current tabindex
1839 * @param $skin Skin object
1840 * @param $checked Array of checkbox => bool, where bool indicates the checked
1841 * status of the checkbox
1842 *
1843 * @return array
1844 */
1845 public static function getCheckboxes( &$tabindex, $skin, $checked ) {
1846 global $wgUser;
1847
1848 $checkboxes = array();
1849
1850 $checkboxes['minor'] = '';
1851 $minorLabel = wfMsgExt('minoredit', array('parseinline'));
1852 if ( $wgUser->isAllowed('minoredit') ) {
1853 $attribs = array(
1854 'tabindex' => ++$tabindex,
1855 'accesskey' => wfMsg( 'accesskey-minoredit' ),
1856 'id' => 'wpMinoredit',
1857 );
1858 $checkboxes['minor'] =
1859 Xml::check( 'wpMinoredit', $checked['minor'], $attribs ) .
1860 "&nbsp;<label for='wpMinoredit'".$skin->tooltipAndAccesskey('minoredit').">{$minorLabel}</label>";
1861 }
1862
1863 $watchLabel = wfMsgExt('watchthis', array('parseinline'));
1864 $checkboxes['watch'] = '';
1865 if ( $wgUser->isLoggedIn() ) {
1866 $attribs = array(
1867 'tabindex' => ++$tabindex,
1868 'accesskey' => wfMsg( 'accesskey-watch' ),
1869 'id' => 'wpWatchthis',
1870 );
1871 $checkboxes['watch'] =
1872 Xml::check( 'wpWatchthis', $checked['watch'], $attribs ) .
1873 "&nbsp;<label for='wpWatchthis'".$skin->tooltipAndAccesskey('watch').">{$watchLabel}</label>";
1874 }
1875 return $checkboxes;
1876 }
1877
1878 /**
1879 * Returns an array of html code of the following buttons:
1880 * save, diff, preview and live
1881 *
1882 * @param $tabindex Current tabindex
1883 *
1884 * @return array
1885 */
1886 public function getEditButtons(&$tabindex) {
1887 global $wgLivePreview, $wgUser;
1888
1889 $buttons = array();
1890
1891 $temp = array(
1892 'id' => 'wpSave',
1893 'name' => 'wpSave',
1894 'type' => 'submit',
1895 'tabindex' => ++$tabindex,
1896 'value' => wfMsg('savearticle'),
1897 'accesskey' => wfMsg('accesskey-save'),
1898 'title' => wfMsg( 'tooltip-save' ).' ['.wfMsg( 'accesskey-save' ).']',
1899 );
1900 $buttons['save'] = wfElement('input', $temp, '');
1901
1902 ++$tabindex; // use the same for preview and live preview
1903 if ( $wgLivePreview && $wgUser->getOption( 'uselivepreview' ) ) {
1904 $temp = array(
1905 'id' => 'wpPreview',
1906 'name' => 'wpPreview',
1907 'type' => 'submit',
1908 'tabindex' => $tabindex,
1909 'value' => wfMsg('showpreview'),
1910 'accesskey' => '',
1911 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1912 'style' => 'display: none;',
1913 );
1914 $buttons['preview'] = wfElement('input', $temp, '');
1915
1916 $temp = array(
1917 'id' => 'wpLivePreview',
1918 'name' => 'wpLivePreview',
1919 'type' => 'submit',
1920 'tabindex' => $tabindex,
1921 'value' => wfMsg('showlivepreview'),
1922 'accesskey' => wfMsg('accesskey-preview'),
1923 'title' => '',
1924 'onclick' => $this->doLivePreviewScript(),
1925 );
1926 $buttons['live'] = wfElement('input', $temp, '');
1927 } else {
1928 $temp = array(
1929 'id' => 'wpPreview',
1930 'name' => 'wpPreview',
1931 'type' => 'submit',
1932 'tabindex' => $tabindex,
1933 'value' => wfMsg('showpreview'),
1934 'accesskey' => wfMsg('accesskey-preview'),
1935 'title' => wfMsg( 'tooltip-preview' ).' ['.wfMsg( 'accesskey-preview' ).']',
1936 );
1937 $buttons['preview'] = wfElement('input', $temp, '');
1938 $buttons['live'] = '';
1939 }
1940
1941 $temp = array(
1942 'id' => 'wpDiff',
1943 'name' => 'wpDiff',
1944 'type' => 'submit',
1945 'tabindex' => ++$tabindex,
1946 'value' => wfMsg('showdiff'),
1947 'accesskey' => wfMsg('accesskey-diff'),
1948 'title' => wfMsg( 'tooltip-diff' ).' ['.wfMsg( 'accesskey-diff' ).']',
1949 );
1950 $buttons['diff'] = wfElement('input', $temp, '');
1951
1952 return $buttons;
1953 }
1954
1955 /**
1956 * Output preview text only. This can be sucked into the edit page
1957 * via JavaScript, and saves the server time rendering the skin as
1958 * well as theoretically being more robust on the client (doesn't
1959 * disturb the edit box's undo history, won't eat your text on
1960 * failure, etc).
1961 *
1962 * @todo This doesn't include category or interlanguage links.
1963 * Would need to enhance it a bit, <s>maybe wrap them in XML
1964 * or something...</s> that might also require more skin
1965 * initialization, so check whether that's a problem.
1966 */
1967 function livePreview() {
1968 global $wgOut;
1969 $wgOut->disable();
1970 header( 'Content-type: text/xml; charset=utf-8' );
1971 header( 'Cache-control: no-cache' );
1972
1973 $previewText = $this->getPreviewText();
1974 #$categories = $skin->getCategoryLinks();
1975
1976 $s =
1977 '<?xml version="1.0" encoding="UTF-8" ?>' . "\n" .
1978 Xml::tags( 'livepreview', null,
1979 Xml::element( 'preview', null, $previewText )
1980 #. Xml::element( 'category', null, $categories )
1981 );
1982 echo $s;
1983 }
1984
1985
1986 /**
1987 * Get a diff between the current contents of the edit box and the
1988 * version of the page we're editing from.
1989 *
1990 * If this is a section edit, we'll replace the section as for final
1991 * save and then make a comparison.
1992 */
1993 function showDiff() {
1994 $oldtext = $this->mArticle->fetchContent();
1995 $newtext = $this->mArticle->replaceSection(
1996 $this->section, $this->textbox1, $this->summary, $this->edittime );
1997 $newtext = $this->mArticle->preSaveTransform( $newtext );
1998 $oldtitle = wfMsgExt( 'currentrev', array('parseinline') );
1999 $newtitle = wfMsgExt( 'yourtext', array('parseinline') );
2000 if ( $oldtext !== false || $newtext != '' ) {
2001 $de = new DifferenceEngine( $this->mTitle );
2002 $de->setText( $oldtext, $newtext );
2003 $difftext = $de->getDiff( $oldtitle, $newtitle );
2004 $de->showDiffStyle();
2005 } else {
2006 $difftext = '';
2007 }
2008
2009 global $wgOut;
2010 $wgOut->addHtml( '<div id="wikiDiff">' . $difftext . '</div>' );
2011 }
2012
2013 /**
2014 * Filter an input field through a Unicode de-armoring process if it
2015 * came from an old browser with known broken Unicode editing issues.
2016 *
2017 * @param WebRequest $request
2018 * @param string $field
2019 * @return string
2020 * @private
2021 */
2022 function safeUnicodeInput( $request, $field ) {
2023 $text = rtrim( $request->getText( $field ) );
2024 return $request->getBool( 'safemode' )
2025 ? $this->unmakesafe( $text )
2026 : $text;
2027 }
2028
2029 /**
2030 * Filter an output field through a Unicode armoring process if it is
2031 * going to an old browser with known broken Unicode editing issues.
2032 *
2033 * @param string $text
2034 * @return string
2035 * @private
2036 */
2037 function safeUnicodeOutput( $text ) {
2038 global $wgContLang;
2039 $codedText = $wgContLang->recodeForEdit( $text );
2040 return $this->checkUnicodeCompliantBrowser()
2041 ? $codedText
2042 : $this->makesafe( $codedText );
2043 }
2044
2045 /**
2046 * A number of web browsers are known to corrupt non-ASCII characters
2047 * in a UTF-8 text editing environment. To protect against this,
2048 * detected browsers will be served an armored version of the text,
2049 * with non-ASCII chars converted to numeric HTML character references.
2050 *
2051 * Preexisting such character references will have a 0 added to them
2052 * to ensure that round-trips do not alter the original data.
2053 *
2054 * @param string $invalue
2055 * @return string
2056 * @private
2057 */
2058 function makesafe( $invalue ) {
2059 // Armor existing references for reversability.
2060 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
2061
2062 $bytesleft = 0;
2063 $result = "";
2064 $working = 0;
2065 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2066 $bytevalue = ord( $invalue{$i} );
2067 if( $bytevalue <= 0x7F ) { //0xxx xxxx
2068 $result .= chr( $bytevalue );
2069 $bytesleft = 0;
2070 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
2071 $working = $working << 6;
2072 $working += ($bytevalue & 0x3F);
2073 $bytesleft--;
2074 if( $bytesleft <= 0 ) {
2075 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
2076 }
2077 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
2078 $working = $bytevalue & 0x1F;
2079 $bytesleft = 1;
2080 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
2081 $working = $bytevalue & 0x0F;
2082 $bytesleft = 2;
2083 } else { //1111 0xxx
2084 $working = $bytevalue & 0x07;
2085 $bytesleft = 3;
2086 }
2087 }
2088 return $result;
2089 }
2090
2091 /**
2092 * Reverse the previously applied transliteration of non-ASCII characters
2093 * back to UTF-8. Used to protect data from corruption by broken web browsers
2094 * as listed in $wgBrowserBlackList.
2095 *
2096 * @param string $invalue
2097 * @return string
2098 * @private
2099 */
2100 function unmakesafe( $invalue ) {
2101 $result = "";
2102 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
2103 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
2104 $i += 3;
2105 $hexstring = "";
2106 do {
2107 $hexstring .= $invalue{$i};
2108 $i++;
2109 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
2110
2111 // Do some sanity checks. These aren't needed for reversability,
2112 // but should help keep the breakage down if the editor
2113 // breaks one of the entities whilst editing.
2114 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
2115 $codepoint = hexdec($hexstring);
2116 $result .= codepointToUtf8( $codepoint );
2117 } else {
2118 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
2119 }
2120 } else {
2121 $result .= substr( $invalue, $i, 1 );
2122 }
2123 }
2124 // reverse the transform that we made for reversability reasons.
2125 return strtr( $result, array( "&#x0" => "&#x" ) );
2126 }
2127
2128 function noCreatePermission() {
2129 global $wgOut;
2130 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
2131 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
2132 }
2133
2134 /**
2135 * If there are rows in the deletion log for this page, show them,
2136 * along with a nice little note for the user
2137 *
2138 * @param OutputPage $out
2139 */
2140 private function showDeletionLog( $out ) {
2141 $title = $this->mTitle;
2142 $reader = new LogReader(
2143 new FauxRequest(
2144 array(
2145 'page' => $title->getPrefixedText(),
2146 'type' => 'delete',
2147 )
2148 )
2149 );
2150 if( $reader->hasRows() ) {
2151 $out->addHtml( '<div id="mw-recreate-deleted-warn">' );
2152 $out->addWikiText( wfMsg( 'recreate-deleted-warn' ) );
2153 $viewer = new LogViewer( $reader );
2154 $viewer->showList( $out );
2155 $out->addHtml( '</div>' );
2156 }
2157 }
2158
2159 /**
2160 * Attempt submission
2161 * @return bool false if output is done, true if the rest of the form should be displayed
2162 */
2163 function attemptSave() {
2164 global $wgUser, $wgOut, $wgTitle, $wgRequest;
2165
2166 $resultDetails = false;
2167 $value = $this->internalAttemptSave( $resultDetails, $wgUser->isAllowed('bot') && $wgRequest->getBool('bot', true) );
2168
2169 if( $value == self::AS_SUCCESS_UPDATE || $value == self::AS_SUCCESS_NEW_ARTICLE ) {
2170 $this->didSave = true;
2171 }
2172
2173 switch ($value)
2174 {
2175 case self::AS_HOOK_ERROR_EXPECTED:
2176 case self::AS_CONTENT_TOO_BIG:
2177 case self::AS_ARTICLE_WAS_DELETED:
2178 case self::AS_CONFLICT_DETECTED:
2179 case self::AS_SUMMARY_NEEDED:
2180 case self::AS_TEXTBOX_EMPTY:
2181 case self::AS_MAX_ARTICLE_SIZE_EXCEDED:
2182 case self::AS_END:
2183 return true;
2184
2185 case self::AS_HOOK_ERROR:
2186 case self::AS_FILTERING:
2187 case self::AS_SUCCESS_NEW_ARTICLE:
2188 case self::AS_SUCCESS_UPDATE:
2189 return false;
2190
2191 case self::AS_SPAM_ERROR:
2192 $this->spamPage ( $resultDetails['spam'] );
2193 return false;
2194
2195 case self::AS_BLOCKED_PAGE_FOR_USER:
2196 $this->blockedPage();
2197 return false;
2198
2199 case self::AS_READ_ONLY_PAGE_ANON:
2200 $this->userNotLoggedInPage();
2201 return false;
2202
2203 case self::AS_READ_ONLY_PAGE_LOGGED:
2204 case self::AS_READ_ONLY_PAGE:
2205 $wgOut->readOnlyPage();
2206 return false;
2207
2208 case self::AS_RATE_LIMITED:
2209 $wgOut->rateLimited();
2210 return false;
2211
2212 case self::AS_NO_CREATE_PERMISSION;
2213 $this->noCreatePermission();
2214 return;
2215
2216 case self::AS_BLANK_ARTICLE:
2217 $wgOut->redirect( $wgTitle->getFullURL() );
2218 return false;
2219 }
2220 }
2221 }