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