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