html_formimpl.cpp 96.8 KB
Newer Older
George Staikos's avatar
George Staikos committed
1
2
3
4
5
6
/*
 * This file is part of the DOM implementation for KDE.
 *
 * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
 *           (C) 1999 Antti Koivisto (koivisto@kde.org)
 *           (C) 2001 Dirk Mueller (mueller@kde.org)
7
 *           (C) 2004, 2005, 2006 Apple Computer, Inc.
George Staikos's avatar
George Staikos committed
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
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 */

#undef FORMS_DEBUG
//#define FORMS_DEBUG

#include "html/html_formimpl.h"

#include "khtmlview.h"
#include "khtml_part.h"
#include "html/html_documentimpl.h"
#include "khtml_settings.h"

#include "css/cssstyleselector.h"
#include "css/cssproperties.h"
#include "css/cssvalues.h"
#include "css/csshelper.h"
#include "xml/dom_textimpl.h"
#include "xml/dom_docimpl.h"
#include "xml/dom2_eventsimpl.h"
43
#include "xml/dom_restyler.h"
George Staikos's avatar
George Staikos committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include "khtml_ext.h"

#include "rendering/render_form.h"

#include <kcharsets.h>
#include <kglobal.h>
#include <kdebug.h>
#include <kmimetype.h>
#include <kmessagebox.h>
#include <krandom.h>
#include <klocale.h>
#ifndef KHTML_NO_WALLET
#include <kwallet.h>
#endif
#include <netaccess.h>
#include <kfileitem.h>
Dirk Mueller's avatar
Dirk Mueller committed
60
61
62
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QTextCodec>
George Staikos's avatar
George Staikos committed
63
64

// for keygen
Dirk Mueller's avatar
Dirk Mueller committed
65
#include <QtCore/QCharRef>
George Staikos's avatar
George Staikos committed
66
67
68
69
#include <ksslkeygen.h>

#include <assert.h>

Maks Orlovich's avatar
Maks Orlovich committed
70

George Staikos's avatar
George Staikos committed
71
72
using namespace DOM;
using namespace khtml;
73
using namespace WTF;
George Staikos's avatar
George Staikos committed
74

Germain Garand's avatar
Germain Garand committed
75
HTMLFormElementImpl::HTMLFormElementImpl(DocumentImpl *doc, bool implicit)
George Staikos's avatar
George Staikos committed
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
    : HTMLElementImpl(doc)
{
    m_implicit = implicit;
    m_post = false;
    m_multipart = false;
    m_autocomplete = true;
    m_insubmit = false;
    m_doingsubmit = false;
    m_inreset = false;
    m_enctype = "application/x-www-form-urlencoded";
    m_boundary = "----------" + KRandom::randomString( 42 + 13 );
    m_acceptcharset = "UNKNOWN";
    m_malformed = false;
}

HTMLFormElementImpl::~HTMLFormElementImpl()
{
93
94
    if (document() && document()->view() && document()->view()->part()) {
        document()->view()->part()->dequeueWallet(this);
George Staikos's avatar
George Staikos committed
95
    }
Germain Garand's avatar
Germain Garand committed
96
97
98
99
100
101
    QListIterator<HTMLGenericFormElementImpl*> it(formElements);
    while (it.hasNext())
        it.next()->m_form = 0;
    QListIterator<HTMLImageElementImpl*> it2(imgElements);
    while (it2.hasNext())
        it2.next()->m_form = 0;
George Staikos's avatar
George Staikos committed
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
}

NodeImpl::Id HTMLFormElementImpl::id() const
{
    return ID_FORM;
}

HTMLCollectionImpl* HTMLFormElementImpl::elements()
{
    return new HTMLFormCollectionImpl(this);
}

DOMString HTMLFormElementImpl::target() const
{
  return getAttribute(ATTR_TARGET);
}

DOMString HTMLFormElementImpl::action() const
{
  return getAttribute(ATTR_ACTION);
}


long HTMLFormElementImpl::length() const
{
    int len = 0;
Germain Garand's avatar
Germain Garand committed
128
129
    QListIterator<HTMLGenericFormElementImpl*> it(formElements);
    while (it.hasNext())
130
	if (it.next()->isEnumerable())
George Staikos's avatar
George Staikos committed
131
132
133
134
135
136
137
138
139
	    ++len;

    return len;
}

static QByteArray encodeCString(const QByteArray& e)
{
    // http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
    // safe characters like NS handles them for compatibility
140
    static const char safe[] = "-._*";
George Staikos's avatar
George Staikos committed
141
    QByteArray encoded(( e.length()+e.count( '\n' ) )*3
142
                     +e.count('\r') * 3 + 1, 0);
George Staikos's avatar
George Staikos committed
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
    int enclen = 0;
    bool crmissing = false;
    unsigned char oldc;
    unsigned char c ='\0';

    //QCString orig(e.data(), e.size());

    unsigned len = e.length();
    for(unsigned pos = 0; pos < len; pos++) {
        oldc = c;
        c = e[pos];

        if (crmissing && c != '\n') {
            encoded[enclen++] = '%';
            encoded[enclen++] = '0';
            encoded[enclen++] = 'D';
            crmissing = false;
        }

        if ( (( c >= 'A') && ( c <= 'Z')) ||
             (( c >= 'a') && ( c <= 'z')) ||
             (( c >= '0') && ( c <= '9')) ||
             (strchr(safe, c))
            )
            encoded[enclen++] = c;
        else if ( c == ' ' )
            encoded[enclen++] = '+';
        else if ( c == '\n' )
        {
            encoded[enclen++] = '%';
            encoded[enclen++] = '0';
            encoded[enclen++] = 'D';
            encoded[enclen++] = '%';
            encoded[enclen++] = '0';
            encoded[enclen++] = 'A';
            crmissing = false;
        }
        else if (c == '\r' && oldc != '\n') {
            crmissing = true;
        }
        else if ( c != '\r' )
        {
            encoded[enclen++] = '%';
            unsigned int h = c / 16;
            h += (h > 9) ? ('A' - 10) : '0';
            encoded[enclen++] = h;

            unsigned int l = c % 16;
            l += (l > 9) ? ('A' - 10) : '0';
            encoded[enclen++] = l;
        }
    }
    encoded.truncate(enclen);
    return encoded;
}

Maks Orlovich's avatar
Maks Orlovich committed
199
200
201
202
203
204
205
inline static QString ampersandEscape(unsigned val)
{
    QString out;
    out.sprintf("&#%u;", val);
    return out;
}

George Staikos's avatar
George Staikos committed
206
inline static QString escapeUnencodeable(const QTextCodec* codec, const QString& s) {
Maks Orlovich's avatar
Maks Orlovich committed
207
    QString encString;
George Staikos's avatar
George Staikos committed
208
    const int len = s.length();
Maks Orlovich's avatar
Maks Orlovich committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229

    for (int i = 0; i < len; ++i) {
        QChar c = s[i];

        // We need to hand surrogate pairs to the codec at once;
        // also do validity checking on those
        if (c.isLowSurrogate()) {
            c = QChar::ReplacementCharacter;
        } else if (c.isHighSurrogate()) {
            if ((i + 1) < len && s[i + 1].isLowSurrogate()) {
                // A valid SP..
                ++i;
                QString pair = QString(c) + s[i];
                if (codec->canEncode(pair))
                    encString += pair;
                else
                    encString += ampersandEscape(QChar::surrogateToUcs4(c, s[i]));
                continue;
            } else {
                c  = QChar::ReplacementCharacter;
            }
George Staikos's avatar
George Staikos committed
230
        }
Maks Orlovich's avatar
Maks Orlovich committed
231
232
233
234
235
236

        // Normal characters.
        if (codec->canEncode(c))
            encString.append(c);
        else
            encString.append(ampersandEscape(c.unicode()));
George Staikos's avatar
George Staikos committed
237
    }
Maks Orlovich's avatar
Maks Orlovich committed
238
    return encString;
George Staikos's avatar
George Staikos committed
239
240
241
242
243
244
245
246
247
}

inline static QByteArray fixUpfromUnicode(const QTextCodec* codec, const QString& s)
{
    QByteArray str = codec->fromUnicode(escapeUnencodeable(codec,s));
    str.truncate(str.length());
    return str;
}

248
249
250
251
252
253
254
255
256
257
258
259
260
Vector<HTMLGenericFormElementImpl*> HTMLFormElementImpl::gatherInTreeOrder(NodeImpl* root,
                                                               const HashSet<NodeImpl*>& toGather)
{
    Vector<HTMLGenericFormElementImpl*> out;
    out.reserveCapacity(toGather.size());
    
    for (NodeImpl* cur = root; cur; cur = cur->traverseNextNode(root)) {
        if (toGather.contains(cur))
            out.append(static_cast<HTMLGenericFormElementImpl*>(cur));
    }
    return out;
}

George Staikos's avatar
George Staikos committed
261
262
263
QByteArray HTMLFormElementImpl::formData(bool& ok)
{
#ifdef FORMS_DEBUG
Laurent Montel's avatar
Laurent Montel committed
264
    kDebug( 6030 ) << "form: formData()";
George Staikos's avatar
George Staikos committed
265
266
#endif

267
268
269
    QByteArray form_data;
    form_data.resize(0);

George Staikos's avatar
George Staikos committed
270
271
    QByteArray enc_string = ""; // used for non-multipart data

272
273
    bool useMultipart = m_multipart && m_post; // as multipart is ignored for GET

George Staikos's avatar
George Staikos committed
274
275
276
277
    // find out the QTextcodec to use
    QString str = m_acceptcharset.string();
    const QChar space(' ');
    const unsigned int strLength = str.length();
278
    for(unsigned int i=0; i < strLength; ++i) if(str[i].toLatin1() == ',') str[i] = space;
279
    const QStringList charsets = str.split(' ');
George Staikos's avatar
George Staikos committed
280
    QTextCodec* codec = 0;
281
    KHTMLView *view = document()->view();
George Staikos's avatar
George Staikos committed
282
283
284
285
286
287
288
289
290
291
292
293
294
295
    {
        QStringList::ConstIterator it = charsets.begin();
        const QStringList::ConstIterator itEnd = charsets.end();

        for ( ; it != itEnd; ++it )
        {
            QString enc = (*it);
            if(enc.contains("UNKNOWN"))
            {
                // use standard document encoding
                enc = "ISO 8859-1";
                if(view && view->part())
                    enc = view->part()->encoding();
            }
Heng Liu's avatar
Heng Liu committed
296
            if((codec = KGlobal::charsets()->codecForName(enc.toLatin1().constData())))
George Staikos's avatar
George Staikos committed
297
298
299
300
301
302
303
304
305
306
307
308
309
310
                break;
        }
    }
    if(!codec)
        codec = QTextCodec::codecForLocale();

    // we need to map visual hebrew to logical hebrew, as the web
    // server alsways expects responses in logical ordering
    if ( codec->mibEnum() == 11 )
	codec = QTextCodec::codecForMib( 85 );

    m_encCharset = codec->name();
    const unsigned int m_encCharsetLength = m_encCharset.length();
    for(unsigned int i=0; i < m_encCharsetLength; ++i)
311
        m_encCharset[i] = m_encCharset[i].toLatin1() == ' ' ? QChar('-') : m_encCharset[i].toLower();
George Staikos's avatar
George Staikos committed
312
313

    QStringList fileUploads, fileNotUploads;
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
    
    /**
     Frameworks such as mootools Sortables expect form element values to be submitted in 
     tree order (and HTML5 specifies this behavior); however formElements need not be 
     ordered thus. Hence we walk through the tree and the formElements as we go --- 
     first in our kids, then if needed in the parent
    */
    HashSet<NodeImpl*> formElementsSet;
    foreach (HTMLGenericFormElementImpl* fe, formElements)
        formElementsSet.add(fe);
        
    Vector<HTMLGenericFormElementImpl*> ordered = gatherInTreeOrder(this, formElementsSet);
    
    if (ordered.size() < (unsigned)formElements.size()) {
        // Some of our elements not contained within us due to parsing hijinks -- scan 
        // the entire document.
        ordered = gatherInTreeOrder(document()->documentElement(), formElementsSet);
    }
George Staikos's avatar
George Staikos committed
332

333
334
    for (unsigned i = 0; i < ordered.size(); ++i) {
        HTMLGenericFormElementImpl* const current = ordered[i];
George Staikos's avatar
George Staikos committed
335
336
        khtml::encodingList lst;

337
        if (!current->disabled() && current->encoding(codec, lst, useMultipart))
George Staikos's avatar
George Staikos committed
338
        {
Laurent Montel's avatar
Laurent Montel committed
339
            //kDebug(6030) << "adding name '" << current->name().string() << "'";
340
341
342
            khtml::encodingList::ConstIterator it = lst.constBegin();
            const khtml::encodingList::ConstIterator itEnd = lst.constEnd();
            for( ; it != itEnd; ++it )
George Staikos's avatar
George Staikos committed
343
            {
344
                if (!useMultipart)
George Staikos's avatar
George Staikos committed
345
346
347
348
349
350
351
352
353
354
355
356
                {
                    // handle ISINDEX / <input name=isindex> special
                    // but only if its the first entry
                    if ( enc_string.isEmpty() && *it == "isindex" ) {
                        ++it;
                        enc_string += encodeCString( *it );
                    }
                    else {
                        if(!enc_string.isEmpty())
                            enc_string += '&';

                        enc_string += encodeCString(*it);
Laurent Montel's avatar
Fix ebn    
Laurent Montel committed
357
                        enc_string += '=';
George Staikos's avatar
George Staikos committed
358
359
360
361
362
363
364
                        ++it;
                        enc_string += encodeCString(*it);
                    }
                }
                else
                {
                    QByteArray hstr("--");
365
                    hstr += m_boundary.toLatin1();
George Staikos's avatar
George Staikos committed
366
367
368
369
370
371
372
373
                    hstr += "\r\n";
                    hstr += "Content-Disposition: form-data; name=\"";
                    hstr += (*it).data();
                    hstr += "\"";

                    // if the current type is FILE, then we also need to
                    // include the filename
                    if (current->id() == ID_INPUT &&
Maks Orlovich's avatar
Maks Orlovich committed
374
                        static_cast<HTMLInputElementImpl*>(current)->inputType() == HTMLInputElementImpl::FILE)
George Staikos's avatar
George Staikos committed
375
                    {
376
                        KUrl path;
George Staikos's avatar
George Staikos committed
377
378
379
380
381
382
                        QString val = static_cast<HTMLInputElementImpl*>(current)->value().string().trimmed();
                        if (!val.isEmpty() &&
                            QDir::isRelativePath(val) &&
                            QFile::exists(KGlobalSettings::documentPath() + val)) {
                            path.setPath(KGlobalSettings::documentPath() + val);
                        } else {
383
                            path = KUrl(val);
George Staikos's avatar
George Staikos committed
384
385
386
387
                        }

                        hstr += fixUpfromUnicode(codec, "; filename=\"" + path.fileName() + "\"");
                        if (path.isValid()) {
388
                            fileUploads << path.pathOrUrl();
389
                            const KMimeType::Ptr ptr = KMimeType::findByUrl(path);
George Staikos's avatar
George Staikos committed
390
391
                            if (!ptr->name().isEmpty()) {
                                hstr += "\r\nContent-Type: ";
Heng Liu's avatar
Heng Liu committed
392
                                hstr += ptr->name().toAscii().constData();
George Staikos's avatar
George Staikos committed
393
394
                            }
                        } else if (!val.isEmpty()) {
395
                            fileNotUploads << path.pathOrUrl();
George Staikos's avatar
George Staikos committed
396
397
398
399
400
401
402
                        }
                    }

                    hstr += "\r\n\r\n";
                    ++it;

                    // append body
403
404
405
                    form_data.append(hstr);
                    form_data.append(*it);
                    form_data.append("\r\n");
406

George Staikos's avatar
George Staikos committed
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
		    // reset unsubmittedFormChange flag
                    if (current->id() == ID_INPUT &&
                        static_cast<HTMLInputElementImpl*>(current)->inputType() == HTMLInputElementImpl::TEXT)
                        static_cast<HTMLInputElementImpl*>(current)->setUnsubmittedFormChange(false);

                    if (current->id() == ID_TEXTAREA)
                        static_cast<HTMLTextAreaElementImpl*>(current)->setUnsubmittedFormChange(false);

                }
            }
        }
    }

    if (fileNotUploads.count()) {
        const int result = KMessageBox::warningContinueCancelList( 0,
                                                             i18n("The following files will not be uploaded"
                                                                  " because they could not be found.\n"
                                                                  "Do you want to continue?"),
                                                             fileNotUploads,
426
                                                             i18n("Submit Confirmation"),KGuiItem(i18n("&Submit Anyway"), "dialog-ok"));
George Staikos's avatar
George Staikos committed
427
428
429
430
431
432
433
434
435
436
437
438
439
440


        if (result == KMessageBox::Cancel) {
            ok = false;
            return QByteArray();
        }
    }

    if (fileUploads.count()) {
        const int result = KMessageBox::warningContinueCancelList( 0,
                                                             i18n("You are about to transfer the following files from "
                                                                  "your local computer to the Internet.\n"
                                                                  "Do you really want to continue?"),
                                                             fileUploads,
441
                                                             i18n("Send Confirmation"),KGuiItem(i18np("&Send File", "&Send Files", fileUploads.count()), "document-export"));
George Staikos's avatar
George Staikos committed
442
443
444
445
446
447
448
449


        if (result == KMessageBox::Cancel) {
            ok = false;
            return QByteArray();
        }
    }

450
    if (useMultipart)
451
        enc_string = QString("--" + m_boundary + "--\r\n").toAscii().constData();
George Staikos's avatar
George Staikos committed
452
453
454
455
456
457
458
459
460
461
462

    const int old_size = form_data.size();
    form_data.resize( form_data.size() + enc_string.length() );
    memcpy(form_data.data() + old_size, enc_string.data(), enc_string.length() );

    ok = true;
    return form_data;
}

void HTMLFormElementImpl::setEnctype( const DOMString& type )
{
463
    if(type.string().indexOf("multipart", 0, Qt::CaseInsensitive) != -1 || type.string().indexOf("form-data", 0, Qt::CaseInsensitive) != -1)
George Staikos's avatar
George Staikos committed
464
465
466
    {
        m_enctype = "multipart/form-data";
        m_multipart = true;
467
    } else if (type.string().indexOf("text", 0, Qt::CaseInsensitive) != -1 || type.string().indexOf("plain", 0, Qt::CaseInsensitive) != -1)
George Staikos's avatar
George Staikos committed
468
469
470
471
472
473
474
475
476
477
478
479
480
481
    {
        m_enctype = "text/plain";
        m_multipart = false;
    }
    else
    {
        m_enctype = "application/x-www-form-urlencoded";
        m_multipart = false;
    }
    m_encCharset.clear();
}

static QString calculateAutoFillKey(const HTMLFormElementImpl& e)
{
482
    KUrl k(e.document()->URL());
George Staikos's avatar
George Staikos committed
483
484
485
486
487
488
489
    k.setRef(QString());
    k.setQuery(QString());
    // ensure that we have the user / password inside the url
    // otherwise we might have a potential security problem
    // by saving passwords under wrong lookup key.
    const QString name = e.getAttribute(ATTR_NAME).string().trimmed();
    const QRegExp re("[;,!]");
490
    const QStringList url = k.url().split(re);
George Staikos's avatar
George Staikos committed
491
492
493
494
495
496
497
498
499
500
501
502
503
504
    return url[0] + '#' + name;
}

void HTMLFormElementImpl::doAutoFill()
{
#ifndef KHTML_NO_WALLET
    const QString key = calculateAutoFillKey(*this);

    if (KWallet::Wallet::keyDoesNotExist(KWallet::Wallet::NetworkWallet(),
                                         KWallet::Wallet::FormDataFolder(),
                                         key))
        return;

    // assert(view())
505
    document()->view()->part()->openWallet(this);
George Staikos's avatar
George Staikos committed
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
#endif // KHTML_NO_WALLET
}


void HTMLFormElementImpl::walletOpened(KWallet::Wallet *w) {
#ifndef KHTML_NO_WALLET
    assert(w);
    const QString key = calculateAutoFillKey(*this);
    if (!w->hasFolder(KWallet::Wallet::FormDataFolder())) {
        return; // failed
    }
    w->setFolder(KWallet::Wallet::FormDataFolder());
    QMap<QString, QString> map;
    if (w->readMap(key, map))
        return; // failed, abort

522
523
524
525
    if(document()->view())
    {
        document()->view()->part()->addWalletFormKey(key);
    }
Germain Garand's avatar
Germain Garand committed
526
527
528
529
    for (QListIterator<HTMLGenericFormElementImpl*> it(formElements); it.hasNext();) {
        HTMLGenericFormElementImpl* const cur = it.next();
        if (cur->id() == ID_INPUT) {
            HTMLInputElementImpl* const current = static_cast<HTMLInputElementImpl*>(cur);
George Staikos's avatar
George Staikos committed
530
531
532
533
            if ((current->inputType() == HTMLInputElementImpl::PASSWORD ||
                    current->inputType() == HTMLInputElementImpl::TEXT) &&
                    !current->readOnly() &&
                    map.contains(current->name().string())) {
534
                document()->setFocusNode(current);
George Staikos's avatar
George Staikos committed
535
536
537
538
539
540
541
542
543
544
545
546
547
                current->setValue(map[current->name().string()]);
            }
        }
    }
#endif // KHTML_NO_WALLET
}

void HTMLFormElementImpl::submitFromKeyboard()
{
    // Activate the first nondisabled submit button
    // if there is none, do a submit anyway if not more
    // than one <input type=text> or <input type=password>
    unsigned int inputtext = 0;
Germain Garand's avatar
Germain Garand committed
548
549
550
551
    for (QListIterator<HTMLGenericFormElementImpl*> it(formElements); it.hasNext();) {
        HTMLGenericFormElementImpl* const cur = it.next();
        if (cur->id() == ID_BUTTON) {
            HTMLButtonElementImpl* const current = static_cast<HTMLButtonElementImpl *>(cur);
George Staikos's avatar
George Staikos committed
552
553
554
555
            if (current->buttonType() == HTMLButtonElementImpl::SUBMIT && !current->disabled()) {
                current->click();
                return;
            }
Germain Garand's avatar
Germain Garand committed
556
557
        } else if (cur->id() == ID_INPUT) {
            HTMLInputElementImpl* const current = static_cast<HTMLInputElementImpl *>(cur);
George Staikos's avatar
George Staikos committed
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
            switch(current->inputType())  {
            case HTMLInputElementImpl::SUBMIT:
            case HTMLInputElementImpl::IMAGE:
		if(!current->disabled()) {
			current->click();
			return;
		}
		break;
            case HTMLInputElementImpl::TEXT:
            case HTMLInputElementImpl::PASSWORD:
                ++inputtext;
            default:
                break;
            }
        }
    }

    if (inputtext <= 1)
        prepareSubmit();
}


void HTMLFormElementImpl::gatherWalletData()
{
#ifndef KHTML_NO_WALLET
583
    KHTMLView* const view = document()->view();
George Staikos's avatar
George Staikos committed
584
585
586
587
    // check if we have any password input's
    m_walletMap.clear();
    m_havePassword = false;
    m_haveTextarea = false;
588
    const KUrl formUrl(document()->URL());
589
    if (view && !view->nonPasswordStorableSite(formUrl.host())) {
Germain Garand's avatar
Germain Garand committed
590
591
592
593
        for (QListIterator<HTMLGenericFormElementImpl*> it(formElements); it.hasNext();) {
            HTMLGenericFormElementImpl* const cur = it.next();
            if (cur->id() == ID_INPUT)  {
                HTMLInputElementImpl* const c = static_cast<HTMLInputElementImpl*> (cur);
George Staikos's avatar
George Staikos committed
594
595
596
597
598
599
600
601
602
                if ((c->inputType() == HTMLInputElementImpl::TEXT ||
                        c->inputType() == HTMLInputElementImpl::PASSWORD) &&
                        !c->readOnly())  {
                    m_walletMap.insert(c->name().string(), c->value().string());
                    if (c->inputType() == HTMLInputElementImpl::PASSWORD &&
                            !c->value().isEmpty())
                        m_havePassword = true;
                }
            }
Germain Garand's avatar
Germain Garand committed
603
            else if (cur->id() == ID_TEXTAREA)
George Staikos's avatar
George Staikos committed
604
605
606
607
608
609
610
611
612
                m_haveTextarea = true;
        }
    }
#endif // KHTML_NO_WALLET
}


bool HTMLFormElementImpl::prepareSubmit()
{
613
    KHTMLView* const view = document()->view();
George Staikos's avatar
George Staikos committed
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
    if(m_insubmit || !view || !view->part() || view->part()->onlyLocalReferences())
        return m_insubmit;

    gatherWalletData();

    m_insubmit = true;
    m_doingsubmit = false;

    if ( dispatchHTMLEvent(EventImpl::SUBMIT_EVENT,true,true) && !m_doingsubmit )
        m_doingsubmit = true;

    m_insubmit = false;

    if ( m_doingsubmit )
        submit();

    return m_doingsubmit;
}

void HTMLFormElementImpl::submit(  )
{
    if ( m_insubmit ) {
        m_doingsubmit = true;
        return;
    }

    m_insubmit = true;

#ifdef FORMS_DEBUG
Laurent Montel's avatar
Laurent Montel committed
643
    kDebug( 6030 ) << "submitting!";
George Staikos's avatar
George Staikos committed
644
645
646
#endif

    bool ok;
647
    KHTMLView* const view = document()->view();
George Staikos's avatar
George Staikos committed
648
    const QByteArray form_data = formData(ok);
649
    const KUrl formUrl(document()->URL());
George Staikos's avatar
George Staikos committed
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668

    if (ok && view) {
        if (m_walletMap.isEmpty()) {
            gatherWalletData();
        }
#ifndef KHTML_NO_WALLET
        if (m_havePassword && !m_haveTextarea && KWallet::Wallet::isEnabled()) {
            const QString key = calculateAutoFillKey(*this);
            const bool doesnotexist = KWallet::Wallet::keyDoesNotExist(KWallet::Wallet::NetworkWallet(), KWallet::Wallet::FormDataFolder(), key);
            KWallet::Wallet* const w = view->part()->wallet();
            bool login_changed = false;

            if (!doesnotexist && w) {
                // check if the login information changed from what
                // we had so far.
                if (w->hasFolder(KWallet::Wallet::FormDataFolder())) {
                    w->setFolder(KWallet::Wallet::FormDataFolder());
                    QMap<QString, QString> map;
                    if (!w->readMap(key, map)) {
669
670
                        QMap<QString, QString>::const_iterator it = map.constBegin();
                        const QMap<QString, QString>::const_iterator itEnd = map.constEnd();
George Staikos's avatar
George Staikos committed
671
672
673
674
675
676
677
678
679
680
681
682
                        for ( ; it != itEnd; ++it )
                            if ( map[it.key()] != m_walletMap[it.key()] ) {
                                login_changed = true;
                                break;
                            }
                    } else {
                        login_changed = true;
                    }
                }
            }

            if ( doesnotexist || !w || login_changed ) {
683
684
                if (view->part())
                    view->part()->saveLoginInformation(formUrl.host(), key, m_walletMap);
George Staikos's avatar
George Staikos committed
685
686
687
688
            }
        }
#endif // KHTML_NO_WALLET

689
690
691
692
693
        DOMString value = getAttribute(ATTR_ACTION);
        DOMString url = khtml::parseURL(value);
        // ignore base url if 'action' attribute is empty.
        if (value.isEmpty())
            url = formUrl.url();
George Staikos's avatar
George Staikos committed
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
        if(m_post) {
            view->part()->submitForm( "post", url.string(), form_data,
                                      m_target.string(),
                                      enctype().string(),
                                      m_boundary );
        }
        else {
            view->part()->submitForm( "get", url.string(), form_data,
                                      m_target.string() );
        }
    }

    m_walletMap.clear(); // done with it
    m_havePassword = m_haveTextarea= false;
    m_doingsubmit = m_insubmit = false;
}

void HTMLFormElementImpl::reset(  )
{
713
    KHTMLView* const view = document()->view();
George Staikos's avatar
George Staikos committed
714
715
716
717
718
    if(m_inreset || !view || !view->part()) return;

    m_inreset = true;

#ifdef FORMS_DEBUG
Laurent Montel's avatar
Laurent Montel committed
719
    kDebug( 6030 ) << "reset pressed!";
George Staikos's avatar
George Staikos committed
720
721
722
#endif

    // ### DOM2 labels this event as not cancelable, however
723
    // common browsers( sick! ) allow it be canceled.
George Staikos's avatar
George Staikos committed
724
725
726
727
728
    if ( !dispatchHTMLEvent(EventImpl::RESET_EVENT,true, true) ) {
        m_inreset = false;
        return;
    }

Germain Garand's avatar
Germain Garand committed
729
730
    for (QListIterator<HTMLGenericFormElementImpl*> it(formElements); it.hasNext();)
        it.next()->reset();
George Staikos's avatar
George Staikos committed
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

    m_inreset = false;
}

void HTMLFormElementImpl::parseAttribute(AttributeImpl *attr)
{
    switch(attr->id())
    {
    case ATTR_ACTION:
        break;
    case ATTR_TARGET:
        m_target = attr->value();
        break;
    case ATTR_METHOD:
        m_post = ( strcasecmp( attr->value(), "post" ) == 0 );
        break;
    case ATTR_ENCTYPE:
        setEnctype( attr->value() );
        break;
    case ATTR_ACCEPT_CHARSET:
        // space separated list of charsets the server
        // accepts - see rfc2045
        m_acceptcharset = attr->value();
        break;
    case ATTR_ACCEPT:
        // ignore this one for the moment...
        break;
    case ATTR_AUTOCOMPLETE:
        m_autocomplete = strcasecmp( attr->value(), "off" );
        break;
    case ATTR_ONSUBMIT:
        setHTMLEventListener(EventImpl::SUBMIT_EVENT,
763
	    document()->createHTMLEventListener(attr->value().string(), "onsubmit", this));
George Staikos's avatar
George Staikos committed
764
765
766
        break;
    case ATTR_ONRESET:
        setHTMLEventListener(EventImpl::RESET_EVENT,
767
	    document()->createHTMLEventListener(attr->value().string(), "onreset", this));
George Staikos's avatar
George Staikos committed
768
769
770
        break;
    case ATTR_NAME:
        if (inDocument() && m_name != attr->value()) {
Maks Orlovich's avatar
Maks Orlovich committed
771
772
            document()->underDocNamedCache().remove(m_name,        this);
            document()->underDocNamedCache().add   (attr->value(), this);
George Staikos's avatar
George Staikos committed
773
774
775
776
777
778
779
780
781
782
        }
        m_name = attr->value();
        //Fallthrough intentional
    default:
        HTMLElementImpl::parseAttribute(attr);
    }
}

void HTMLFormElementImpl::removedFromDocument()
{
Maks Orlovich's avatar
Maks Orlovich committed
783
    document()->underDocNamedCache().remove(m_name, this);
George Staikos's avatar
George Staikos committed
784
785
786
787
788
    HTMLElementImpl::removedFromDocument();
}

void HTMLFormElementImpl::insertedIntoDocument()
{
Maks Orlovich's avatar
Maks Orlovich committed
789
    document()->underDocNamedCache().add(m_name, this);
George Staikos's avatar
George Staikos committed
790
791
792
    HTMLElementImpl::insertedIntoDocument();
}

Maks Orlovich's avatar
Maks Orlovich committed
793
void HTMLFormElementImpl::removeId(const DOMString& id)
George Staikos's avatar
George Staikos committed
794
{
795
    document()->underDocNamedCache().remove(id, this);
George Staikos's avatar
George Staikos committed
796
797
798
    HTMLElementImpl::removeId(id);
}

Maks Orlovich's avatar
Maks Orlovich committed
799
void HTMLFormElementImpl::addId   (const DOMString& id)
George Staikos's avatar
George Staikos committed
800
{
801
    document()->underDocNamedCache().add(id, this);
George Staikos's avatar
George Staikos committed
802
803
804
805
    HTMLElementImpl::addId(id);
}


806
void HTMLFormElementImpl::uncheckOtherRadioButtonsInGroup( HTMLGenericFormElementImpl *caller, bool setDefaultChecked )
George Staikos's avatar
George Staikos committed
807
{
Germain Garand's avatar
Germain Garand committed
808
809
    for (QListIterator<HTMLGenericFormElementImpl*> it(formElements); it.hasNext();) {
        HTMLGenericFormElementImpl* const current = it.next();
George Staikos's avatar
George Staikos committed
810
811
812
        if (current->id() == ID_INPUT &&
            static_cast<HTMLInputElementImpl*>(current)->inputType() == HTMLInputElementImpl::RADIO &&
            current != caller && current->form() == caller->form() && current->name() == caller->name())
813
            static_cast<HTMLInputElementImpl*>(current)->setChecked(false, setDefaultChecked);
George Staikos's avatar
George Staikos committed
814
815
816
817
818
819
820
821
822
823
    }
}

void HTMLFormElementImpl::registerFormElement(HTMLGenericFormElementImpl *e)
{
    formElements.append(e);
}

void HTMLFormElementImpl::removeFormElement(HTMLGenericFormElementImpl *e)
{
824
    int i = formElements.indexOf(e);
Germain Garand's avatar
Germain Garand committed
825
826
    if (i != -1)
        formElements.removeAt(i);
827
828
829
830
831
832
833
834
835
        
    if (e->hasPastNames()) {
        QMutableHashIterator<DOMString, HTMLGenericFormElementImpl*> it(m_pastNamesMap);
        while (it.hasNext()) {
            it.next();
            if (it.value() == e)
                it.remove();
        }
    }
George Staikos's avatar
George Staikos committed
836
837
838
839
840
841
842
843
844
}

void HTMLFormElementImpl::registerImgElement(HTMLImageElementImpl *e)
{
    imgElements.append(e);
}

void HTMLFormElementImpl::removeImgElement(HTMLImageElementImpl *e)
{
845
    int i = imgElements.indexOf(e);
Germain Garand's avatar
Germain Garand committed
846
847
    if (i != -1)
        imgElements.removeAt(i);
George Staikos's avatar
George Staikos committed
848
849
}

850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
HTMLGenericFormElementImpl* HTMLFormElementImpl::lookupByPastName(const DOMString& id)
{
    return m_pastNamesMap.value(id);
}

void HTMLFormElementImpl::bindPastName(HTMLGenericFormElementImpl* e)
{
    DOMString id = e->getAttribute(ATTR_ID);
    if (!id.isEmpty())
        m_pastNamesMap.insert(id, e);
        
    DOMString nm = e->getAttribute(ATTR_NAME);
    if (!nm.isEmpty())
        m_pastNamesMap.insert(nm, e);
    e->setHasPastNames();
}

George Staikos's avatar
George Staikos committed
867
868
// -------------------------------------------------------------------------

Germain Garand's avatar
Germain Garand committed
869
HTMLGenericFormElementImpl::HTMLGenericFormElementImpl(DocumentImpl *doc, HTMLFormElementImpl *f)
George Staikos's avatar
George Staikos committed
870
871
    : HTMLElementImpl(doc)
{
872
    m_disabled = m_readOnly = m_hasPastNames = false;
George Staikos's avatar
George Staikos committed
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
    m_name = 0;

    if (f)
	m_form = f;
    else
	m_form = getForm();
    if (m_form)
        m_form->registerFormElement(this);
}

void HTMLGenericFormElementImpl::insertedIntoDocument()
{
    HTMLElementImpl::insertedIntoDocument();

    if (!m_form) {
        HTMLFormElementImpl* const newform = getForm();
        if (newform) {
            m_form = newform;
            m_form->registerFormElement(this);
        }
    }
}

void HTMLGenericFormElementImpl::removedFromDocument()
{
    HTMLElementImpl::removedFromDocument();

    if (m_form)
        m_form->removeFormElement(this);

    m_form = 0;
}

HTMLGenericFormElementImpl::~HTMLGenericFormElementImpl()
{
    if (m_form)
        m_form->removeFormElement(this);
    if (m_name) m_name->deref();
}

void HTMLGenericFormElementImpl::parseAttribute(AttributeImpl *attr)
{
    switch(attr->id())
    {
    case ATTR_DISABLED:
        setDisabled( attr->val() != 0 );
        break;
    case ATTR_READONLY:
    {
        const bool m_oldreadOnly = m_readOnly;
        m_readOnly = attr->val() != 0;
        if (m_oldreadOnly != m_readOnly) setChanged();
        break;
    }
    default:
        HTMLElementImpl::parseAttribute(attr);
    }
}

void HTMLGenericFormElementImpl::attach()
{
    assert(!attached());

    if (m_render) {
        assert(m_render->style());
        parentNode()->renderer()->addChild(m_render, nextRenderer());
    }

    // FIXME: This handles the case of a new form element being created by
    // JavaScript and inserted inside a form. What it does not handle is
    // a form element being moved from inside a form to outside, or from one
    // inside one form to another. The reason this other case is hard to fix
    // is that during parsing, we may have been passed a form that we are not
    // inside, DOM-tree-wise. If so, it's hard for us to know when we should
    // be removed from that form's element list.
    if (!m_form) {
	m_form = getForm();
	if (m_form)
	    m_form->registerFormElement(this);
    }

    NodeBaseImpl::attach();

    // The call to updateFromElement() needs to go after the call through
    // to the base class's attach() because that can sometimes do a close
    // on the renderer.
    if (m_render)
        m_render->updateFromElement();

}

HTMLFormElementImpl *HTMLGenericFormElementImpl::getForm() const
{
    NodeImpl *p = parentNode();
    while(p)
    {
        if( p->id() == ID_FORM )
            return static_cast<HTMLFormElementImpl *>(p);
971
972
973
974
975
        if( p->parentNode() && p->parentNode()->id() == ID_TABLE && p->previousSibling() )
        {
            p = p->previousSibling();
            continue;
        }
Maks Orlovich's avatar
Maks Orlovich committed
976
        p = p->parentNode();
George Staikos's avatar
George Staikos committed
977
978
    }
#ifdef FORMS_DEBUG
Laurent Montel's avatar
Laurent Montel committed
979
980
    kDebug( 6030 ) << "couldn't find form!";
    kDebug( 6030 ) << kBacktrace();
George Staikos's avatar
George Staikos committed
981
982
983
984
985
986
987
988
989
#endif
    return 0;
}

DOMString HTMLGenericFormElementImpl::name() const
{
    if (m_name) return m_name;

// ###
990
//     DOMString n = document()->htmlMode() != DocumentImpl::XHtml ?
George Staikos's avatar
George Staikos committed
991
992
993
994
995
996
997
998
999
1000
//                   getAttribute(ATTR_NAME) : getAttribute(ATTR_ID);
    const DOMString n = getAttribute(ATTR_NAME);
    if (n.isNull())
        return new DOMStringImpl("");

    return n;
}

void HTMLGenericFormElementImpl::setName(const DOMString& name)
{