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