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