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