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