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