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