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