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