composerviewbase.cpp 84.7 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

50
51
52
#include <Akonadi/CollectionComboBox>
#include <Akonadi/CollectionFetchJob>
#include <Akonadi/ItemCreateJob>
Laurent Montel's avatar
Laurent Montel committed
53
#include <Akonadi/KMime/MessageFlags>
54
55
#include <Akonadi/KMime/SpecialMailCollections>

Laurent Montel's avatar
Laurent Montel committed
56
#include <KEmailAddress>
57
58
#include <KIdentityManagement/IdentityCombo>
#include <KIdentityManagement/IdentityManager>
59

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
82
using namespace MessageComposer;

ComposerViewBase::ComposerViewBase(QObject *parent, QWidget *parentGui)
83
84
85
86
    : 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
87
    , m_autoSaveInterval(60000) // default of 1 min
88
89
90
91
92
93
{
    m_charsets << "utf-8"; // default, so we have a backup in case client code forgot to set.

    initAutoSave();
}

94
ComposerViewBase::~ComposerViewBase() = default;
95

96
bool ComposerViewBase::isComposing() const
97
98
99
100
{
    return !m_composers.isEmpty();
}

101
void ComposerViewBase::setMessage(const KMime::Message::Ptr &msg, bool allowDecryption)
102
{
Laurent Montel's avatar
Laurent Montel committed
103
    if (m_attachmentModel) {
Laurent Montel's avatar
Laurent Montel committed
104
105
        const auto attachments{m_attachmentModel->attachments()};
        for (const MessageCore::AttachmentPart::Ptr &attachment : attachments) {
Laurent Montel's avatar
Laurent Montel committed
106
107
108
            if (!m_attachmentModel->removeAttachment(attachment)) {
                qCWarning(MESSAGECOMPOSER_LOG) << "Attachment not found.";
            }
109
110
111
112
113
114
115
116
        }
    }
    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);
117
        m_recipientsEditor->setRecipientString(m_msg->replyTo()->mailboxes(), MessageComposer::Recipient::ReplyTo);
118
119
120
        m_recipientsEditor->setFocusBottom();

        // If we are loading from a draft, load unexpanded aliases as well
Laurent Montel's avatar
Laurent Montel committed
121
        if (auto hrd = m_msg->headerByType("X-KMail-UnExpanded-To")) {
122
            const QStringList spl = hrd->asUnicodeString().split(QLatin1Char(','));
123
            for (const QString &addr : spl) {
Laurent Montel's avatar
Laurent Montel committed
124
125
126
                if (!m_recipientsEditor->addRecipient(addr, MessageComposer::Recipient::To)) {
                    qCWarning(MESSAGECOMPOSER_LOG) << "Impossible to add recipient.";
                }
127
128
            }
        }
Laurent Montel's avatar
Laurent Montel committed
129
        if (auto hrd = m_msg->headerByType("X-KMail-UnExpanded-CC")) {
130
            const QStringList spl = hrd->asUnicodeString().split(QLatin1Char(','));
131
            for (const QString &addr : spl) {
Laurent Montel's avatar
Laurent Montel committed
132
133
134
                if (!m_recipientsEditor->addRecipient(addr, MessageComposer::Recipient::Cc)) {
                    qCWarning(MESSAGECOMPOSER_LOG) << "Impossible to add recipient.";
                }
135
136
            }
        }
Laurent Montel's avatar
Laurent Montel committed
137
        if (auto hrd = m_msg->headerByType("X-KMail-UnExpanded-BCC")) {
138
            const QStringList spl = hrd->asUnicodeString().split(QLatin1Char(','));
139
            for (const QString &addr : spl) {
Laurent Montel's avatar
Laurent Montel committed
140
141
142
                if (!m_recipientsEditor->addRecipient(addr, MessageComposer::Recipient::Bcc)) {
                    qCWarning(MESSAGECOMPOSER_LOG) << "Impossible to add recipient.";
                }
143
144
            }
        }
145
146
147
148
149
150
151
152
        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.";
                }
            }
        }
153
154
155
156
157
    }

    // 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
158
    auto msgContent = new KMime::Content;
159
160
    msgContent->setContent(m_msg->encodedContent());
    msgContent->parse();
161
    MimeTreeParser::SimpleObjectTreeSource emptySource;
Laurent Montel's avatar
Laurent Montel committed
162
    MimeTreeParser::ObjectTreeParser otp(&emptySource); // All default are ok
163
    emptySource.setDecryptMessage(allowDecryption);
164
165
166
    otp.parseObjectTree(msgContent);

    // Load the attachments
Laurent Montel's avatar
Laurent Montel committed
167
168
    const auto attachmentsOfExtraContents{otp.nodeHelper()->attachmentsOfExtraContents()};
    for (const auto &att : attachmentsOfExtraContents) {
169
170
        addAttachmentPart(att);
    }
Laurent Montel's avatar
Laurent Montel committed
171
172
    const auto attachments{msgContent->attachments()};
    for (const auto &att : attachments) {
173
174
175
176
177
178
179
180
181
182
183
        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
184
185
186
            if (!m_transport->setCurrentTransport(transport->id())) {
                qCWarning(MESSAGECOMPOSER_LOG) << "Impossible to find transport id" << transport->id();
            }
187
188
189
190
        }
    }

    // Set the HTML text and collect HTML images
191
    QString htmlContent = otp.htmlContent();
Laurent Montel's avatar
Laurent Montel committed
192
193
194
    if (htmlContent.isEmpty()) {
        m_editor->setPlainText(otp.plainTextContent());
    } else {
Laurent Montel's avatar
Laurent Montel committed
195
        // Bug 372085 <div id="name"> is replaced in qtextedit by <a id="name">... => break url
196
        htmlContent.replace(QRegularExpression(QStringLiteral("<div\\s*id=\".*\">")), QStringLiteral("<div>"));
Laurent Montel's avatar
Laurent Montel committed
197
        m_editor->setHtml(htmlContent);
198
199
200
201
202
        Q_EMIT enableHtml();
        collectImages(m_msg.data());
    }

    if (auto hdr = m_msg->headerByType("X-KMail-CursorPos")) {
Laurent Montel's avatar
Laurent Montel committed
203
        m_editor->setCursorPositionFromStart(hdr->asUnicodeString().toUInt());
204
205
206
207
    }
    delete msgContent;
}

208
void ComposerViewBase::updateTemplate(const KMime::Message::Ptr &msg)
209
210
211
212
{
    // 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
213
    auto msgContent = new KMime::Content;
214
215
    msgContent->setContent(msg->encodedContent());
    msgContent->parse();
216
    MimeTreeParser::SimpleObjectTreeSource emptySource;
Laurent Montel's avatar
Laurent Montel committed
217
    MimeTreeParser::ObjectTreeParser otp(&emptySource); // All default are ok
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
    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;
}

234
void ComposerViewBase::saveMailSettings()
235
236
237
238
239
240
{
    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);

241
242
243
244
    header = new KMime::Headers::Generic("X-KMail-Transport-Name");
    header->fromUnicodeString(m_transport->currentText(), "utf-8");
    m_msg->setHeader(header);

245
246
247
    header = new KMime::Headers::Generic("X-KMail-Fcc");
    header->fromUnicodeString(QString::number(m_fccCollection.id()), "utf-8");
    m_msg->setHeader(header);
248

249
250
251
    header = new KMime::Headers::Generic("X-KMail-Identity");
    header->fromUnicodeString(QString::number(identity.uoid()), "utf-8");
    m_msg->setHeader(header);
252
253
254
255
256

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

257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
    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";
    }
}

282
void ComposerViewBase::clearFollowUp()
283
284
285
286
287
{
    mFollowUpDate = QDate();
    mFollowUpCollection = Akonadi::Collection();
}

288
void ComposerViewBase::send(MessageComposer::MessageSender::SendMethod method, MessageComposer::MessageSender::SaveIn saveIn, bool checkMailDispatcher)
289
290
291
292
{
    mSendMethod = method;
    mSaveIn = saveIn;

293
    KCursorSaver saver(Qt::WaitCursor);
294
295
296
297
298
299
300
301
302
303
304
    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
305
306
307
        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)");
308
        int ret = KMessageBox::warningYesNoCancel(m_parentWidget,
Laurent Montel's avatar
Laurent Montel committed
309
310
311
312
313
                                                  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));
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
        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
341
    if (mSendMethod == MessageComposer::MessageSender::SendImmediate && checkMailDispatcher) {
Laurent Montel's avatar
Laurent Montel committed
342
343
344
345
        if (!MessageComposer::Util::sendMailDispatcherIsOnline(m_parentWidget)) {
            qCWarning(MESSAGECOMPOSER_LOG) << "Impossible to set sendmaildispatcher online. Please verify it";
            return;
        }
346
347
348
349
350
    }

    readyForSending();
}

351
void ComposerViewBase::setCustomHeader(const QMap<QByteArray, QString> &customHeader)
352
353
354
355
{
    m_customHeader = customHeader;
}

356
void ComposerViewBase::readyForSending()
357
358
359
360
361
362
363
364
365
{
    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.
Laurent Montel's avatar
Laurent Montel committed
366
        qCDebug(MESSAGECOMPOSER_LOG) << "ready for sending: Called while composer active; ignoring. Number of composer " << m_composers.count();
367
368
369
370
        return;
    }

    // first, expand all addresses
Laurent Montel's avatar
Laurent Montel committed
371
    auto job = new MessageComposer::EmailAddressResolveJob(this);
372
373
374
375
376
377
378
379
    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
380
    job->setReplyTo(m_recipientsEditor->recipientStringList(MessageComposer::Recipient::ReplyTo));
381

382
383
384
385
    connect(job, &MessageComposer::EmailAddressResolveJob::result, this, &ComposerViewBase::slotEmailAddressResolved);
    job->start();
}

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

Laurent Montel's avatar
Laurent Montel committed
478
479
480
481
    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
482
483
484
    // 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
485
    if (m_neverEncrypt && mSaveIn != MessageComposer::MessageSender::SaveInNone && !mSendLaterInfo) {
Laurent Montel's avatar
Laurent Montel committed
486
        auto composer = new MessageComposer::Composer;
487
488
489
        composer->setNoCrypto(true);
        m_composers.append(composer);
    } else {
490
        bool wasCanceled = false;
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
        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
507
508
509
510
511
                    const int rc = KMessageBox::warningYesNo(m_parentWidget,
                                                             i18n("Do you want to resize images?"),
                                                             i18n("Auto Resize Images"),
                                                             KStandardGuiItem::yes(),
                                                             KStandardGuiItem::no());
512
513
514
515
516
517
518
519
520
521
522
523
                    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
524

525
526
527
    // working copy in case composers instantly emit result
    const auto composers = m_composers;
    for (MessageComposer::Composer *composer : composers) {
528
529
530
531
532
533
534
535
536
537
538
539
540
541
        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
542
543
namespace
{
544
545
546
547
// helper methods for reading encryption settings

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

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

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

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

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

inline int signingChainCertNearExpiryWarningThresholdInDays()
{
Laurent Montel's avatar
Laurent Montel committed
593
    if (!MessageComposer::MessageComposerSettings::self()->cryptoWarnWhenNearExpire()) {
594
595
        return -1;
    }
Laurent Montel's avatar
Laurent Montel committed
596
    const int num = MessageComposer::MessageComposerSettings::self()->cryptoWarnSignChaincertNearExpiryThresholdDays();
597
598
599
600
601
602
603
604
605
606
607
608
609
610
    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
611
612
613
bool ComposerViewBase::addKeysToContext(const QString &gnupgHome,
                                        const QVector<QPair<QStringList, std::vector<GpgME::Key>>> &data,
                                        const std::map<QByteArray, QString> &autocryptMap)
614
615
616
{
    bool needSpecialContext = false;

Sandro Knauß's avatar
Sandro Knauß committed
617
    for (const auto &p : data) {
Laurent Montel's avatar
Laurent Montel committed
618
        for (const auto &k : p.second) {
619
620
621
622
623
624
625
626
627
628
629
            const auto it = autocryptMap.find(k.primaryFingerprint());
            if (it != autocryptMap.end()) {
                needSpecialContext = true;
                break;
            }
        }
        if (needSpecialContext) {
            break;
        }
    }

Laurent Montel's avatar
Laurent Montel committed
630
    // qDebug() << "addKeysToContext: " << needSpecialContext;
631
632
633
634
635
636
637
638
639

    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
640
    for (const auto &p : data) {
Laurent Montel's avatar
Laurent Montel committed
641
        for (const auto &k : p.second) {
642
643
            const auto it = autocryptMap.find(k.primaryFingerprint());
            if (it == autocryptMap.end()) {
Laurent Montel's avatar
Laurent Montel committed
644
                qCDebug(MESSAGECOMPOSER_LOG) << "Adding " << k.primaryFingerprint() << "via Export/Import";
645
                auto exportJob = proto->publicKeyExportJob(false);
Sandro Knauß's avatar
Sandro Knauß committed
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
                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();
666
667
668
669
670
671
672
673
674
675
676
677
678
                            --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 {
Laurent Montel's avatar
Laurent Montel committed
679
                qCDebug(MESSAGECOMPOSER_LOG) << "Adding " << k.primaryFingerprint() << "from Autocrypt storage";
680
681
682
683
                const auto recipient = storage->getRecipient(it->second.toUtf8());
                auto key = recipient->gpgKey();
                auto keydata = recipient->gpgKeydata();
                if (QByteArray(key.primaryFingerprint()) != QByteArray(k.primaryFingerprint())) {
Laurent Montel's avatar
Laurent Montel committed
684
                    qCDebug(MESSAGECOMPOSER_LOG) << "Using gossipkey";
685
686
687
688
689
690
691
692
693
694
695
696
697
                    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
698
QVector<MessageComposer::Composer *> ComposerViewBase::generateCryptoMessages(bool &wasCanceled)
699
{
700
    const KIdentityManagement::Identity &id = m_identMan->identityForUoidOrDefault(m_identityCombo->currentIdentity());
701
702

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

714
715
    keyResolver->setAutocryptEnabled(id.autocryptEnabled());

716
717
718
719
720
721
722
723
    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
724
    // Add encryptionkeys from id to keyResolver
725
726
727
728
729
730
731
732
733
    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
734
        return QVector<MessageComposer::Composer *>();
735
736
    }

Laurent Montel's avatar
Laurent Montel committed
737
    // Add signingkeys from id to keyResolver
738
739
740
741
742
743
744
745
    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
746
        return QVector<MessageComposer::Composer *>();
747
748
749
    }

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

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

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

    bool result = true;
    bool canceled = false;
Laurent Montel's avatar
Laurent Montel committed
773
    signSomething = determineWhetherToSign(doSignCompletely, keyResolver.data(), signSomething, result, canceled);
774
775
776
777
778
779
780
781
782
    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
783
        return QVector<MessageComposer::Composer *>();
784
785
786
    }

    canceled = false;
Laurent Montel's avatar
Laurent Montel committed
787
    encryptSomething = determineWhetherToEncrypt(doEncryptCompletely, keyResolver.data(), encryptSomething, signSomething, result, canceled);
788
789
790
791
792
793
794
795
796
797
    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
798
        return QVector<MessageComposer::Composer *>();
799
800
    }

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

    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
809
        return QVector<MessageComposer::Composer *>();
810
811
812
813
    } 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
814
        return QVector<MessageComposer::Composer *>();
815
816
817
    }
    qCDebug(MESSAGECOMPOSER_LOG) << "done resolving keys:";

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

    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
832
            auto composer = new MessageComposer::Composer;
833
834
835
836

            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
837
                auto end(encData.end());
Laurent Montel's avatar
Laurent Montel committed
838
                QVector<QPair<QStringList, std::vector<GpgME::Key>>> data;
839
840
                data.reserve(encData.size());
                for (it = encData.begin(); it != end; ++it) {
Laurent Montel's avatar
Laurent Montel committed
841
                    QPair<QStringList, std::vector<GpgME::Key>> p(it->recipients, it->keys);
842
843
844
845
                    data.append(p);
                    qCDebug(MESSAGECOMPOSER_LOG) << "got resolved keys for:" << it->recipients;
                }
                composer->setEncryptionKeys(data);
846
847
848
849
850
851
852
853
854
855
                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());
                    }
                }
856
857
858
859
860
861
862
863
864
865
866
867
868
869
            }

            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
870
        auto composer = new MessageComposer::Composer;
871
        composers.append(composer);
Laurent Montel's avatar
Laurent Montel committed
872
        // If we canceled sign or encrypt be sure to change status in attachment.
873
        markAllAttachmentsForSigning(false);
Laurent Montel's avatar
Laurent Montel committed
874
        markAllAttachmentsForEncryption(false);
875
876
877
878
879
880
881
882
883
    }

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

    return composers;
}

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

892
void ComposerViewBase::fillInfoPart(MessageComposer::InfoPart *infoPart, ComposerViewBase::RecipientExpansion expansion)
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
{
    // 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);
911
        infoPart->setReplyTo(mExpandedReplyTo);
912
913
914
915
916
    } 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));
917
        infoPart->setReplyTo(m_recipientsEditor->recipientStringList(MessageComposer::Recipient::ReplyTo));
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
    }
    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;
    }
950
951
952
    if (auto hdr = m_msg->headerByType("X-KMail-UnExpanded-Reply-To")) {
        extras << hdr;
    }
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
    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;
    }
983
984
985
986
    if (auto hdr = m_msg->headerByType("X-KMail-Identity-Name")) {
        extras << hdr;
    }
    if (auto hdr = m_msg->headerByType("X-KMail-Transport-Name")) {
987
988
989
990
991
992
        extras << hdr;
    }

    infoPart->setExtraHeaders(extras);
}

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

    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
1020
        qCDebug(MESSAGECOMPOSER_LOG) << "other Error." << composer->error();
1021
1022
1023
1024
1025
1026
1027
1028
1029
        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);
    }

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

1035
1036
1037
    m_composers.removeAll(composer);
}

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

1055
void ComposerViewBase::queueMessage(const KMime::Message::Ptr &message, MessageComposer::Composer *composer)
1056
1057
{
    const MessageComposer::InfoPart *infoPart = composer->infoPart();
Laurent Montel's avatar
Laurent Montel committed
1058
    auto qjob = new MailTransport::MessageQueueJob(this);
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
    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
1073
        qjob->sentBehaviourAttribute().setSentBehaviour(MailTransport::SentBehaviourAttribute::MoveToDefaultSentCollection);
1074
1075
    }

1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
    MailTransport::Transport *transport = MailTransport::TransportManager::self()->transportById(infoPart->transportId());
    if (transport && transport->specifySenderOverwriteAddress()) {
        qjob->addressAttribute().setFrom(
            KEmailAddress::extractEmailAddress(KEmailAddress::normalizeAddressesAndEncodeIdn(transport->senderOverwriteAddress())));
    } 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.
    if (KMime::Headers::Base *realTo = message->headerByType("X-KMail-EncBccRecipients")) {
        qjob->addressAttribute().setTo(MessageComposer::Util::cleanUpEmailListAndEncoding(realTo->asUnicodeString().split(QLatin1Char('%'))));
        message->removeHeader("X-KMail-EncBccRecipients");
        message->assemble();
        qCDebug(MESSAGECOMPOSER_LOG) << "sending with-bcc encr mail to a/n recipient:" << qjob->addressAttribute().to();
    } else {
        qjob->addressAttribute().setTo(MessageComposer::Util::cleanUpEmailListAndEncoding(infoPart->to()));
        qjob->addressAttribute().setCc(MessageComposer::Util::cleanUpEmailListAndEncoding(infoPart->cc()));
        qjob->addressAttribute().setBcc(MessageComposer::Util::cleanUpEmailListAndEncoding(infoPart->bcc()));
    }
Laurent Montel's avatar
Laurent Montel committed
1095
1096
1097
    if (m_requestDeleveryConfirmation) {
        qjob->addressAttribute().setDeliveryStatusNotification(true);
    }
1098
    MessageComposer::Util::addSendReplyForwardAction(message, qjob);
1099
1100
    MessageCore::StringUtil::removePrivateHeaderFields(message, false);

1101
    MessageComposer::Util::addCustomHeaders(message, m_customHeader);
1102
1103
1104
1105
1106
1107
1108
1109
    message->assemble();
    connect(qjob, &MailTransport::MessageQueueJob::result, this, &ComposerViewBase::slotQueueResult);
    m_pendingQueueJobs++;
    qjob->start();

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

1110
void ComposerViewBase::slotQueueResult(KJob *job)
1111
1112
{
    m_pendingQueueJobs--;
Laurent Montel's avatar
Laurent Montel committed
1113
    auto qjob = static_cast<MailTransport::MessageQueueJob *>(job);
1114
1115
1116
1117
1118
1119
1120
1121
    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
1122
        QString msg = i18n("There were problems trying to queue the message for sending: %1", job->errorString());
1123
1124
1125
1126
1127
1128
1129
1130
1131

        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
1132
        Q_EMIT sentSuccessfully(-1);
1133
1134
1135
    }
}

1136
void ComposerViewBase::initAutoSave()
1137
{
1138
    qCDebug(MESSAGECOMPOSER_LOG) << "initialising autosave";
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153

    // 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
1154

1155
Akonadi::Collection ComposerViewBase::followUpCollection() const
1156
1157
1158
1159
{
    return mFollowUpCollection;
}

1160
void ComposerViewBase::setFollowUpCollection(const Akonadi::Collection &followUpCollection)
1161
1162
1163
1164
{
    mFollowUpCollection = followUpCollection;
}

1165
QDate ComposerViewBase::followUpDate() const
1166
1167
1168
1169
{
    return mFollowUpDate;
}

1170
void ComposerViewBase::setFollowUpDate(const QDate &followUpDate)
1171
1172
1173
1174
{
    mFollowUpDate = followUpDate;
}

1175
Sonnet::DictionaryComboBox *ComposerViewBase::dictionary() const
1176
1177
1178
1179
{
    return m_dictionary;
}

1180
void ComposerViewBase::setDictionary(Sonnet::DictionaryComboBox *dictionary)
1181
1182
1183
1184
{
    m_dictionary = dictionary;
}

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

1203
void ComposerViewBase::cleanupAutoSave()
1204
1205
{
    delete m_autoSaveTimer;
Laurent Montel's avatar
Laurent Montel committed
1206
    m_autoSaveTimer = nullptr;
1207
1208
1209
1210
1211
1212
1213
    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
Laurent Montel's avatar
Laurent Montel committed
1214
        const QStringList autoSaveFilter{m_autoSaveUUID + QLatin1String("*")};
1215
1216
1217
        autoSaveDir.setNameFilters(autoSaveFilter);

        // Return the files to be removed
1218
        const QStringList autoSaveFiles = autoSaveDir.entryList();
1219
1220
1221
        qCDebug(MESSAGECOMPOSER_LOG) << "There are" << autoSaveFiles.count() << "to be deleted.";

        // Delete each file
1222
        for (const QString &file : autoSaveFiles) {
1223
1224
1225
1226
1227
1228
1229
            autoSaveDir.remove(file);
        }
        m_autoSaveUUID.clear();
    }
}

//-----------------------------------------------------------------------------