File: searchpattern.cpp

package info (click to toggle)
libkf5mailcommon 4%3A20.08.3-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 8,120 kB
  • sloc: cpp: 30,277; xml: 340; ansic: 16; makefile: 15; sh: 3
file content (428 lines) | stat: -rw-r--r-- 11,545 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/*

  Author: Marc Mutz <mutz@kde.org>
  Copyright (C) 2012 Andras Mantia <amantia@kde.org>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

#include "searchpattern.h"
#include "searchrule/searchrulenumerical.h"
#include "searchrule/searchruledate.h"
#include "searchrule/searchrulestring.h"
#include "searchrule/searchrulestatus.h"
#include "filter/filterlog.h"
using MailCommon::FilterLog;
#include "mailcommon_debug.h"
#include <Akonadi/Contact/ContactSearchJob>

#include <SearchQuery>

#include <KMime/KMimeMessage>

#include <KConfigGroup>
#include <KLocalizedString>

#include <QDataStream>

#include <algorithm>
#include <boost/bind.hpp>

using namespace MailCommon;

//==================================================
//
// class SearchPattern
//
//==================================================

SearchPattern::SearchPattern()
    : QList<SearchRule::Ptr>()
{
    init();
}

SearchPattern::SearchPattern(const KConfigGroup &config)
    : QList<SearchRule::Ptr>()
{
    readConfig(config);
}

SearchPattern::~SearchPattern()
{
}

bool SearchPattern::matches(const Akonadi::Item &item, bool ignoreBody) const
{
    if (isEmpty()) {
        return true;
    }
    if (!item.hasPayload<KMime::Message::Ptr>()) {
        return false;
    }

    QList<SearchRule::Ptr>::const_iterator it;
    QList<SearchRule::Ptr>::const_iterator end(constEnd());
    switch (mOperator) {
    case OpAnd: // all rules must match
        for (it = constBegin(); it != end; ++it) {
            if (!((*it)->requiredPart() == SearchRule::CompleteMessage && ignoreBody)) {
                if (!(*it)->matches(item)) {
                    return false;
                }
            }
        }
        return true;

    case OpOr:  // at least one rule must match
        for (it = constBegin(); it != end; ++it) {
            if (!((*it)->requiredPart() == MailCommon::SearchRule::CompleteMessage && ignoreBody)) {
                if ((*it)->matches(item)) {
                    return true;
                }
            }
        }
        return false;

    case OpAll:
        return true;

    default:
        return false;
    }
}

SearchRule::RequiredPart SearchPattern::requiredPart() const
{
    SearchRule::RequiredPart reqPart = SearchRule::Envelope;

    if (!isEmpty()) {
        reqPart = (*std::max_element(constBegin(), constEnd(),
                                     boost::bind(&MailCommon::SearchRule::requiredPart, _1)
                                     < boost::bind(&MailCommon::SearchRule::requiredPart, _2)))->requiredPart();
    }
    return reqPart;
}

QString SearchPattern::purify(bool removeAction)
{
    QString informationAboutNotValidPattern;
    QList<SearchRule::Ptr>::iterator it = end();
    while (it != begin()) {
        --it;
        if ((*it)->isEmpty()) {
            if (removeAction) {
#ifndef NDEBUG
                qCDebug(MAILCOMMON_LOG) << "Removing" << (*it)->asString();
#endif
                if (!informationAboutNotValidPattern.isEmpty()) {
                    informationAboutNotValidPattern += QLatin1Char('\n');
                }
                informationAboutNotValidPattern += (*it)->informationAboutNotValidRules();

                erase(it);
                it = end();
            }
        }
    }

    return informationAboutNotValidPattern;
}

void SearchPattern::readConfig(const KConfigGroup &config)
{
    init();

    mName = config.readEntry("name");
    if (!config.hasKey("rules")) {
        qCDebug(MAILCOMMON_LOG) << "Found legacy config! Converting.";
        importLegacyConfig(config);
        return;
    }

    const QString op = config.readEntry("operator");
    if (op == QLatin1String("or")) {
        mOperator = OpOr;
    } else if (op == QLatin1String("and")) {
        mOperator = OpAnd;
    } else if (op == QLatin1String("all")) {
        mOperator = OpAll;
    }

    const int nRules = config.readEntry("rules", 0);

    for (int i = 0; i < nRules; ++i) {
        SearchRule::Ptr r = SearchRule::createInstanceFromConfig(config, i);
        if (!r->isEmpty()) {
            append(r);
        }
    }
}

void SearchPattern::importLegacyConfig(const KConfigGroup &config)
{
    SearchRule::Ptr rule
        = SearchRule::createInstance(
              config.readEntry("fieldA").toLatin1(),
              config.readEntry("funcA").toLatin1().constData(),
              config.readEntry("contentsA"));

    if (rule->isEmpty()) {
        // if the first rule is invalid,
        // we really can't do much heuristics...
        return;
    }
    append(rule);

    const QString sOperator = config.readEntry("operator");
    if (sOperator == QLatin1String("ignore")) {
        return;
    }

    rule
        = SearchRule::createInstance(
              config.readEntry("fieldB").toLatin1(),
              config.readEntry("funcB").toLatin1().constData(),
              config.readEntry("contentsB"));

    if (rule->isEmpty()) {
        return;
    }
    append(rule);

    if (sOperator == QLatin1String("or")) {
        mOperator = OpOr;
        return;
    }
    // This is the interesting case...
    if (sOperator == QLatin1String("unless")) {     // meaning "and not", ie we need to...
        // ...invert the function (e.g. "equals" <-> "doesn't equal")
        // We simply toggle the last bit (xor with 0x1)... This assumes that
        // SearchRule::Function's come in adjacent pairs of pros and cons
        SearchRule::Function func = last()->function();
        unsigned int intFunc = (unsigned int)func;
        func = SearchRule::Function(intFunc ^ 0x1);

        last()->setFunction(func);
    }

    // treat any other case as "and" (our default).
}

void SearchPattern::writeConfig(KConfigGroup &config) const
{
    config.writeEntry("name", mName);
    switch (mOperator) {
    case OpOr:
        config.writeEntry("operator", "or");
        break;
    case OpAnd:
        config.writeEntry("operator", "and");
        break;
    case OpAll:
        config.writeEntry("operator", "all");
        break;
    }

    int i = 0;
    QList<SearchRule::Ptr>::const_iterator it;
    QList<SearchRule::Ptr>::const_iterator endIt(constEnd());

    if (count() >= filterRulesMaximumSize()) {
        qCDebug(MAILCOMMON_LOG) << "Number of patterns > to filter max rules";
    }
    for (it = constBegin(); it != endIt && i < filterRulesMaximumSize(); ++i, ++it) {
        // we could do this ourselves, but we want the rules to be extensible,
        // so we give the rule it's number and let it do the rest.
        (*it)->writeConfig(config, i);
    }

    // save the total number of rules.
    config.writeEntry("rules", i);
}

int SearchPattern::filterRulesMaximumSize()
{
    return 8;
}

void SearchPattern::init()
{
    clear();
    mOperator = OpAnd;
    mName = QLatin1Char('<') + i18nc("name used for a virgin filter", "unknown") + QLatin1Char('>');
}

QString SearchPattern::asString() const
{
    QString result;
    switch (mOperator) {
    case OpOr:
        result = i18n("(match any of the following)");
        break;
    case OpAnd:
        result = i18n("(match all of the following)");
        break;
    case OpAll:
        result = i18n("(match all messages)");
        break;
    }

    QList<SearchRule::Ptr>::const_iterator it;
    QList<SearchRule::Ptr>::const_iterator endIt = constEnd();
    for (it = constBegin(); it != endIt; ++it) {
        result += QLatin1String("\n\t") + FilterLog::recode((*it)->asString());
    }

    return result;
}

SearchPattern::SparqlQueryError SearchPattern::asAkonadiQuery(Akonadi::SearchQuery &query) const
{
    query = Akonadi::SearchQuery();

    Akonadi::SearchTerm term(Akonadi::SearchTerm::RelAnd);
    if (op() == SearchPattern::OpOr) {
        term = Akonadi::SearchTerm(Akonadi::SearchTerm::RelOr);
    }

    const_iterator end(constEnd());
    bool emptyIsNotAnError = false;
    bool resultAddQuery = false;
    for (const_iterator it = constBegin(); it != end; ++it) {
        (*it)->addQueryTerms(term, emptyIsNotAnError);
        resultAddQuery &= emptyIsNotAnError;
    }

    if (term.subTerms().isEmpty()) {
        if (resultAddQuery) {
            qCDebug(MAILCOMMON_LOG) << " innergroup is Empty. Need to report bug";
            return MissingCheck;
        } else {
            return EmptyResult;
        }
    }
    query.setTerm(term);

    return NoError;
}

const SearchPattern &SearchPattern::operator=(const SearchPattern &other)
{
    if (this == &other) {
        return *this;
    }

    setOp(other.op());
    setName(other.name());

    clear(); // ###
    QList<SearchRule::Ptr>::const_iterator it;
    QList<SearchRule::Ptr>::const_iterator end(other.constEnd());
    for (it = other.constBegin(); it != end; ++it) {
        append(SearchRule::createInstance(**it));     // deep copy
    }

    return *this;
}

QByteArray SearchPattern::serialize() const
{
    QByteArray out;
    QDataStream stream(&out, QIODevice::WriteOnly);
    *this >> stream;
    return out;
}

void SearchPattern::deserialize(const QByteArray &str)
{
    QDataStream stream(str);
    *this << stream;
}

QDataStream &SearchPattern::operator>>(QDataStream &s) const
{
    switch (op()) {
    case SearchPattern::OpAnd:
        s << QStringLiteral("and");
        break;
    case SearchPattern::OpOr:
        s << QStringLiteral("or");
        break;
    case SearchPattern::OpAll:
        s << QStringLiteral("all");
        break;
    }

    for (const SearchRule::Ptr rule : qAsConst(*this)) {
        *rule >> s;
    }
    return s;
}

QDataStream &SearchPattern::operator<<(QDataStream &s)
{
    QString op;
    s >> op;
    if (op == QLatin1String("and")) {
        setOp(OpAnd);
    } else if (op == QLatin1String("or")) {
        setOp(OpOr);
    } else if (op == QLatin1String("all")) {
        setOp(OpAll);
    }

    while (!s.atEnd()) {
        SearchRule::Ptr rule = SearchRule::createInstance(s);
        append(rule);
    }
    return s;
}

void SearchPattern::generateSieveScript(QStringList &requiresModules, QString &code)
{
    code += QLatin1String("\n#") + mName + QLatin1Char('\n');
    switch (mOperator) {
    case OpOr:
        code += QLatin1String("if anyof (");
        break;
    case OpAnd:
        code += QLatin1String("if allof (");
        break;
    case OpAll:
        code += QLatin1String("if (true) {");
        return;
    }

    QList<SearchRule::Ptr>::const_iterator it;
    QList<SearchRule::Ptr>::const_iterator endIt(constEnd());
    int i = 0;
    for (it = constBegin(); it != endIt && i < filterRulesMaximumSize(); ++i, ++it) {
        if (i != 0) {
            code += QLatin1String("\n, ");
        }
        (*it)->generateSieveScript(requiresModules, code);
    }
}

// Needed for MSVC 2010, as it seems to not implicit cast for a pointer anymore
#ifdef _MSC_VER
namespace MailCommon {
uint qHash(SearchRule::Ptr sr)
{
    return ::qHash(sr.get());
}
}
#endif