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