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