forked from roytam1/UXP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHTMLFormElement.cpp
2580 lines (2229 loc) · 78.7 KB
/
HTMLFormElement.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/dom/HTMLFormElement.h"
#include "jsapi.h"
#include "mozilla/ContentEvents.h"
#include "mozilla/EventDispatcher.h"
#include "mozilla/EventStateManager.h"
#include "mozilla/EventStates.h"
#include "mozilla/dom/AutocompleteErrorEvent.h"
#include "mozilla/dom/nsCSPUtils.h"
#include "mozilla/dom/nsCSPContext.h"
#include "mozilla/dom/HTMLFormControlsCollection.h"
#include "mozilla/dom/HTMLFormElementBinding.h"
#include "mozilla/Move.h"
#include "nsIHTMLDocument.h"
#include "nsGkAtoms.h"
#include "nsStyleConsts.h"
#include "nsPresContext.h"
#include "nsIDocument.h"
#include "nsIFormControlFrame.h"
#include "nsError.h"
#include "nsContentUtils.h"
#include "nsInterfaceHashtable.h"
#include "nsContentList.h"
#include "nsCOMArray.h"
#include "nsAutoPtr.h"
#include "nsTArray.h"
#include "nsIMutableArray.h"
#include "nsIFormAutofillContentService.h"
#include "mozilla/BinarySearch.h"
#include "nsQueryObject.h"
// form submission
#include "HTMLFormSubmissionConstants.h"
#include "mozilla/dom/FormData.h"
#include "nsIFormSubmitObserver.h"
#include "nsIObserverService.h"
#include "nsICategoryManager.h"
#include "nsCategoryManagerUtils.h"
#include "nsISimpleEnumerator.h"
#include "nsRange.h"
#include "nsIScriptError.h"
#include "nsIScriptSecurityManager.h"
#include "nsNetUtil.h"
#include "nsIInterfaceRequestorUtils.h"
#include "nsIWebProgress.h"
#include "nsIDocShell.h"
#include "nsIPrompt.h"
#include "nsIStringBundle.h"
// radio buttons
#include "mozilla/dom/HTMLInputElement.h"
#include "nsIRadioVisitor.h"
#include "RadioNodeList.h"
#include "nsLayoutUtils.h"
#include "mozAutoDocUpdate.h"
#include "nsIHTMLCollection.h"
#include "nsIConstraintValidation.h"
#include "nsIDOMHTMLButtonElement.h"
#include "nsSandboxFlags.h"
#include "nsIContentSecurityPolicy.h"
// images
#include "mozilla/dom/HTMLImageElement.h"
// construction, destruction
NS_IMPL_NS_NEW_HTML_ELEMENT(Form)
namespace mozilla {
namespace dom {
static const uint8_t NS_FORM_AUTOCOMPLETE_ON = 1;
static const uint8_t NS_FORM_AUTOCOMPLETE_OFF = 0;
static const nsAttrValue::EnumTable kFormAutocompleteTable[] = {
{ "on", NS_FORM_AUTOCOMPLETE_ON },
{ "off", NS_FORM_AUTOCOMPLETE_OFF },
{ nullptr, 0 }
};
// Default autocomplete value is 'on'.
static const nsAttrValue::EnumTable* kFormDefaultAutocomplete = &kFormAutocompleteTable[0];
bool HTMLFormElement::gFirstFormSubmitted = false;
bool HTMLFormElement::gPasswordManagerInitialized = false;
HTMLFormElement::HTMLFormElement(already_AddRefed<mozilla::dom::NodeInfo>& aNodeInfo)
: nsGenericHTMLElement(aNodeInfo),
mControls(new HTMLFormControlsCollection(this)),
mSelectedRadioButtons(2),
mRequiredRadioButtonCounts(2),
mValueMissingRadioGroups(2),
mGeneratingSubmit(false),
mGeneratingReset(false),
mIsSubmitting(false),
mDeferSubmission(false),
mNotifiedObservers(false),
mNotifiedObserversResult(false),
mSubmitPopupState(openAbused),
mSubmitInitiatedFromUserInput(false),
mPendingSubmission(nullptr),
mSubmittingRequest(nullptr),
mDefaultSubmitElement(nullptr),
mFirstSubmitInElements(nullptr),
mFirstSubmitNotInElements(nullptr),
mImageNameLookupTable(FORM_CONTROL_LIST_HASHTABLE_LENGTH),
mPastNameLookupTable(FORM_CONTROL_LIST_HASHTABLE_LENGTH),
mInvalidElementsCount(0),
mEverTriedInvalidSubmit(false)
{
// We start out valid.
AddStatesSilently(NS_EVENT_STATE_VALID);
}
HTMLFormElement::~HTMLFormElement()
{
if (mControls) {
mControls->DropFormReference();
}
Clear();
}
// nsISupports
NS_IMPL_CYCLE_COLLECTION_CLASS(HTMLFormElement)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN_INHERITED(HTMLFormElement,
nsGenericHTMLElement)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mControls)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mImageNameLookupTable)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mPastNameLookupTable)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mSelectedRadioButtons)
NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN_INHERITED(HTMLFormElement,
nsGenericHTMLElement)
tmp->Clear();
tmp->mExpandoAndGeneration.OwnerUnlinked();
NS_IMPL_CYCLE_COLLECTION_UNLINK_END
NS_IMPL_ADDREF_INHERITED(HTMLFormElement, Element)
NS_IMPL_RELEASE_INHERITED(HTMLFormElement, Element)
// QueryInterface implementation for HTMLFormElement
NS_INTERFACE_TABLE_HEAD_CYCLE_COLLECTION_INHERITED(HTMLFormElement)
NS_INTERFACE_TABLE_INHERITED(HTMLFormElement,
nsIDOMHTMLFormElement,
nsIForm,
nsIWebProgressListener,
nsIRadioGroupContainer)
NS_INTERFACE_TABLE_TAIL_INHERITING(nsGenericHTMLElement)
// EventTarget
void
HTMLFormElement::AsyncEventRunning(AsyncEventDispatcher* aEvent)
{
if (mFormPasswordEventDispatcher == aEvent) {
mFormPasswordEventDispatcher = nullptr;
}
}
// nsIDOMHTMLFormElement
NS_IMPL_ELEMENT_CLONE(HTMLFormElement)
nsIHTMLCollection*
HTMLFormElement::Elements()
{
return mControls;
}
NS_IMETHODIMP
HTMLFormElement::GetElements(nsIDOMHTMLCollection** aElements)
{
*aElements = Elements();
NS_ADDREF(*aElements);
return NS_OK;
}
nsresult
HTMLFormElement::BeforeSetAttr(int32_t aNamespaceID, nsIAtom* aName,
const nsAttrValueOrString* aValue, bool aNotify)
{
if (aNamespaceID == kNameSpaceID_None) {
if (aName == nsGkAtoms::action || aName == nsGkAtoms::target) {
// This check is mostly to preserve previous behavior.
if (aValue) {
if (mPendingSubmission) {
// aha, there is a pending submission that means we're in
// the script and we need to flush it. let's tell it
// that the event was ignored to force the flush.
// the second argument is not playing a role at all.
FlushPendingSubmission();
}
// Don't forget we've notified the password manager already if the
// page sets the action/target in the during submit. (bug 343182)
bool notifiedObservers = mNotifiedObservers;
ForgetCurrentSubmission();
mNotifiedObservers = notifiedObservers;
}
}
}
return nsGenericHTMLElement::BeforeSetAttr(aNamespaceID, aName, aValue,
aNotify);
}
nsresult
HTMLFormElement::AfterSetAttr(int32_t aNameSpaceID, nsIAtom* aName,
const nsAttrValue* aValue,
const nsAttrValue* aOldValue, bool aNotify)
{
if (aName == nsGkAtoms::novalidate && aNameSpaceID == kNameSpaceID_None) {
// Update all form elements states because they might be [no longer]
// affected by :-moz-ui-valid or :-moz-ui-invalid.
for (uint32_t i = 0, length = mControls->mElements.Length();
i < length; ++i) {
mControls->mElements[i]->UpdateState(true);
}
for (uint32_t i = 0, length = mControls->mNotInElements.Length();
i < length; ++i) {
mControls->mNotInElements[i]->UpdateState(true);
}
}
return nsGenericHTMLElement::AfterSetAttr(aNameSpaceID, aName, aValue,
aOldValue, aNotify);
}
NS_IMPL_STRING_ATTR(HTMLFormElement, AcceptCharset, acceptcharset)
NS_IMPL_ACTION_ATTR(HTMLFormElement, Action, action)
NS_IMPL_ENUM_ATTR_DEFAULT_VALUE(HTMLFormElement, Autocomplete, autocomplete,
kFormDefaultAutocomplete->tag)
NS_IMPL_ENUM_ATTR_DEFAULT_VALUE(HTMLFormElement, Enctype, enctype,
kFormDefaultEnctype->tag)
NS_IMPL_ENUM_ATTR_DEFAULT_VALUE(HTMLFormElement, Method, method,
kFormDefaultMethod->tag)
NS_IMPL_BOOL_ATTR(HTMLFormElement, NoValidate, novalidate)
NS_IMPL_STRING_ATTR(HTMLFormElement, Name, name)
NS_IMPL_STRING_ATTR(HTMLFormElement, Target, target)
void
HTMLFormElement::Submit(ErrorResult& aRv)
{
// Send the submit event
if (mPendingSubmission) {
// aha, we have a pending submission that was not flushed
// (this happens when form.submit() is called twice)
// we have to delete it and build a new one since values
// might have changed inbetween (we emulate IE here, that's all)
mPendingSubmission = nullptr;
}
aRv = DoSubmitOrReset(nullptr, eFormSubmit);
}
NS_IMETHODIMP
HTMLFormElement::Submit()
{
ErrorResult rv;
Submit(rv);
return rv.StealNSResult();
}
NS_IMETHODIMP
HTMLFormElement::Reset()
{
InternalFormEvent event(true, eFormReset);
EventDispatcher::Dispatch(static_cast<nsIContent*>(this), nullptr, &event);
return NS_OK;
}
NS_IMETHODIMP
HTMLFormElement::CheckValidity(bool* retVal)
{
*retVal = CheckValidity();
return NS_OK;
}
void
HTMLFormElement::RequestAutocomplete()
{
bool dummy;
nsCOMPtr<nsIDOMWindow> window =
do_QueryInterface(OwnerDoc()->GetScriptHandlingObject(dummy));
nsCOMPtr<nsIFormAutofillContentService> formAutofillContentService =
do_GetService("@mozilla.org/formautofill/content-service;1");
if (!formAutofillContentService || !window) {
AutocompleteErrorEventInit init;
init.mBubbles = true;
init.mCancelable = false;
init.mReason = AutoCompleteErrorReason::Disabled;
RefPtr<AutocompleteErrorEvent> event =
AutocompleteErrorEvent::Constructor(this, NS_LITERAL_STRING("autocompleteerror"), init);
(new AsyncEventDispatcher(this, event))->PostDOMEvent();
return;
}
formAutofillContentService->RequestAutocomplete(this, window);
}
bool
HTMLFormElement::ParseAttribute(int32_t aNamespaceID,
nsIAtom* aAttribute,
const nsAString& aValue,
nsAttrValue& aResult)
{
if (aNamespaceID == kNameSpaceID_None) {
if (aAttribute == nsGkAtoms::method) {
return aResult.ParseEnumValue(aValue, kFormMethodTable, false);
}
if (aAttribute == nsGkAtoms::enctype) {
return aResult.ParseEnumValue(aValue, kFormEnctypeTable, false);
}
if (aAttribute == nsGkAtoms::autocomplete) {
return aResult.ParseEnumValue(aValue, kFormAutocompleteTable, false);
}
}
return nsGenericHTMLElement::ParseAttribute(aNamespaceID, aAttribute, aValue,
aResult);
}
nsresult
HTMLFormElement::BindToTree(nsIDocument* aDocument, nsIContent* aParent,
nsIContent* aBindingParent,
bool aCompileEventHandlers)
{
nsresult rv = nsGenericHTMLElement::BindToTree(aDocument, aParent,
aBindingParent,
aCompileEventHandlers);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIHTMLDocument> htmlDoc(do_QueryInterface(aDocument));
if (htmlDoc) {
htmlDoc->AddedForm();
}
return rv;
}
template<typename T>
static void
MarkOrphans(const nsTArray<T*>& aArray)
{
uint32_t length = aArray.Length();
for (uint32_t i = 0; i < length; ++i) {
aArray[i]->SetFlags(MAYBE_ORPHAN_FORM_ELEMENT);
}
}
static void
CollectOrphans(nsINode* aRemovalRoot,
const nsTArray<nsGenericHTMLFormElement*>& aArray
#ifdef DEBUG
, nsIDOMHTMLFormElement* aThisForm
#endif
)
{
// Put a script blocker around all the notifications we're about to do.
nsAutoScriptBlocker scriptBlocker;
// Walk backwards so that if we remove elements we can just keep iterating
uint32_t length = aArray.Length();
for (uint32_t i = length; i > 0; --i) {
nsGenericHTMLFormElement* node = aArray[i-1];
// Now if MAYBE_ORPHAN_FORM_ELEMENT is not set, that would mean that the
// node is in fact a descendant of the form and hence should stay in the
// form. If it _is_ set, then we need to check whether the node is a
// descendant of aRemovalRoot. If it is, we leave it in the form.
#ifdef DEBUG
bool removed = false;
#endif
if (node->HasFlag(MAYBE_ORPHAN_FORM_ELEMENT)) {
node->UnsetFlags(MAYBE_ORPHAN_FORM_ELEMENT);
if (!nsContentUtils::ContentIsDescendantOf(node, aRemovalRoot)) {
node->ClearForm(true);
// When a form control loses its form owner, its state can change.
node->UpdateState(true);
#ifdef DEBUG
removed = true;
#endif
}
}
#ifdef DEBUG
if (!removed) {
nsCOMPtr<nsIDOMHTMLFormElement> form;
node->GetForm(getter_AddRefs(form));
NS_ASSERTION(form == aThisForm, "How did that happen?");
}
#endif /* DEBUG */
}
}
static void
CollectOrphans(nsINode* aRemovalRoot,
const nsTArray<HTMLImageElement*>& aArray
#ifdef DEBUG
, nsIDOMHTMLFormElement* aThisForm
#endif
)
{
// Walk backwards so that if we remove elements we can just keep iterating
uint32_t length = aArray.Length();
for (uint32_t i = length; i > 0; --i) {
HTMLImageElement* node = aArray[i-1];
// Now if MAYBE_ORPHAN_FORM_ELEMENT is not set, that would mean that the
// node is in fact a descendant of the form and hence should stay in the
// form. If it _is_ set, then we need to check whether the node is a
// descendant of aRemovalRoot. If it is, we leave it in the form.
#ifdef DEBUG
bool removed = false;
#endif
if (node->HasFlag(MAYBE_ORPHAN_FORM_ELEMENT)) {
node->UnsetFlags(MAYBE_ORPHAN_FORM_ELEMENT);
if (!nsContentUtils::ContentIsDescendantOf(node, aRemovalRoot)) {
node->ClearForm(true);
#ifdef DEBUG
removed = true;
#endif
}
}
#ifdef DEBUG
if (!removed) {
nsCOMPtr<nsIDOMHTMLFormElement> form = node->GetForm();
NS_ASSERTION(form == aThisForm, "How did that happen?");
}
#endif /* DEBUG */
}
}
void
HTMLFormElement::UnbindFromTree(bool aDeep, bool aNullParent)
{
nsCOMPtr<nsIHTMLDocument> oldDocument = do_QueryInterface(GetUncomposedDoc());
// Mark all of our controls as maybe being orphans
MarkOrphans(mControls->mElements);
MarkOrphans(mControls->mNotInElements);
MarkOrphans(mImageElements);
nsGenericHTMLElement::UnbindFromTree(aDeep, aNullParent);
nsINode* ancestor = this;
nsINode* cur;
do {
cur = ancestor->GetParentNode();
if (!cur) {
break;
}
ancestor = cur;
} while (1);
CollectOrphans(ancestor, mControls->mElements
#ifdef DEBUG
, this
#endif
);
CollectOrphans(ancestor, mControls->mNotInElements
#ifdef DEBUG
, this
#endif
);
CollectOrphans(ancestor, mImageElements
#ifdef DEBUG
, this
#endif
);
if (oldDocument) {
oldDocument->RemovedForm();
}
ForgetCurrentSubmission();
}
nsresult
HTMLFormElement::GetEventTargetParent(EventChainPreVisitor& aVisitor)
{
aVisitor.mWantsWillHandleEvent = true;
if (aVisitor.mEvent->mOriginalTarget == static_cast<nsIContent*>(this)) {
uint32_t msg = aVisitor.mEvent->mMessage;
if (msg == eFormSubmit) {
if (mGeneratingSubmit) {
aVisitor.mCanHandle = false;
return NS_OK;
}
mGeneratingSubmit = true;
// let the form know that it needs to defer the submission,
// that means that if there are scripted submissions, the
// latest one will be deferred until after the exit point of the handler.
mDeferSubmission = true;
} else if (msg == eFormReset) {
if (mGeneratingReset) {
aVisitor.mCanHandle = false;
return NS_OK;
}
mGeneratingReset = true;
}
}
return nsGenericHTMLElement::GetEventTargetParent(aVisitor);
}
nsresult
HTMLFormElement::WillHandleEvent(EventChainPostVisitor& aVisitor)
{
// If this is the bubble stage and there is a nested form below us which
// received a submit event we do *not* want to handle the submit event
// for this form too.
if ((aVisitor.mEvent->mMessage == eFormSubmit ||
aVisitor.mEvent->mMessage == eFormReset) &&
aVisitor.mEvent->mFlags.mInBubblingPhase &&
aVisitor.mEvent->mOriginalTarget != static_cast<nsIContent*>(this)) {
aVisitor.mEvent->StopPropagation();
}
return NS_OK;
}
nsresult
HTMLFormElement::PostHandleEvent(EventChainPostVisitor& aVisitor)
{
if (aVisitor.mEvent->mOriginalTarget == static_cast<nsIContent*>(this)) {
EventMessage msg = aVisitor.mEvent->mMessage;
if (msg == eFormSubmit) {
// let the form know not to defer subsequent submissions
mDeferSubmission = false;
}
if (aVisitor.mEventStatus == nsEventStatus_eIgnore) {
switch (msg) {
case eFormReset:
case eFormSubmit: {
if (mPendingSubmission && msg == eFormSubmit) {
// tell the form to forget a possible pending submission.
// the reason is that the script returned true (the event was
// ignored) so if there is a stored submission, it will miss
// the name/value of the submitting element, thus we need
// to forget it and the form element will build a new one
mPendingSubmission = nullptr;
}
DoSubmitOrReset(aVisitor.mEvent, msg);
break;
}
default:
break;
}
} else {
if (msg == eFormSubmit) {
// tell the form to flush a possible pending submission.
// the reason is that the script returned false (the event was
// not ignored) so if there is a stored submission, it needs to
// be submitted immediatelly.
FlushPendingSubmission();
}
}
if (msg == eFormSubmit) {
mGeneratingSubmit = false;
} else if (msg == eFormReset) {
mGeneratingReset = false;
}
}
return NS_OK;
}
nsresult
HTMLFormElement::DoSubmitOrReset(WidgetEvent* aEvent,
EventMessage aMessage)
{
// Make sure the presentation is up-to-date
nsIDocument* doc = GetComposedDoc();
if (doc) {
doc->FlushPendingNotifications(Flush_ContentAndNotify);
}
// JBK Don't get form frames anymore - bug 34297
// Submit or Reset the form
if (eFormReset == aMessage) {
return DoReset();
}
if (eFormSubmit == aMessage) {
// Don't submit if we're not in a document or if we're in
// a sandboxed frame and form submit is disabled.
if (!doc || (doc->GetSandboxFlags() & SANDBOXED_FORMS)) {
return NS_OK;
}
return DoSubmit(aEvent);
}
MOZ_ASSERT(false);
return NS_OK;
}
nsresult
HTMLFormElement::DoReset()
{
// JBK walk the elements[] array instead of form frame controls - bug 34297
uint32_t numElements = GetElementCount();
for (uint32_t elementX = 0; elementX < numElements; ++elementX) {
// Hold strong ref in case the reset does something weird
nsCOMPtr<nsIFormControl> controlNode = GetElementAt(elementX);
if (controlNode) {
controlNode->Reset();
}
}
return NS_OK;
}
#define NS_ENSURE_SUBMIT_SUCCESS(rv) \
if (NS_FAILED(rv)) { \
ForgetCurrentSubmission(); \
return rv; \
}
nsresult
HTMLFormElement::DoSubmit(WidgetEvent* aEvent)
{
NS_ASSERTION(GetComposedDoc(), "Should never get here without a current doc");
if (mIsSubmitting) {
NS_WARNING("Preventing double form submission");
// XXX Should this return an error?
return NS_OK;
}
// Mark us as submitting so that we don't try to submit again
mIsSubmitting = true;
NS_ASSERTION(!mWebProgress && !mSubmittingRequest, "Web progress / submitting request should not exist here!");
nsAutoPtr<HTMLFormSubmission> submission;
//
// prepare the submission object
//
nsresult rv = BuildSubmission(getter_Transfers(submission), aEvent);
if (NS_FAILED(rv)) {
mIsSubmitting = false;
return rv;
}
// XXXbz if the script global is that for an sXBL/XBL2 doc, it won't
// be a window...
nsPIDOMWindowOuter *window = OwnerDoc()->GetWindow();
if (window) {
mSubmitPopupState = window->GetPopupControlState();
} else {
mSubmitPopupState = openAbused;
}
mSubmitInitiatedFromUserInput = EventStateManager::IsHandlingUserInput();
if(mDeferSubmission) {
// we are in an event handler, JS submitted so we have to
// defer this submission. let's remember it and return
// without submitting
mPendingSubmission = submission;
// ensure reentrancy
mIsSubmitting = false;
return NS_OK;
}
//
// perform the submission
//
return SubmitSubmission(submission);
}
nsresult
HTMLFormElement::BuildSubmission(HTMLFormSubmission** aFormSubmission,
WidgetEvent* aEvent)
{
NS_ASSERTION(!mPendingSubmission, "tried to build two submissions!");
// Get the originating frame (failure is non-fatal)
nsGenericHTMLElement* originatingElement = nullptr;
if (aEvent) {
InternalFormEvent* formEvent = aEvent->AsFormEvent();
if (formEvent) {
nsIContent* originator = formEvent->mOriginator;
if (originator) {
if (!originator->IsHTMLElement()) {
return NS_ERROR_UNEXPECTED;
}
originatingElement = static_cast<nsGenericHTMLElement*>(originator);
}
}
}
nsresult rv;
//
// Get the submission object
//
rv = HTMLFormSubmission::GetFromForm(this, originatingElement,
aFormSubmission);
NS_ENSURE_SUBMIT_SUCCESS(rv);
//
// Dump the data into the submission object
//
rv = WalkFormElements(*aFormSubmission);
NS_ENSURE_SUBMIT_SUCCESS(rv);
return NS_OK;
}
nsresult
HTMLFormElement::SubmitSubmission(HTMLFormSubmission* aFormSubmission)
{
nsresult rv;
nsIContent* originatingElement = aFormSubmission->GetOriginatingElement();
//
// Get the action and target
//
nsCOMPtr<nsIURI> actionURI;
rv = GetActionURL(getter_AddRefs(actionURI), originatingElement);
NS_ENSURE_SUBMIT_SUCCESS(rv);
if (!actionURI) {
mIsSubmitting = false;
return NS_OK;
}
// If there is no link handler, then we won't actually be able to submit.
nsIDocument* doc = GetComposedDoc();
nsCOMPtr<nsISupports> container = doc ? doc->GetContainer() : nullptr;
nsCOMPtr<nsILinkHandler> linkHandler(do_QueryInterface(container));
if (!linkHandler || IsEditable()) {
mIsSubmitting = false;
return NS_OK;
}
// javascript URIs are not really submissions; they just call a function.
// Also, they may synchronously call submit(), and we want them to be able to
// do so while still disallowing other double submissions. (Bug 139798)
// Note that any other URI types that are of equivalent type should also be
// added here.
// XXXbz this is a mess. The real issue here is that nsJSChannel sets the
// LOAD_BACKGROUND flag, so doesn't notify us, compounded by the fact that
// the JS executes before we forget the submission in OnStateChange on
// STATE_STOP. As a result, we have to make sure that we simply pretend
// we're not submitting when submitting to a JS URL. That's kinda bogus, but
// there we are.
bool schemeIsJavaScript = false;
if (NS_SUCCEEDED(actionURI->SchemeIs("javascript", &schemeIsJavaScript)) &&
schemeIsJavaScript) {
mIsSubmitting = false;
}
// The target is the originating element formtarget attribute if the element
// is a submit control and has such an attribute.
// Otherwise, the target is the form owner's target attribute,
// if it has such an attribute.
// Finally, if one of the child nodes of the head element is a base element
// with a target attribute, then the value of the target attribute of the
// first such base element; or, if there is no such element, the empty string.
nsAutoString target;
if (!(originatingElement && originatingElement->GetAttr(kNameSpaceID_None,
nsGkAtoms::formtarget,
target)) &&
!GetAttr(kNameSpaceID_None, nsGkAtoms::target, target)) {
GetBaseTarget(target);
}
//
// Notify observers of submit
//
bool cancelSubmit = false;
if (mNotifiedObservers) {
cancelSubmit = mNotifiedObserversResult;
} else {
rv = NotifySubmitObservers(actionURI, &cancelSubmit, true);
NS_ENSURE_SUBMIT_SUCCESS(rv);
}
if (cancelSubmit) {
mIsSubmitting = false;
return NS_OK;
}
cancelSubmit = false;
rv = NotifySubmitObservers(actionURI, &cancelSubmit, false);
NS_ENSURE_SUBMIT_SUCCESS(rv);
if (cancelSubmit) {
mIsSubmitting = false;
return NS_OK;
}
//
// Submit
//
nsCOMPtr<nsIDocShell> docShell;
{
nsAutoPopupStatePusher popupStatePusher(mSubmitPopupState);
AutoHandlingUserInputStatePusher userInpStatePusher(
mSubmitInitiatedFromUserInput,
nullptr, doc);
nsCOMPtr<nsIInputStream> postDataStream;
rv = aFormSubmission->GetEncodedSubmission(actionURI,
getter_AddRefs(postDataStream));
NS_ENSURE_SUBMIT_SUCCESS(rv);
rv = linkHandler->OnLinkClickSync(this, actionURI,
target.get(),
NullString(),
postDataStream, nullptr,
getter_AddRefs(docShell),
getter_AddRefs(mSubmittingRequest));
NS_ENSURE_SUBMIT_SUCCESS(rv);
}
// Even if the submit succeeds, it's possible for there to be no docshell
// or request; for example, if it's to a named anchor within the same page
// the submit will not really do anything.
if (docShell) {
// If the channel is pending, we have to listen for web progress.
bool pending = false;
mSubmittingRequest->IsPending(&pending);
if (pending && !schemeIsJavaScript) {
nsCOMPtr<nsIWebProgress> webProgress = do_GetInterface(docShell);
NS_ASSERTION(webProgress, "nsIDocShell not converted to nsIWebProgress!");
rv = webProgress->AddProgressListener(this, nsIWebProgress::NOTIFY_STATE_ALL);
NS_ENSURE_SUBMIT_SUCCESS(rv);
mWebProgress = do_GetWeakReference(webProgress);
NS_ASSERTION(mWebProgress, "can't hold weak ref to webprogress!");
} else {
ForgetCurrentSubmission();
}
} else {
ForgetCurrentSubmission();
}
return rv;
}
nsresult
HTMLFormElement::DoSecureToInsecureSubmitCheck(nsIURI* aActionURL,
bool* aCancelSubmit)
{
*aCancelSubmit = false;
// Only ask the user about posting from a secure URI to an insecure URI if
// this element is in the root document. When this is not the case, the mixed
// content blocker will take care of security for us.
nsIDocument* parent = OwnerDoc()->GetParentDocument();
bool isRootDocument = (!parent || nsContentUtils::IsChromeDoc(parent));
if (!isRootDocument) {
return NS_OK;
}
nsIPrincipal* principal = NodePrincipal();
if (!principal) {
*aCancelSubmit = true;
return NS_OK;
}
nsCOMPtr<nsIURI> principalURI;
nsresult rv = principal->GetURI(getter_AddRefs(principalURI));
if (NS_FAILED(rv)) {
return rv;
}
if (!principalURI) {
principalURI = OwnerDoc()->GetDocumentURI();
}
bool formIsHTTPS;
rv = principalURI->SchemeIs("https", &formIsHTTPS);
if (NS_FAILED(rv)) {
return rv;
}
bool actionIsHTTPS;
rv = aActionURL->SchemeIs("https", &actionIsHTTPS);
if (NS_FAILED(rv)) {
return rv;
}
bool actionIsJS;
rv = aActionURL->SchemeIs("javascript", &actionIsJS);
if (NS_FAILED(rv)) {
return rv;
}
if (!formIsHTTPS || actionIsHTTPS || actionIsJS) {
return NS_OK;
}
nsCOMPtr<nsPIDOMWindowOuter> window = OwnerDoc()->GetWindow();
if (!window) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIDocShell> docShell = window->GetDocShell();
if (!docShell) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIPrompt> prompt = do_GetInterface(docShell);
if (!prompt) {
return NS_ERROR_FAILURE;
}
nsCOMPtr<nsIStringBundle> stringBundle;
nsCOMPtr<nsIStringBundleService> stringBundleService =
mozilla::services::GetStringBundleService();
if (!stringBundleService) {
return NS_ERROR_FAILURE;
}
rv = stringBundleService->CreateBundle(
"chrome://global/locale/browser.properties",
getter_AddRefs(stringBundle));
if (NS_FAILED(rv)) {
return rv;
}
nsAutoString title;
nsAutoString message;
nsAutoString cont;
stringBundle->GetStringFromName(
u"formPostSecureToInsecureWarning.title", getter_Copies(title));
stringBundle->GetStringFromName(
u"formPostSecureToInsecureWarning.message",
getter_Copies(message));
stringBundle->GetStringFromName(
u"formPostSecureToInsecureWarning.continue",
getter_Copies(cont));
int32_t buttonPressed;
bool checkState = false; // this is unused (ConfirmEx requires this parameter)
rv = prompt->ConfirmEx(title.get(), message.get(),
(nsIPrompt::BUTTON_TITLE_IS_STRING *
nsIPrompt::BUTTON_POS_0) +
(nsIPrompt::BUTTON_TITLE_CANCEL *
nsIPrompt::BUTTON_POS_1),
cont.get(), nullptr, nullptr, nullptr,
&checkState, &buttonPressed);
if (NS_FAILED(rv)) {
return rv;
}
*aCancelSubmit = (buttonPressed == 1);
return NS_OK;
}
nsresult
HTMLFormElement::NotifySubmitObservers(nsIURI* aActionURL,
bool* aCancelSubmit,
bool aEarlyNotify)
{
// If this is the first form, bring alive the first form submit
// category observers
if (!gFirstFormSubmitted) {
gFirstFormSubmitted = true;
NS_CreateServicesFromCategory(NS_FIRST_FORMSUBMIT_CATEGORY,
nullptr,
NS_FIRST_FORMSUBMIT_CATEGORY);
}
if (!aEarlyNotify) {
nsresult rv = DoSecureToInsecureSubmitCheck(aActionURL, aCancelSubmit);
if (NS_FAILED(rv)) {
return rv;
}
if (*aCancelSubmit) {
return NS_OK;
}
}
// Notify observers that the form is being submitted.
nsCOMPtr<nsIObserverService> service =
mozilla::services::GetObserverService();
if (!service)
return NS_ERROR_FAILURE;
nsCOMPtr<nsISimpleEnumerator> theEnum;
nsresult rv = service->EnumerateObservers(aEarlyNotify ?
NS_EARLYFORMSUBMIT_SUBJECT :
NS_FORMSUBMIT_SUBJECT,
getter_AddRefs(theEnum));
NS_ENSURE_SUCCESS(rv, rv);