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