composerviewbase.cpp 85.1 KB
Newer Older
1
/*
2
3
  SPDX-FileCopyrightText: 2010 Klaralvdalens Datakonsult AB, a KDAB Group company, info@kdab.com
  SPDX-FileCopyrightText: 2010 Leo Franchi <lfranchi@kde.org>
4

5
  SPDX-License-Identifier: LGPL-2.0-or-later
6
7
8
9
10
11
12
13
*/

#include "composerviewbase.h"

#include "attachment/attachmentcontrollerbase.h"
#include "attachment/attachmentmodel.h"
#include "composer-ng/richtextcomposerng.h"
#include "composer-ng/richtextcomposersignatures.h"
Laurent Montel's avatar
Laurent Montel committed
14
#include "composer.h"
15
#include "composer/keyresolver.h"
Laurent Montel's avatar
Laurent Montel committed
16
17
18
#include "composer/signaturecontroller.h"
#include "imagescaling/imagescalingutils.h"
#include "job/emailaddressresolvejob.h"
19
20
#include "part/globalpart.h"
#include "part/infopart.h"
Laurent Montel's avatar
Laurent Montel committed
21
#include "utils/kleo_util.h"
22
#include "utils/util.h"
Laurent Montel's avatar
Laurent Montel committed
23
#include "utils/util_p.h"
Laurent Montel's avatar
Laurent Montel committed
24
25
#include <KPIMTextEdit/RichTextComposerControler>
#include <KPIMTextEdit/RichTextComposerImages>
26

27
#include "sendlater/sendlatercreatejob.h"
Laurent Montel's avatar
Laurent Montel committed
28
#include "sendlater/sendlaterinfo.h"
29
30

#include "helper/messagehelper.h"
Laurent Montel's avatar
Laurent Montel committed
31
#include <PimCommonAkonadi/RecentAddresses>
32
33

#include "settings/messagecomposersettings.h"
Laurent Montel's avatar
Laurent Montel committed
34
#include <MessageComposer/RecipientsEditor>
35

Laurent Montel's avatar
Laurent Montel committed
36
37
#include <KCursorSaver>
#include <KIdentityManagement/Identity>
38
#include <MimeTreeParser/ObjectTreeParser>
39
#include <MimeTreeParser/SimpleObjectTreeSource>
40
#include <Sonnet/DictionaryComboBox>
41

42
#include <MessageCore/AutocryptStorage>
43
#include <MessageCore/NodeHelper>
Laurent Montel's avatar
Laurent Montel committed
44
#include <MessageCore/StringUtil>
45

46
47
#include <MailTransport/TransportComboBox>
#include <MailTransport/TransportManager>
Laurent Montel's avatar
Laurent Montel committed
48
#include <MailTransportAkonadi/MessageQueueJob>
49

Laurent Montel's avatar
Laurent Montel committed
50
#include <Akonadi/KMime/MessageFlags>
51
52
#include <Akonadi/KMime/SpecialMailCollections>
#include <AkonadiCore/collectionfetchjob.h>
Laurent Montel's avatar
Laurent Montel committed
53
#include <AkonadiCore/itemcreatejob.h>
54
55
#include <AkonadiWidgets/collectioncombobox.h>

Laurent Montel's avatar
Laurent Montel committed
56
#include <KEmailAddress>
57
58
59
#include <KIdentityManagement/kidentitymanagement/identitycombo.h>
#include <KIdentityManagement/kidentitymanagement/identitymanager.h>

Laurent Montel's avatar
Laurent Montel committed
60
#include "messagecomposer_debug.h"
61
62
63
64
65
66
67
68

#include <QGpgME/ExportJob>
#include <QGpgME/ImportJob>
#include <QGpgME/Protocol>
#include <gpgme++/context.h>
#include <gpgme++/gpgmepp_version.h>
#include <gpgme++/importresult.h>

69
70
#include <KLocalizedString>
#include <KMessageBox>
Laurent Montel's avatar
Laurent Montel committed
71
#include <QSaveFile>
72
73

#include <QDir>
Laurent Montel's avatar
Laurent Montel committed
74
#include <QStandardPaths>
75
#include <QTemporaryDir>
76
77
78
79
#include <QTimer>
#include <QUuid>
#include <followupreminder/followupremindercreatejob.h>

80
81
using namespace MessageComposer;

82
83
84
85
static QStringList encodeIdn(const QStringList &emails)
{
    QStringList encoded;
    encoded.reserve(emails.count());
Laurent Montel's avatar
Laurent Montel committed
86
    for (const QString &email : emails) {
87
88
89
90
91
92
        encoded << KEmailAddress::normalizeAddressesAndEncodeIdn(email);
    }

    return encoded;
}

93
ComposerViewBase::ComposerViewBase(QObject *parent, QWidget *parentGui)
94
95
96
97
    : QObject(parent)
    , m_msg(KMime::Message::Ptr(new KMime::Message))
    , m_parentWidget(parentGui)
    , m_cryptoMessageFormat(Kleo::AutoFormat)
Laurent Montel's avatar
Minor    
Laurent Montel committed
98
    , m_autoSaveInterval(60000) // default of 1 min
99
100
101
102
103
104
{
    m_charsets << "utf-8"; // default, so we have a backup in case client code forgot to set.

    initAutoSave();
}

105
ComposerViewBase::~ComposerViewBase() = default;
106

107
bool ComposerViewBase::isComposing() const
108
109
110
111
{
    return !m_composers.isEmpty();
}

112
void ComposerViewBase::setMessage(const KMime::Message::Ptr &msg, bool allowDecryption)
113
{
Laurent Montel's avatar
Laurent Montel committed
114
    if (m_attachmentModel) {
Laurent Montel's avatar
Laurent Montel committed
115
        foreach (const MessageCore::AttachmentPart::Ptr &attachment, m_attachmentModel->attachments()) {
Laurent Montel's avatar
Laurent Montel committed
116
117
118
            if (!m_attachmentModel->removeAttachment(attachment)) {
                qCWarning(MESSAGECOMPOSER_LOG) << "Attachment not found.";
            }
119
120
121
122
123
124
125
126
        }
    }
    m_msg = msg;
    if (m_recipientsEditor) {
        m_recipientsEditor->clear();
        m_recipientsEditor->setRecipientString(m_msg->to()->mailboxes(), MessageComposer::Recipient::To);
        m_recipientsEditor->setRecipientString(m_msg->cc()->mailboxes(), MessageComposer::Recipient::Cc);
        m_recipientsEditor->setRecipientString(m_msg->bcc()->mailboxes(), MessageComposer::Recipient::Bcc);
127
        m_recipientsEditor->setRecipientString(m_msg->replyTo()->mailboxes(), MessageComposer::Recipient::ReplyTo);
128
129
130
        m_recipientsEditor->setFocusBottom();

        // If we are loading from a draft, load unexpanded aliases as well
Laurent Montel's avatar
Laurent Montel committed
131
        if (auto hrd = m_msg->headerByType("X-KMail-UnExpanded-To")) {
132
            const QStringList spl = hrd->asUnicodeString().split(QLatin1Char(','));
133
            for (const QString &addr : spl) {
Laurent Montel's avatar
Laurent Montel committed
134
135
136
                if (!m_recipientsEditor->addRecipient(addr, MessageComposer::Recipient::To)) {
                    qCWarning(MESSAGECOMPOSER_LOG) << "Impossible to add recipient.";
                }
137
138
            }
        }
Laurent Montel's avatar
Laurent Montel committed
139
        if (auto hrd = m_msg->headerByType("X-KMail-UnExpanded-CC")) {
140
            const QStringList spl = hrd->asUnicodeString().split(QLatin1Char(','));
141
            for (const QString &addr : spl) {
Laurent Montel's avatar
Laurent Montel committed
142
143
144
                if (!m_recipientsEditor->addRecipient(addr, MessageComposer::Recipient::Cc)) {
                    qCWarning(MESSAGECOMPOSER_LOG) << "Impossible to add recipient.";
                }
145
146
            }
        }
Laurent Montel's avatar
Laurent Montel committed
147
        if (auto hrd = m_msg->headerByType("X-KMail-UnExpanded-BCC")) {
148
            const QStringList spl = hrd->asUnicodeString().split(QLatin1Char(','));
149
            for (const QString &addr : spl) {
Laurent Montel's avatar
Laurent Montel committed
150
151
152
                if (!m_recipientsEditor->addRecipient(addr, MessageComposer::Recipient::Bcc)) {
                    qCWarning(MESSAGECOMPOSER_LOG) << "Impossible to add recipient.";
                }
153
154
            }
        }
155
156
157
158
159
160
161
162
        if (auto hrd = m_msg->headerByType("X-KMail-UnExpanded-Reply-To")) {
            const QStringList spl = hrd->asUnicodeString().split(QLatin1Char(','));
            for (const QString &addr : spl) {
                if (!m_recipientsEditor->addRecipient(addr, MessageComposer::Recipient::ReplyTo)) {
                    qCWarning(MESSAGECOMPOSER_LOG) << "Impossible to add recipient.";
                }
            }
        }
163
164
165
166
167
    }

    // First, we copy the message and then parse it to the object tree parser.
    // The otp gets the message text out of it, in textualContent(), and also decrypts
    // the message if necessary.
Laurent Montel's avatar
Laurent Montel committed
168
    auto msgContent = new KMime::Content;
169
170
    msgContent->setContent(m_msg->encodedContent());
    msgContent->parse();
171
    MimeTreeParser::SimpleObjectTreeSource emptySource;
Laurent Montel's avatar
Laurent Montel committed
172
    MimeTreeParser::ObjectTreeParser otp(&emptySource); // All default are ok
173
    emptySource.setDecryptMessage(allowDecryption);
174
175
176
    otp.parseObjectTree(msgContent);

    // Load the attachments
Laurent Montel's avatar
Laurent Montel committed
177
    foreach (const auto &att, otp.nodeHelper()->attachmentsOfExtraContents()) {
178
179
        addAttachmentPart(att);
    }
Laurent Montel's avatar
Laurent Montel committed
180
    foreach (const auto &att, msgContent->attachments()) {
181
182
183
184
185
186
187
188
189
190
191
        addAttachmentPart(att);
    }

    int transportId = -1;
    if (auto hdr = m_msg->headerByType("X-KMail-Transport")) {
        transportId = hdr->asUnicodeString().toInt();
    }

    if (m_transport) {
        const MailTransport::Transport *transport = MailTransport::TransportManager::self()->transportById(transportId);
        if (transport) {
Laurent Montel's avatar
Laurent Montel committed
192
193
194
            if (!m_transport->setCurrentTransport(transport->id())) {
                qCWarning(MESSAGECOMPOSER_LOG) << "Impossible to find transport id" << transport->id();
            }
195
196
197
198
        }
    }

    // Set the HTML text and collect HTML images
199
    QString htmlContent = otp.htmlContent();
Laurent Montel's avatar
Laurent Montel committed
200
201
202
    if (htmlContent.isEmpty()) {
        m_editor->setPlainText(otp.plainTextContent());
    } else {
Laurent Montel's avatar
Laurent Montel committed
203
        // Bug 372085 <div id="name"> is replaced in qtextedit by <a id="name">... => break url
204
        htmlContent.replace(QRegularExpression(QStringLiteral("<div\\s*id=\".*\">")), QStringLiteral("<div>"));
Laurent Montel's avatar
Laurent Montel committed
205
        m_editor->setHtml(htmlContent);
206
207
208
209
210
        Q_EMIT enableHtml();
        collectImages(m_msg.data());
    }

    if (auto hdr = m_msg->headerByType("X-KMail-CursorPos")) {
Laurent Montel's avatar
Laurent Montel committed
211
        m_editor->setCursorPositionFromStart(hdr->asUnicodeString().toUInt());
212
213
214
215
    }
    delete msgContent;
}

216
void ComposerViewBase::updateTemplate(const KMime::Message::Ptr &msg)
217
218
219
220
{
    // First, we copy the message and then parse it to the object tree parser.
    // The otp gets the message text out of it, in textualContent(), and also decrypts
    // the message if necessary.
Laurent Montel's avatar
Laurent Montel committed
221
    auto msgContent = new KMime::Content;
222
223
    msgContent->setContent(msg->encodedContent());
    msgContent->parse();
224
    MimeTreeParser::SimpleObjectTreeSource emptySource;
Laurent Montel's avatar
Laurent Montel committed
225
    MimeTreeParser::ObjectTreeParser otp(&emptySource); // All default are ok
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
    otp.parseObjectTree(msgContent);
    // Set the HTML text and collect HTML images
    if (!otp.htmlContent().isEmpty()) {
        m_editor->setHtml(otp.htmlContent());
        Q_EMIT enableHtml();
        collectImages(msg.data());
    } else {
        m_editor->setPlainText(otp.plainTextContent());
    }

    if (auto hdr = msg->headerByType("X-KMail-CursorPos")) {
        m_editor->setCursorPositionFromStart(hdr->asUnicodeString().toInt());
    }
    delete msgContent;
}

242
void ComposerViewBase::saveMailSettings()
243
244
245
246
247
248
{
    const KIdentityManagement::Identity identity = identityManager()->identityForUoid(m_identityCombo->currentIdentity());
    auto header = new KMime::Headers::Generic("X-KMail-Transport");
    header->fromUnicodeString(QString::number(m_transport->currentTransportId()), "utf-8");
    m_msg->setHeader(header);

249
250
251
252
    header = new KMime::Headers::Generic("X-KMail-Transport-Name");
    header->fromUnicodeString(m_transport->currentText(), "utf-8");
    m_msg->setHeader(header);

253
254
255
    header = new KMime::Headers::Generic("X-KMail-Fcc");
    header->fromUnicodeString(QString::number(m_fccCollection.id()), "utf-8");
    m_msg->setHeader(header);
256

257
258
259
    header = new KMime::Headers::Generic("X-KMail-Identity");
    header->fromUnicodeString(QString::number(identity.uoid()), "utf-8");
    m_msg->setHeader(header);
260
261
262
263
264

    header = new KMime::Headers::Generic("X-KMail-Identity-Name");
    header->fromUnicodeString(identity.identityName(), "utf-8");
    m_msg->setHeader(header);

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
    header = new KMime::Headers::Generic("X-KMail-Dictionary");
    header->fromUnicodeString(m_dictionary->currentDictionary(), "utf-8");
    m_msg->setHeader(header);

    // Save the quote prefix which is used for this message. Each message can have
    // a different quote prefix, for example depending on the original sender.
    if (m_editor->quotePrefixName().isEmpty()) {
        m_msg->removeHeader("X-KMail-QuotePrefix");
    } else {
        header = new KMime::Headers::Generic("X-KMail-QuotePrefix");
        header->fromUnicodeString(m_editor->quotePrefixName(), "utf-8");
        m_msg->setHeader(header);
    }

    if (m_editor->composerControler()->isFormattingUsed()) {
        qCDebug(MESSAGECOMPOSER_LOG) << "HTML mode";
        header = new KMime::Headers::Generic("X-KMail-Markup");
        header->fromUnicodeString(QStringLiteral("true"), "utf-8");
        m_msg->setHeader(header);
    } else {
        m_msg->removeHeader("X-KMail-Markup");
        qCDebug(MESSAGECOMPOSER_LOG) << "Plain text";
    }
}

290
void ComposerViewBase::clearFollowUp()
291
292
293
294
295
{
    mFollowUpDate = QDate();
    mFollowUpCollection = Akonadi::Collection();
}

296
void ComposerViewBase::send(MessageComposer::MessageSender::SendMethod method, MessageComposer::MessageSender::SaveIn saveIn, bool checkMailDispatcher)
297
298
299
300
{
    mSendMethod = method;
    mSaveIn = saveIn;

301
    KCursorSaver saver(Qt::WaitCursor);
302
303
304
305
306
307
308
309
310
311
312
    const KIdentityManagement::Identity identity = identityManager()->identityForUoid(m_identityCombo->currentIdentity());

    if (identity.attachVcard() && m_attachmentController->attachOwnVcard()) {
        const QString vcardFileName = identity.vCardFile();
        if (!vcardFileName.isEmpty()) {
            m_attachmentController->addAttachmentUrlSync(QUrl::fromLocalFile(vcardFileName));
        }
    }
    saveMailSettings();

    if (m_editor->composerControler()->isFormattingUsed() && inlineSigningEncryptionSelected()) {
Laurent Montel's avatar
Laurent Montel committed
313
314
315
        const QString keepBtnText =
            m_encrypt ? m_sign ? i18n("&Keep markup, do not sign/encrypt") : i18n("&Keep markup, do not encrypt") : i18n("&Keep markup, do not sign");
        const QString yesBtnText = m_encrypt ? m_sign ? i18n("Sign/Encrypt (delete markup)") : i18n("Encrypt (delete markup)") : i18n("Sign (delete markup)");
316
        int ret = KMessageBox::warningYesNoCancel(m_parentWidget,
Laurent Montel's avatar
Laurent Montel committed
317
318
319
320
321
                                                  i18n("<qt><p>Inline signing/encrypting of HTML messages is not possible;</p>"
                                                       "<p>do you want to delete your markup?</p></qt>"),
                                                  i18n("Sign/Encrypt Message?"),
                                                  KGuiItem(yesBtnText),
                                                  KGuiItem(keepBtnText));
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
        if (KMessageBox::Cancel == ret) {
            return;
        }
        if (KMessageBox::No == ret) {
            m_encrypt = false;
            m_sign = false;
        } else {
            Q_EMIT disableHtml(NoConfirmationNeeded);
        }
    }

    if (m_neverEncrypt && saveIn != MessageComposer::MessageSender::SaveInNone) {
        // we can't use the state of the mail itself, to remember the
        // signing and encryption state, so let's add a header instead
        auto header = new KMime::Headers::Generic("X-KMail-SignatureActionEnabled");
        header->fromUnicodeString(m_sign ? QStringLiteral("true") : QStringLiteral("false"), "utf-8");
        m_msg->setHeader(header);
        header = new KMime::Headers::Generic("X-KMail-EncryptActionEnabled");
        header->fromUnicodeString(m_encrypt ? QStringLiteral("true") : QStringLiteral("false"), "utf-8");
        m_msg->setHeader(header);
        header = new KMime::Headers::Generic("X-KMail-CryptoMessageFormat");
        header->fromUnicodeString(QString::number(m_cryptoMessageFormat), "utf-8");
        m_msg->setHeader(header);
    } else {
        MessageComposer::Util::removeNotNecessaryHeaders(m_msg);
    }

Laurent Montel's avatar
Laurent Montel committed
349
    if (mSendMethod == MessageComposer::MessageSender::SendImmediate && checkMailDispatcher) {
Laurent Montel's avatar
Laurent Montel committed
350
351
352
353
        if (!MessageComposer::Util::sendMailDispatcherIsOnline(m_parentWidget)) {
            qCWarning(MESSAGECOMPOSER_LOG) << "Impossible to set sendmaildispatcher online. Please verify it";
            return;
        }
354
355
356
357
358
    }

    readyForSending();
}

359
void ComposerViewBase::setCustomHeader(const QMap<QByteArray, QString> &customHeader)
360
361
362
363
{
    m_customHeader = customHeader;
}

364
void ComposerViewBase::readyForSending()
365
366
367
368
369
370
371
372
373
374
375
376
377
378
{
    qCDebug(MESSAGECOMPOSER_LOG) << "Entering readyForSending";
    if (!m_msg) {
        qCDebug(MESSAGECOMPOSER_LOG) << "m_msg == 0!";
        return;
    }

    if (!m_composers.isEmpty()) {
        // This may happen if e.g. the autosave timer calls applyChanges.
        qCDebug(MESSAGECOMPOSER_LOG) << "Called while composer active; ignoring.";
        return;
    }

    // first, expand all addresses
Laurent Montel's avatar
Laurent Montel committed
379
    auto job = new MessageComposer::EmailAddressResolveJob(this);
380
381
382
383
384
385
386
387
    const KIdentityManagement::Identity identity = identityManager()->identityForUoid(m_identityCombo->currentIdentity());
    if (!identity.isNull()) {
        job->setDefaultDomainName(identity.defaultDomainName());
    }
    job->setFrom(from());
    job->setTo(m_recipientsEditor->recipientStringList(MessageComposer::Recipient::To));
    job->setCc(m_recipientsEditor->recipientStringList(MessageComposer::Recipient::Cc));
    job->setBcc(m_recipientsEditor->recipientStringList(MessageComposer::Recipient::Bcc));
Laurent Montel's avatar
Laurent Montel committed
388
    job->setReplyTo(m_recipientsEditor->recipientStringList(MessageComposer::Recipient::ReplyTo));
389

390
391
392
393
    connect(job, &MessageComposer::EmailAddressResolveJob::result, this, &ComposerViewBase::slotEmailAddressResolved);
    job->start();
}

394
void ComposerViewBase::slotEmailAddressResolved(KJob *job)
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
{
    if (job->error()) {
        qCWarning(MESSAGECOMPOSER_LOG) << "An error occurred while resolving the email addresses:" << job->errorString();
        // This error could be caused by a broken search infrastructure, so we ignore it for now
        // to not block sending emails completely.
    }

    bool autoresizeImage = MessageComposer::MessageComposerSettings::self()->autoResizeImageEnabled();

    const MessageComposer::EmailAddressResolveJob *resolveJob = qobject_cast<MessageComposer::EmailAddressResolveJob *>(job);
    if (mSaveIn == MessageComposer::MessageSender::SaveInNone) {
        mExpandedFrom = resolveJob->expandedFrom();
        mExpandedTo = resolveJob->expandedTo();
        mExpandedCc = resolveJob->expandedCc();
        mExpandedBcc = resolveJob->expandedBcc();
410
        mExpandedReplyTo = resolveJob->expandedReplyTo();
411
412
413
414
415
416
        if (autoresizeImage) {
            QStringList listEmails;
            listEmails << mExpandedFrom;
            listEmails << mExpandedTo;
            listEmails << mExpandedCc;
            listEmails << mExpandedBcc;
417
            listEmails << mExpandedReplyTo;
418
419
420
421
422
423
424
            MessageComposer::Utils resizeUtils;
            autoresizeImage = resizeUtils.filterRecipients(listEmails);
        }
    } else { // saved to draft, so keep the old values, not very nice.
        mExpandedFrom = from();
        foreach (const MessageComposer::Recipient::Ptr &r, m_recipientsEditor->recipients()) {
            switch (r->type()) {
Laurent Montel's avatar
Laurent Montel committed
425
426
427
428
429
430
431
432
433
            case MessageComposer::Recipient::To:
                mExpandedTo << r->email();
                break;
            case MessageComposer::Recipient::Cc:
                mExpandedCc << r->email();
                break;
            case MessageComposer::Recipient::Bcc:
                mExpandedBcc << r->email();
                break;
434
435
436
            case MessageComposer::Recipient::ReplyTo:
                mExpandedReplyTo << r->email();
                break;
Laurent Montel's avatar
Laurent Montel committed
437
            case MessageComposer::Recipient::Undefined:
Yuri Chornoivan's avatar
Yuri Chornoivan committed
438
                Q_ASSERT(!"Unknown recipient type!");
Laurent Montel's avatar
Laurent Montel committed
439
                break;
440
441
            }
        }
442
        QStringList unExpandedTo, unExpandedCc, unExpandedBcc, unExpandedReplyTo;
Laurent Montel's avatar
Laurent Montel committed
443
444
        const auto expandedToLst{resolveJob->expandedTo()};
        for (const QString &exp : expandedToLst) {
Laurent Montel's avatar
Laurent Montel committed
445
            if (!mExpandedTo.contains(exp)) { // this address was expanded, so save it explicitly
446
447
448
                unExpandedTo << exp;
            }
        }
Laurent Montel's avatar
Laurent Montel committed
449
450
        const auto expandedCcLst{resolveJob->expandedCc()};
        for (const QString &exp : expandedCcLst) {
451
452
453
454
            if (!mExpandedCc.contains(exp)) {
                unExpandedCc << exp;
            }
        }
Laurent Montel's avatar
Laurent Montel committed
455
456
        const auto expandedBCcLst{resolveJob->expandedBcc()};
        for (const QString &exp : expandedBCcLst) {
Laurent Montel's avatar
Laurent Montel committed
457
            if (!mExpandedBcc.contains(exp)) { // this address was expanded, so save it explicitly
458
459
460
                unExpandedBcc << exp;
            }
        }
Laurent Montel's avatar
Laurent Montel committed
461
462
        const auto expandedReplyLst{resolveJob->expandedReplyTo()};
        for (const QString &exp : expandedReplyLst) {
Laurent Montel's avatar
Laurent Montel committed
463
            if (!mExpandedReplyTo.contains(exp)) { // this address was expanded, so save it explicitly
464
465
466
                unExpandedReplyTo << exp;
            }
        }
467
        auto header = new KMime::Headers::Generic("X-KMail-UnExpanded-To");
468
        header->from7BitString(unExpandedTo.join(QLatin1String(", ")).toLatin1());
469
470
        m_msg->setHeader(header);
        header = new KMime::Headers::Generic("X-KMail-UnExpanded-CC");
471
        header->from7BitString(unExpandedCc.join(QLatin1String(", ")).toLatin1());
472
473
        m_msg->setHeader(header);
        header = new KMime::Headers::Generic("X-KMail-UnExpanded-BCC");
474
        header->from7BitString(unExpandedBcc.join(QLatin1String(", ")).toLatin1());
475
        m_msg->setHeader(header);
476
        header = new KMime::Headers::Generic("X-KMail-UnExpanded-Reply-To");
477
        header->from7BitString(unExpandedReplyTo.join(QLatin1String(", ")).toLatin1());
478
        m_msg->setHeader(header);
479
480
481
        autoresizeImage = false;
    }

Laurent Montel's avatar
Laurent Montel committed
482
483
484
485
    Q_ASSERT(m_composers.isEmpty()); // composers should be empty. The caller of this function
    // checks for emptiness before calling it
    // so just ensure it actually is empty
    // and document it
486
487
488
    // we first figure out if we need to create multiple messages with different crypto formats
    // if so, we create a composer per format
    // if we aren't signing or encrypting, this just returns a single empty message
489
    if (m_neverEncrypt && mSaveIn != MessageComposer::MessageSender::SaveInNone && !mSendLaterInfo) {
Laurent Montel's avatar
Laurent Montel committed
490
        auto composer = new MessageComposer::Composer;
491
492
493
        composer->setNoCrypto(true);
        m_composers.append(composer);
    } else {
494
        bool wasCanceled = false;
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
        m_composers = generateCryptoMessages(wasCanceled);
        if (wasCanceled) {
            return;
        }
    }

    if (m_composers.isEmpty()) {
        Q_EMIT failed(i18n("It was not possible to create a message composer."));
        return;
    }

    if (autoresizeImage) {
        if (MessageComposer::MessageComposerSettings::self()->askBeforeResizing()) {
            if (m_attachmentModel) {
                MessageComposer::Utils resizeUtils;
                if (resizeUtils.containsImage(m_attachmentModel->attachments())) {
Laurent Montel's avatar
Laurent Montel committed
511
512
513
514
515
                    const int rc = KMessageBox::warningYesNo(m_parentWidget,
                                                             i18n("Do you want to resize images?"),
                                                             i18n("Auto Resize Images"),
                                                             KStandardGuiItem::yes(),
                                                             KStandardGuiItem::no());
516
517
518
519
520
521
522
523
524
525
526
527
                    if (rc == KMessageBox::Yes) {
                        autoresizeImage = true;
                    } else {
                        autoresizeImage = false;
                    }
                } else {
                    autoresizeImage = false;
                }
            }
        }
    }
    // Compose each message and prepare it for queueing, sending, or storing
Laurent Montel's avatar
Laurent Montel committed
528

529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
    foreach (MessageComposer::Composer *composer, m_composers) {
        fillGlobalPart(composer->globalPart());
        m_editor->fillComposerTextPart(composer->textPart());
        fillInfoPart(composer->infoPart(), UseExpandedRecipients);

        if (m_attachmentModel) {
            composer->addAttachmentParts(m_attachmentModel->attachments(), autoresizeImage);
        }

        connect(composer, &MessageComposer::Composer::result, this, &ComposerViewBase::slotSendComposeResult);
        composer->start();
        qCDebug(MESSAGECOMPOSER_LOG) << "Started a composer for sending!";
    }
}

Laurent Montel's avatar
Laurent Montel committed
544
545
namespace
{
546
547
548
549
// helper methods for reading encryption settings

inline int encryptKeyNearExpiryWarningThresholdInDays()
{
Laurent Montel's avatar
Laurent Montel committed
550
    if (!MessageComposer::MessageComposerSettings::self()->cryptoWarnWhenNearExpire()) {
551
552
        return -1;
    }
Laurent Montel's avatar
Laurent Montel committed
553
    const int num = MessageComposer::MessageComposerSettings::self()->cryptoWarnEncrKeyNearExpiryThresholdDays();
554
555
556
557
558
    return qMax(1, num);
}

inline int signingKeyNearExpiryWarningThresholdInDays()
{
Laurent Montel's avatar
Laurent Montel committed
559
    if (!MessageComposer::MessageComposerSettings::self()->cryptoWarnWhenNearExpire()) {
560
561
        return -1;
    }
Laurent Montel's avatar
Laurent Montel committed
562
    const int num = MessageComposer::MessageComposerSettings::self()->cryptoWarnSignKeyNearExpiryThresholdDays();
563
564
565
566
567
    return qMax(1, num);
}

inline int encryptRootCertNearExpiryWarningThresholdInDays()
{
Laurent Montel's avatar
Laurent Montel committed
568
    if (!MessageComposer::MessageComposerSettings::self()->cryptoWarnWhenNearExpire()) {
569
570
        return -1;
    }
Laurent Montel's avatar
Laurent Montel committed
571
    const int num = MessageComposer::MessageComposerSettings::self()->cryptoWarnEncrRootNearExpiryThresholdDays();
572
573
574
575
576
    return qMax(1, num);
}

inline int signingRootCertNearExpiryWarningThresholdInDays()
{
Laurent Montel's avatar
Laurent Montel committed
577
    if (!MessageComposer::MessageComposerSettings::self()->cryptoWarnWhenNearExpire()) {
578
579
        return -1;
    }
Laurent Montel's avatar
Laurent Montel committed
580
    const int num = MessageComposer::MessageComposerSettings::self()->cryptoWarnSignRootNearExpiryThresholdDays();
581
582
583
584
585
    return qMax(1, num);
}

inline int encryptChainCertNearExpiryWarningThresholdInDays()
{
Laurent Montel's avatar
Laurent Montel committed
586
    if (!MessageComposer::MessageComposerSettings::self()->cryptoWarnWhenNearExpire()) {
587
588
        return -1;
    }
Laurent Montel's avatar
Laurent Montel committed
589
    const int num = MessageComposer::MessageComposerSettings::self()->cryptoWarnEncrChaincertNearExpiryThresholdDays();
590
591
592
593
594
    return qMax(1, num);
}

inline int signingChainCertNearExpiryWarningThresholdInDays()
{
Laurent Montel's avatar
Laurent Montel committed
595
    if (!MessageComposer::MessageComposerSettings::self()->cryptoWarnWhenNearExpire()) {
596
597
        return -1;
    }
Laurent Montel's avatar
Laurent Montel committed
598
    const int num = MessageComposer::MessageComposerSettings::self()->cryptoWarnSignChaincertNearExpiryThresholdDays();
599
600
601
602
603
604
605
606
607
608
609
610
611
612
    return qMax(1, num);
}

inline bool encryptToSelf()
{
    return MessageComposer::MessageComposerSettings::self()->cryptoEncryptToSelf();
}

inline bool showKeyApprovalDialog()
{
    return MessageComposer::MessageComposerSettings::self()->cryptoShowKeysForApproval();
}
} // nameless namespace

Sandro Knauß's avatar
Sandro Knauß committed
613
614
615
bool ComposerViewBase::addKeysToContext(const QString &gnupgHome,
                                        const QVector<QPair<QStringList, std::vector<GpgME::Key>>> &data,
                                        const std::map<QByteArray, QString> &autocryptMap)
616
617
618
{
    bool needSpecialContext = false;

Sandro Knauß's avatar
Sandro Knauß committed
619
    for (const auto &p : data) {
Laurent Montel's avatar
Laurent Montel committed
620
        for (const auto &k : p.second) {
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
            const auto it = autocryptMap.find(k.primaryFingerprint());
            if (it != autocryptMap.end()) {
                needSpecialContext = true;
                break;
            }
        }
        if (needSpecialContext) {
            break;
        }
    }

    qDebug() << "addKeysToContext: " << needSpecialContext;

    if (!needSpecialContext) {
        return false;
    }
    const QGpgME::Protocol *proto(QGpgME::openpgp());

    const auto storage = MessageCore::AutocryptStorage::self();
    QEventLoop loop;
    int runningJobs = 0;
Sandro Knauß's avatar
Sandro Knauß committed
642
    for (const auto &p : data) {
Laurent Montel's avatar
Laurent Montel committed
643
        for (const auto &k : p.second) {
644
645
646
647
            const auto it = autocryptMap.find(k.primaryFingerprint());
            if (it == autocryptMap.end()) {
                qDebug() << "Adding " << k.primaryFingerprint() << "via Export/Import";
                auto exportJob = proto->publicKeyExportJob(false);
Sandro Knauß's avatar
Sandro Knauß committed
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
                connect(exportJob,
                        &QGpgME::ExportJob::result,
                        [&gnupgHome, &proto, &runningJobs, &loop, &k](const GpgME::Error &result,
                                                                      const QByteArray &keyData,
                                                                      const QString &auditLogAsHtml,
                                                                      const GpgME::Error &auditLogError) {
                            Q_UNUSED(auditLogAsHtml);
                            Q_UNUSED(auditLogError);
                            if (result) {
                                qCWarning(MESSAGECOMPOSER_LOG) << "Failed to export " << k.primaryFingerprint() << result.asString();
                                --runningJobs;
                                if (runningJobs < 1) {
                                    loop.quit();
                                }
                            }

                            auto importJob = proto->importJob();
                            QGpgME::Job::context(importJob)->setEngineHomeDirectory(gnupgHome.toUtf8().constData());
                            importJob->exec(keyData);
                            importJob->deleteLater();
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
                            --runningJobs;
                            if (runningJobs < 1) {
                                loop.quit();
                            }
                        });
                QStringList patterns;
                patterns << QString::fromUtf8(k.primaryFingerprint());
                runningJobs++;
                exportJob->start(patterns);
#if GPGMEPP_VERSION >= 0x10E00 // 1.14.0
                exportJob->setExportFlags(GpgME::Context::ExportMinimal);
#endif
            } else {
                qDebug() << "Adding " << k.primaryFingerprint() << "from Autocrypt storage";
                const auto recipient = storage->getRecipient(it->second.toUtf8());
                auto key = recipient->gpgKey();
                auto keydata = recipient->gpgKeydata();
                if (QByteArray(key.primaryFingerprint()) != QByteArray(k.primaryFingerprint())) {
                    qDebug() << "Using gossipkey";
                    keydata = recipient->gossipKeydata();
                }
                auto importJob = proto->importJob();
                QGpgME::Job::context(importJob)->setEngineHomeDirectory(gnupgHome.toUtf8().constData());
                const auto result = importJob->exec(keydata);
                importJob->deleteLater();
            }
        }
    }
    loop.exec();
    return true;
}

Laurent Montel's avatar
Laurent Montel committed
700
QVector<MessageComposer::Composer *> ComposerViewBase::generateCryptoMessages(bool &wasCanceled)
701
{
702
    const KIdentityManagement::Identity &id = m_identMan->identityForUoidOrDefault(m_identityCombo->currentIdentity());
703
704

    qCDebug(MESSAGECOMPOSER_LOG) << "filling crypto info";
Laurent Montel's avatar
Laurent Montel committed
705
    QScopedPointer<Kleo::KeyResolver> keyResolver(new Kleo::KeyResolver(encryptToSelf(),
Laurent Montel's avatar
Laurent Montel committed
706
707
708
709
710
711
712
713
714
                                                                        showKeyApprovalDialog(),
                                                                        id.pgpAutoEncrypt(),
                                                                        m_cryptoMessageFormat,
                                                                        encryptKeyNearExpiryWarningThresholdInDays(),
                                                                        signingKeyNearExpiryWarningThresholdInDays(),
                                                                        encryptRootCertNearExpiryWarningThresholdInDays(),
                                                                        signingRootCertNearExpiryWarningThresholdInDays(),
                                                                        encryptChainCertNearExpiryWarningThresholdInDays(),
                                                                        signingChainCertNearExpiryWarningThresholdInDays()));
715

716
717
    keyResolver->setAutocryptEnabled(id.autocryptEnabled());

718
719
720
721
722
723
724
725
    QStringList encryptToSelfKeys;
    QStringList signKeys;

    bool signSomething = m_sign;
    bool doSignCompletely = m_sign;
    bool encryptSomething = m_encrypt;
    bool doEncryptCompletely = m_encrypt;

Laurent Montel's avatar
Laurent Montel committed
726
    // Add encryptionkeys from id to keyResolver
727
728
729
730
731
732
733
734
735
    qCDebug(MESSAGECOMPOSER_LOG) << id.pgpEncryptionKey().isEmpty() << id.smimeEncryptionKey().isEmpty();
    if (!id.pgpEncryptionKey().isEmpty()) {
        encryptToSelfKeys.push_back(QLatin1String(id.pgpEncryptionKey()));
    }
    if (!id.smimeEncryptionKey().isEmpty()) {
        encryptToSelfKeys.push_back(QLatin1String(id.smimeEncryptionKey()));
    }
    if (keyResolver->setEncryptToSelfKeys(encryptToSelfKeys) != Kleo::Ok) {
        qCDebug(MESSAGECOMPOSER_LOG) << "Failed to set encryptoToSelf keys!";
Laurent Montel's avatar
Laurent Montel committed
736
        return QVector<MessageComposer::Composer *>();
737
738
    }

Laurent Montel's avatar
Laurent Montel committed
739
    // Add signingkeys from id to keyResolver
740
741
742
743
744
745
746
747
    if (!id.pgpSigningKey().isEmpty()) {
        signKeys.push_back(QLatin1String(id.pgpSigningKey()));
    }
    if (!id.smimeSigningKey().isEmpty()) {
        signKeys.push_back(QLatin1String(id.smimeSigningKey()));
    }
    if (keyResolver->setSigningKeys(signKeys) != Kleo::Ok) {
        qCDebug(MESSAGECOMPOSER_LOG) << "Failed to set signing keys!";
Laurent Montel's avatar
Laurent Montel committed
748
        return QVector<MessageComposer::Composer *>();
749
750
751
    }

    if (m_attachmentModel) {
Laurent Montel's avatar
Laurent Montel committed
752
753
        const auto attachments = m_attachmentModel->attachments();
        for (const MessageCore::AttachmentPart::Ptr &attachment : attachments) {
754
755
756
757
758
759
760
761
762
763
764
765
766
            if (attachment->isSigned()) {
                signSomething = true;
            } else {
                doEncryptCompletely = false;
            }
            if (attachment->isEncrypted()) {
                encryptSomething = true;
            } else {
                doSignCompletely = false;
            }
        }
    }

Laurent Montel's avatar
Laurent Montel committed
767
    const QStringList recipients = mExpandedTo + mExpandedCc;
Laurent Montel's avatar
Laurent Montel committed
768
    const QStringList bcc(mExpandedBcc);
769
770
771
772
773
774

    keyResolver->setPrimaryRecipients(recipients);
    keyResolver->setSecondaryRecipients(bcc);

    bool result = true;
    bool canceled = false;
Laurent Montel's avatar
Laurent Montel committed
775
    signSomething = determineWhetherToSign(doSignCompletely, keyResolver.data(), signSomething, result, canceled);
776
777
778
779
780
781
782
783
784
    if (!result) {
        // TODO handle failure
        qCDebug(MESSAGECOMPOSER_LOG) << "determineWhetherToSign: failed to resolve keys! oh noes";
        if (!canceled) {
            Q_EMIT failed(i18n("Failed to resolve keys. Please report a bug."));
        } else {
            Q_EMIT failed(QString());
        }
        wasCanceled = canceled;
Laurent Montel's avatar
Laurent Montel committed
785
        return QVector<MessageComposer::Composer *>();
786
787
788
    }

    canceled = false;
Laurent Montel's avatar
Laurent Montel committed
789
    encryptSomething = determineWhetherToEncrypt(doEncryptCompletely, keyResolver.data(), encryptSomething, signSomething, result, canceled);
790
791
792
793
794
795
796
797
798
799
    if (!result) {
        // TODO handle failure
        qCDebug(MESSAGECOMPOSER_LOG) << "determineWhetherToEncrypt: failed to resolve keys! oh noes";
        if (!canceled) {
            Q_EMIT failed(i18n("Failed to resolve keys. Please report a bug."));
        } else {
            Q_EMIT failed(QString());
        }

        wasCanceled = canceled;
Laurent Montel's avatar
Laurent Montel committed
800
        return QVector<MessageComposer::Composer *>();
801
802
    }

Laurent Montel's avatar
Laurent Montel committed
803
    // No encryption or signing is needed
804
    if (!signSomething && !encryptSomething) {
Laurent Montel's avatar
Laurent Montel committed
805
        return QVector<MessageComposer::Composer *>() << new MessageComposer::Composer();
806
807
808
809
810
    }

    const Kleo::Result kpgpResult = keyResolver->resolveAllKeys(signSomething, encryptSomething);
    if (kpgpResult == Kleo::Canceled) {
        qCDebug(MESSAGECOMPOSER_LOG) << "resolveAllKeys: one key resolution canceled by user";
Laurent Montel's avatar
Laurent Montel committed
811
        return QVector<MessageComposer::Composer *>();
812
813
814
815
    } else if (kpgpResult != Kleo::Ok) {
        // TODO handle failure
        qCDebug(MESSAGECOMPOSER_LOG) << "resolveAllKeys: failed to resolve keys! oh noes";
        Q_EMIT failed(i18n("Failed to resolve keys. Please report a bug."));
Laurent Montel's avatar
Laurent Montel committed
816
        return QVector<MessageComposer::Composer *>();
817
818
819
    }
    qCDebug(MESSAGECOMPOSER_LOG) << "done resolving keys:";

Laurent Montel's avatar
Laurent Montel committed
820
    QVector<MessageComposer::Composer *> composers;
821
822
823
824
825
826
827
828
829
830
831
832
833

    if (encryptSomething || signSomething) {
        Kleo::CryptoMessageFormat concreteFormat = Kleo::AutoFormat;
        for (unsigned int i = 0; i < numConcreteCryptoMessageFormats; ++i) {
            concreteFormat = concreteCryptoMessageFormats[i];
            if (keyResolver->encryptionItems(concreteFormat).empty()) {
                continue;
            }

            if (!(concreteFormat & m_cryptoMessageFormat)) {
                continue;
            }

Laurent Montel's avatar
Laurent Montel committed
834
            auto composer = new MessageComposer::Composer;
835
836
837
838

            if (encryptSomething) {
                std::vector<Kleo::KeyResolver::SplitInfo> encData = keyResolver->encryptionItems(concreteFormat);
                std::vector<Kleo::KeyResolver::SplitInfo>::iterator it;
Laurent Montel's avatar
Laurent Montel committed
839
                auto end(encData.end());
Laurent Montel's avatar
Laurent Montel committed
840
                QVector<QPair<QStringList, std::vector<GpgME::Key>>> data;
841
842
                data.reserve(encData.size());
                for (it = encData.begin(); it != end; ++it) {
Laurent Montel's avatar
Laurent Montel committed
843
                    QPair<QStringList, std::vector<GpgME::Key>> p(it->recipients, it->keys);
844
845
846
847
                    data.append(p);
                    qCDebug(MESSAGECOMPOSER_LOG) << "got resolved keys for:" << it->recipients;
                }
                composer->setEncryptionKeys(data);
848
849
850
851
852
853
854
855
856
857
                if (concreteFormat & Kleo::OpenPGPMIMEFormat && id.autocryptEnabled()) {
                    composer->setAutocryptEnabled(id.autocryptEnabled());
                    composer->setSenderEncryptionKey(keyResolver->encryptToSelfKeysFor(concreteFormat)[0]);
                    QTemporaryDir dir;
                    bool specialGnupgHome = addKeysToContext(dir.path(), data, keyResolver->useAutocrypt());
                    if (specialGnupgHome) {
                        dir.setAutoRemove(false);
                        composer->setGnupgHome(dir.path());
                    }
                }
858
859
860
861
862
863
864
865
866
867
868
869
870
871
            }

            if (signSomething) {
                // find signing keys for this format
                std::vector<GpgME::Key> signingKeys = keyResolver->signingKeys(concreteFormat);
                composer->setSigningKeys(signingKeys);
            }

            composer->setMessageCryptoFormat(concreteFormat);
            composer->setSignAndEncrypt(signSomething, encryptSomething);

            composers.append(composer);
        }
    } else {
Laurent Montel's avatar
Laurent Montel committed
872
        auto composer = new MessageComposer::Composer;
873
        composers.append(composer);
Laurent Montel's avatar
Laurent Montel committed
874
        // If we canceled sign or encrypt be sure to change status in attachment.
875
        markAllAttachmentsForSigning(false);
Laurent Montel's avatar
Laurent Montel committed
876
        markAllAttachmentsForEncryption(false);
877
878
879
880
881
882
883
884
885
    }

    if (composers.isEmpty() && (signSomething || encryptSomething)) {
        Q_ASSERT_X(false, "ComposerViewBase::fillCryptoInfo", "No concrete sign or encrypt method selected");
    }

    return composers;
}

886
void ComposerViewBase::fillGlobalPart(MessageComposer::GlobalPart *globalPart)
887
888
889
890
{
    globalPart->setParentWidgetForGui(m_parentWidget);
    globalPart->setCharsets(m_charsets);
    globalPart->setMDNRequested(m_mdnRequested);
891
    globalPart->setRequestDeleveryConfirmation(m_requestDeleveryConfirmation);
892
893
}

894
void ComposerViewBase::fillInfoPart(MessageComposer::InfoPart *infoPart, ComposerViewBase::RecipientExpansion expansion)
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
{
    // TODO splitAddressList and expandAliases ugliness should be handled by a
    // special AddressListEdit widget... (later: see RecipientsEditor)

    if (m_fccCombo) {
        infoPart->setFcc(QString::number(m_fccCombo->currentCollection().id()));
    } else {
        if (m_fccCollection.isValid()) {
            infoPart->setFcc(QString::number(m_fccCollection.id()));
        }
    }

    infoPart->setTransportId(m_transport->currentTransportId());
    if (expansion == UseExpandedRecipients) {
        infoPart->setFrom(mExpandedFrom);
        infoPart->setTo(mExpandedTo);
        infoPart->setCc(mExpandedCc);
        infoPart->setBcc(mExpandedBcc);
913
        infoPart->setReplyTo(mExpandedReplyTo);
914
915
916
917
918
    } else {
        infoPart->setFrom(from());
        infoPart->setTo(m_recipientsEditor->recipientStringList(MessageComposer::Recipient::To));
        infoPart->setCc(m_recipientsEditor->recipientStringList(MessageComposer::Recipient::Cc));
        infoPart->setBcc(m_recipientsEditor->recipientStringList(MessageComposer::Recipient::Bcc));
919
        infoPart->setReplyTo(m_recipientsEditor->recipientStringList(MessageComposer::Recipient::ReplyTo));
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
    }
    infoPart->setSubject(subject());
    infoPart->setUserAgent(QStringLiteral("KMail"));
    infoPart->setUrgent(m_urgent);

    if (m_msg->inReplyTo()) {
        infoPart->setInReplyTo(m_msg->inReplyTo()->asUnicodeString());
    }

    if (m_msg->references()) {
        infoPart->setReferences(m_msg->references()->asUnicodeString());
    }

    KMime::Headers::Base::List extras;
    if (auto hdr = m_msg->headerByType("X-KMail-SignatureActionEnabled")) {
        extras << hdr;
    }
    if (auto hdr = m_msg->headerByType("X-KMail-EncryptActionEnabled")) {
        extras << hdr;
    }
    if (auto hdr = m_msg->headerByType("X-KMail-CryptoMessageFormat")) {
        extras << hdr;
    }
    if (auto hdr = m_msg->headerByType("X-KMail-UnExpanded-To")) {
        extras << hdr;
    }
    if (auto hdr = m_msg->headerByType("X-KMail-UnExpanded-CC")) {
        extras << hdr;
    }
    if (auto hdr = m_msg->headerByType("X-KMail-UnExpanded-BCC")) {
        extras << hdr;
    }
952
953
954
    if (auto hdr = m_msg->headerByType("X-KMail-UnExpanded-Reply-To")) {
        extras << hdr;
    }
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
    if (auto hdr = m_msg->organization(false)) {
        extras << hdr;
    }
    if (auto hdr = m_msg->headerByType("X-KMail-Identity")) {
        extras << hdr;
    }
    if (auto hdr = m_msg->headerByType("X-KMail-Transport")) {
        extras << hdr;
    }
    if (auto hdr = m_msg->headerByType("X-KMail-Fcc")) {
        extras << hdr;
    }
    if (auto hdr = m_msg->headerByType("X-KMail-Drafts")) {
        extras << hdr;
    }
    if (auto hdr = m_msg->headerByType("X-KMail-Templates")) {
        extras << hdr;
    }
    if (auto hdr = m_msg->headerByType("X-KMail-Link-Message")) {
        extras << hdr;
    }
    if (auto hdr = m_msg->headerByType("X-KMail-Link-Type")) {
        extras << hdr;
    }
    if (auto hdr = m_msg->headerByType("X-Face")) {
        extras << hdr;
    }
    if (auto hdr = m_msg->headerByType("X-KMail-FccDisabled")) {
        extras << hdr;
    }
985
986
987
988
    if (auto hdr = m_msg->headerByType("X-KMail-Identity-Name")) {
        extras << hdr;
    }
    if (auto hdr = m_msg->headerByType("X-KMail-Transport-Name")) {
989
990
991
992
993
994
        extras << hdr;
    }

    infoPart->setExtraHeaders(extras);
}

995
void ComposerViewBase::slotSendComposeResult(KJob *job)
996
{
Laurent Montel's avatar
Laurent Montel committed
997
998
    Q_ASSERT(dynamic_cast<MessageComposer::Composer *>(job));
    auto composer = static_cast<MessageComposer::Composer *>(job);
999
1000
1001
    if (composer->error() != MessageComposer::Composer::NoError) {
        qCDebug(MESSAGECOMPOSER_LOG) << "compose job might have error: " << job->error() << " errorString: " << job->errorString();
    }
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021

    if (composer->error() == MessageComposer::Composer::NoError) {
        Q_ASSERT(m_composers.contains(composer));
        // The messages were composed successfully.
        qCDebug(MESSAGECOMPOSER_LOG) << "NoError.";
        const int numberOfMessage(composer->resultMessages().size());
        for (int i = 0; i < numberOfMessage; ++i) {
            if (mSaveIn == MessageComposer::MessageSender::SaveInNone) {
                queueMessage(composer->resultMessages().at(i), composer);
            } else {
                saveMessage(composer->resultMessages().at(i), mSaveIn);
            }
        }
        saveRecentAddresses(composer->resultMessages().at(0));
    } else if (composer->error() == MessageComposer::Composer::UserCancelledError) {
        // The job warned the user about something, and the user chose to return
        // to the message.  Nothing to do.
        qCDebug(MESSAGECOMPOSER_LOG) << "UserCancelledError.";
        Q_EMIT failed(i18n("Job cancelled by the user"));
    } else {
Laurent Montel's avatar
Laurent Montel committed
1022
        qCDebug(MESSAGECOMPOSER_LOG) << "other Error." << composer->error();
1023
1024
1025
1026
1027
1028
1029
1030
1031
        QString msg;
        if (composer->error() == MessageComposer::Composer::BugError) {
            msg = i18n("Could not compose message: %1 \n Please report this bug.", job->errorString());
        } else {
            msg = i18n("Could not compose message: %1", job->errorString());
        }
        Q_EMIT failed(msg);
    }

1032
1033
1034
1035
1036
    if (!composer->gnupgHome().isEmpty()) {
        QDir dir(composer->gnupgHome());
        dir.removeRecursively();
    }

1037
1038
1039
    m_composers.removeAll(composer);
}

1040
void ComposerViewBase::saveRecentAddresses(const KMime::Message::Ptr &msg)
1041
{
Laurent Montel's avatar
Laurent Montel committed
1042
    KConfig *config = MessageComposer::MessageComposerSettings::self()->config();
Laurent Montel's avatar
Laurent Montel committed
1043
1044
    const QVector<QByteArray> toAddresses = msg->to()->addresses();
    for (const QByteArray &address : toAddresses) {
Laurent Montel's avatar
Laurent Montel committed
1045
        PimCommon::RecentAddresses::self(config)->add(QLatin1String(address));
1046
    }
Laurent Montel's avatar
Laurent Montel committed
1047
1048
    const QVector<QByteArray> ccAddresses = msg->cc()->addresses();
    for (const QByteArray &address : ccAddresses) {
Laurent Montel's avatar
Laurent Montel committed
1049
        PimCommon::RecentAddresses::self(config)->add(QLatin1String(address));
1050
    }
Laurent Montel's avatar
Laurent Montel committed
1051
1052
    const QVector<QByteArray> bccAddresses = msg->bcc()->addresses();
    for (const QByteArray &address : bccAddresses) {
Laurent Montel's avatar
Laurent Montel committed
1053
        PimCommon::RecentAddresses::self(config)->add(QLatin1String(address));
1054
1055
1056
    }
}

1057
void ComposerViewBase::queueMessage(const KMime::Message::Ptr &message, MessageComposer::Composer *composer)
1058
1059
{
    const MessageComposer::InfoPart *infoPart = composer->infoPart();
Laurent Montel's avatar
Laurent Montel committed
1060
    auto qjob = new MailTransport::MessageQueueJob(this);
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
    qjob->setMessage(message);
    qjob->transportAttribute().setTransportId(infoPart->transportId());
    if (mSendMethod == MessageComposer::MessageSender::SendLater) {
        qjob->dispatchModeAttribute().setDispatchMode(MailTransport::DispatchModeAttribute::Manual);
    }

    if (message->hasHeader("X-KMail-FccDisabled")) {
        qjob->sentBehaviourAttribute().setSentBehaviour(MailTransport::SentBehaviourAttribute::Delete);
    } else if (!infoPart->fcc().isEmpty()) {
        qjob->sentBehaviourAttribute().setSentBehaviour(MailTransport::SentBehaviourAttribute::MoveToCollection);

        const Akonadi::Collection sentCollection(infoPart->fcc().toLongLong());
        qjob->sentBehaviourAttribute().setMoveToCollection(sentCollection);
    } else {
Laurent Montel's avatar
Laurent Montel committed
1075
        qjob->sentBehaviourAttribute().setSentBehaviour(MailTransport::SentBehaviourAttribute::MoveToDefaultSentCollection);
1076
1077
1078
1079
1080
1081
1082
    }
    MessageComposer::Util::addSendReplyForwardAction(message, qjob);

    fillQueueJobHeaders(qjob, message, infoPart);

    MessageCore::StringUtil::removePrivateHeaderFields(message, false);

1083
    addCustomHeaders(message);
1084
1085
1086
1087
1088
1089
1090
1091
    message->assemble();
    connect(qjob, &MailTransport::MessageQueueJob::result, this, &ComposerViewBase::slotQueueResult);
    m_pendingQueueJobs++;
    qjob->start();

    qCDebug(MESSAGECOMPOSER_LOG) << "Queued a message.";
}

1092
void ComposerViewBase::slotQueueResult(KJob *job)
1093
1094
{
    m_pendingQueueJobs--;
Laurent Montel's avatar
Laurent Montel committed
1095
    auto qjob = static_cast<MailTransport::MessageQueueJob *>(job);
1096
1097
1098
1099
1100
1101
1102
1103
    qCDebug(MESSAGECOMPOSER_LOG) << "mPendingQueueJobs" << m_pendingQueueJobs;
    Q_ASSERT(m_pendingQueueJobs >= 0);

    if (job->error()) {
        qCDebug(MESSAGECOMPOSER_LOG) << "Failed to queue a message:" << job->errorString();
        // There is not much we can do now, since all the MessageQueueJobs have been
        // started.  So just wait for them to finish.
        // TODO show a message box or something
Laurent Montel's avatar
Laurent Montel committed
1104
        QString msg = i18n("There were problems trying to queue the message for sending: %1", job->errorString());
1105
1106
1107
1108
1109
1110
1111
1112
1113

        if (m_pendingQueueJobs == 0) {
            Q_EMIT failed(msg);
            return;
        }
    }

    if (m_pendingQueueJobs == 0) {
        addFollowupReminder(qjob->message()->messageID(false)->asUnicodeString());
Laurent Montel's avatar
Laurent Montel committed
1114
        Q_EMIT sentSuccessfully(-1);
1115
1116
1117
    }
}

1118
void ComposerViewBase::fillQueueJobHeaders(MailTransport::MessageQueueJob *qjob, KMime::Message::Ptr message, const MessageComposer::InfoPart *infoPart)
1119
1120
1121
{
    MailTransport::Transport *transport = MailTransport::TransportManager::self()->transportById(infoPart->transportId());
    if (transport && transport->specifySenderOverwriteAddress()) {
Laurent Montel's avatar
Laurent Montel committed
1122
1123
        qjob->addressAttribute().setFrom(
            KEmailAddress::extractEmailAddress(KEmailAddress::normalizeAddressesAndEncodeIdn(transport->senderOverwriteAddress())));
1124
1125
1126
1127
1128
    } else {
        qjob->addressAttribute().setFrom(KEmailAddress::extractEmailAddress(KEmailAddress::normalizeAddressesAndEncodeIdn(infoPart->from())));
    }
    // if this header is not empty, it contains the real recipient of the message, either the primary or one of the
    //  secondary recipients. so we set that to the transport job, while leaving the message itself alone.
Laurent Montel's avatar
Laurent Montel committed
1129
    if (KMime::Headers::Base *realTo = message->headerByType("X-KMail-EncBccRecipients")) {
1130
1131
1132
        qjob->addressAttribute().setTo(cleanEmailList(encodeIdn(realTo->asUnicodeString().split(QLatin1Char('%')))));
        message->removeHeader("X-KMail-EncBccRecipients");
        message->assemble();
Laurent Montel's avatar
Laurent Montel committed
1133
        qCDebug(MESSAGECOMPOSER_LOG) << "sending with-bcc encr mail to a/n recipient:" << qjob->addressAttribute().to();
1134
1135
1136
1137
1138
1139
1140
    } else {
        qjob->addressAttribute().setTo(cleanEmailList(encodeIdn(infoPart->to())));
        qjob->addressAttribute().setCc(cleanEmailList(encodeIdn(infoPart->cc())));
        qjob->addressAttribute().setBcc(cleanEmailList(encodeIdn(infoPart->bcc())));
    }
}

1141
void ComposerViewBase::initAutoSave()
1142
{
1143
    qCDebug(MESSAGECOMPOSER_LOG) << "initialising autosave";
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158

    // Ensure that the autosave directory exists.
    QDir dataDirectory(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/kmail2/"));
    if (!dataDirectory.exists(QStringLiteral("autosave"))) {
        qCDebug(MESSAGECOMPOSER_LOG) << "Creating autosave directory.";
        dataDirectory.mkdir(QStringLiteral("autosave"));
    }

    // Construct a file name
    if (m_autoSaveUUID.isEmpty()) {
        m_autoSaveUUID = QUuid::createUuid().toString();
    }

    updateAutoSave();
}
Laurent Montel's avatar
Laurent Montel committed
1159

1160
Akonadi::Collection ComposerViewBase::followUpCollection() const
1161
1162
1163
1164
{
    return mFollowUpCollection;
}

1165
void ComposerViewBase::setFollowUpCollection(const Akonadi::Collection &followUpCollection)
1166
1167
1168
1169
{
    mFollowUpCollection = followUpCollection;
}

1170
QDate ComposerViewBase::followUpDate() const
1171
1172
1173
1174
{
    return mFollowUpDate;
}

1175
void ComposerViewBase::setFollowUpDate(const QDate &followUpDate)
1176
1177
1178
1179
{
    mFollowUpDate = followUpDate;
}

1180
Sonnet::DictionaryComboBox *ComposerViewBase::dictionary() const
1181
1182
1183
1184
{
    return m_dictionary;
}

1185
void ComposerViewBase::setDictionary(Sonnet::DictionaryComboBox *dictionary)
1186
1187
1188
1189
{
    m_dictionary = dictionary;
}

1190
void ComposerViewBase::updateAutoSave()
1191
1192
1193
{
    if (m_autoSaveInterval == 0) {
        delete m_autoSaveTimer;
Laurent Montel's avatar
Laurent Montel committed
1194
        m_autoSaveTimer = nullptr;
1195
1196
1197
    } else {
        if (!m_autoSaveTimer) {
            m_autoSaveTimer = new QTimer(this);
Laurent Montel's avatar
Laurent Montel committed
1198
            if (m_parentWidget) {
Laurent Montel's avatar
Laurent Montel committed
1199
                connect(m_autoSaveTimer, SIGNAL(timeout()), m_parentWidget, SLOT(autoSaveMessage()));
Laurent Montel's avatar
Laurent Montel committed
1200
            } else {
Laurent Montel's avatar
Laurent Montel committed
1201
                connect(m_autoSaveTimer, &QTimer::timeout, this, &ComposerViewBase::autoSaveMessage);
Laurent Montel's avatar
Laurent Montel committed
1202
            }
1203
1204
1205
1206
1207
        }
        m_autoSaveTimer->start(m_autoSaveInterval);
    }
}

1208
void ComposerViewBase::cleanupAutoSave()
1209
1210
{
    delete m_autoSaveTimer;
Laurent Montel's avatar
Laurent Montel committed
1211
    m_autoSaveTimer = nullptr;
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
    if (!m_autoSaveUUID.isEmpty()) {
        qCDebug(MESSAGECOMPOSER_LOG) << "deleting autosave files" << m_autoSaveUUID;

        // Delete the autosave files
        QDir autoSaveDir(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/kmail2/autosave"));

        // Filter out only this composer window's autosave files
        QStringList autoSaveFilter;
        autoSaveFilter << m_autoSaveUUID + QLatin1String("*");
        autoSaveDir.setNameFilters(autoSaveFilter);

        // Return the files to be removed
1224
        const QStringList autoSaveFiles = autoSaveDir.entryList();
1225
1226
1227
        qCDebug(MESSAGECOMPOSER_LOG) << "There are" << autoSaveFiles.count() << "to be deleted.";

        // Delete each file
1228
        for (const QString &file : autoSaveFiles) {
1229
1230
1231
1232
1233
1234
1235
            autoSaveDir.remove(file);
        }
        m_autoSaveUUID.clear();
    }
}

//-----------------------------------------------------------------------------
1236
void ComposerViewBase::autoSaveMessage()
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
{
    qCDebug(MESSAGECOMPOSER_LOG) << "Autosaving message";

    if (m_autoSaveTimer) {
        m_autoSaveTimer->stop();
    }

    if (!m_composers.isEmpty()) {
        // This may happen if e.g. the autosave timer calls applyChanges.
        qCDebug(MESSAGECOMPOSER_LOG) << "Called while composer active; ignoring.";
        return;
    }

1250
    const KIdentityManagement::Identity &id = m_identMan->identityForUoidOrDefault(m_identityCombo->currentIdentity());
1251
1252
    MessageComposer::Composer *const composer = createSimpleComposer();
    composer->setAutoSave(true);
1253
    composer->setAutocryptEnabled(id.autocryptEnabled());
1254
1255
1256
1257
1258
    m_composers.append(composer);
    connect(composer, &MessageComposer::Composer::result, this, &ComposerViewBase::slotAutoSaveComposeResult);
    composer->start();
}

1259
void ComposerViewBase::setAutoSaveFileName(const QString &fileName)
1260
1261
1262
1263
1264
1265
{
    m_autoSaveUUID = fileName;

    Q_EMIT modified(true);
}

1266
void ComposerViewBase::slotAutoSaveComposeResult(KJob *job)
1267
1268
1269
{
    using MessageComposer::Composer;

Laurent Montel's avatar
Laurent Montel committed
1270
1271
    Q_ASSERT(dynamic_cast<Composer *>(job));
    auto composer = static_cast<Composer *>(job);
1272
1273
1274
1275
1276
1277
1278

    if (composer->error() == Composer::NoError) {
        Q_ASSERT(m_composers.contains(composer));

        // The messages were composed successfully. Only save the first message, there should
        // only be one anyway, since crypto is disabled.
        qCDebug(MESSAGECOMPOSER_LOG) << "NoError.";
Laurent Montel's avatar
Laurent Montel committed
1279
        writeAutoSaveToDisk(composer->resultMessages().constFirst());
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293