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