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