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