Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Entry.cpp « core « src - github.com/keepassxreboot/keepassxc.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ad7ecce2bbf631d340ef8890d3521590ec0c8f39 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
/*
 *  Copyright (C) 2010 Felix Geyer <debfx@fobos.de>
 *  Copyright (C) 2017 KeePassXC Team <team@keepassxc.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 or (at your option)
 *  version 3 of the License.
 *
 *  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, see <http://www.gnu.org/licenses/>.
 */

#include "Entry.h"

#include "core/Config.h"
#include "core/Database.h"
#include "core/Group.h"
#include "core/Metadata.h"
#include "core/PasswordHealth.h"
#include "core/Tools.h"
#include "totp/totp.h"

#include <QDir>
#include <QRegularExpression>
#include <QUrl>

const int Entry::DefaultIconNumber = 0;
const int Entry::ResolveMaximumDepth = 10;
const QString Entry::AutoTypeSequenceUsername = "{USERNAME}{ENTER}";
const QString Entry::AutoTypeSequencePassword = "{PASSWORD}{ENTER}";

Entry::Entry()
    : m_attributes(new EntryAttributes(this))
    , m_attachments(new EntryAttachments(this))
    , m_autoTypeAssociations(new AutoTypeAssociations(this))
    , m_customData(new CustomData(this))
    , m_modifiedSinceBegin(false)
    , m_updateTimeinfo(true)
{
    m_data.iconNumber = DefaultIconNumber;
    m_data.autoTypeEnabled = true;
    m_data.autoTypeObfuscation = 0;
    m_data.excludeFromReports = false;

    connect(m_attributes, &EntryAttributes::modified, this, &Entry::updateTotp);
    connect(m_attributes, &EntryAttributes::modified, this, &Entry::modified);
    connect(m_attributes, &EntryAttributes::defaultKeyModified, this, &Entry::emitDataChanged);
    connect(m_attachments, &EntryAttachments::modified, this, &Entry::modified);
    connect(m_autoTypeAssociations, &AutoTypeAssociations::modified, this, &Entry::modified);
    connect(m_customData, &CustomData::modified, this, &Entry::modified);

    connect(this, &Entry::modified, this, &Entry::updateTimeinfo);
    connect(this, &Entry::modified, this, &Entry::updateModifiedSinceBegin);
}

Entry::~Entry()
{
    setUpdateTimeinfo(false);
    if (m_group) {
        m_group->removeEntry(this);

        if (m_group->database()) {
            m_group->database()->addDeletedObject(m_uuid);
        }
    }

    qDeleteAll(m_history);
}

template <class T> inline bool Entry::set(T& property, const T& value)
{
    if (property != value) {
        property = value;
        emitModified();
        return true;
    }
    return false;
}

void Entry::updateTimeinfo()
{
    if (m_updateTimeinfo) {
        m_data.timeInfo.setLastModificationTime(Clock::currentDateTimeUtc());
        m_data.timeInfo.setLastAccessTime(Clock::currentDateTimeUtc());
    }
}

bool Entry::canUpdateTimeinfo() const
{
    return m_updateTimeinfo;
}

void Entry::setUpdateTimeinfo(bool value)
{
    m_updateTimeinfo = value;
}

QString Entry::buildReference(const QUuid& uuid, const QString& field)
{
    Q_ASSERT(EntryAttributes::DefaultAttributes.count(field) > 0);

    QString uuidStr = Tools::uuidToHex(uuid).toUpper();
    QString shortField;

    if (field == EntryAttributes::TitleKey) {
        shortField = "T";
    } else if (field == EntryAttributes::UserNameKey) {
        shortField = "U";
    } else if (field == EntryAttributes::PasswordKey) {
        shortField = "P";
    } else if (field == EntryAttributes::URLKey) {
        shortField = "A";
    } else if (field == EntryAttributes::NotesKey) {
        shortField = "N";
    }

    if (shortField.isEmpty()) {
        return {};
    }

    return QString("{REF:%1@I:%2}").arg(shortField, uuidStr);
}

EntryReferenceType Entry::referenceType(const QString& referenceStr)
{
    const QString referenceLowerStr = referenceStr.toLower();
    EntryReferenceType result = EntryReferenceType::Unknown;
    if (referenceLowerStr == QLatin1String("t")) {
        result = EntryReferenceType::Title;
    } else if (referenceLowerStr == QLatin1String("u")) {
        result = EntryReferenceType::UserName;
    } else if (referenceLowerStr == QLatin1String("p")) {
        result = EntryReferenceType::Password;
    } else if (referenceLowerStr == QLatin1String("a")) {
        result = EntryReferenceType::Url;
    } else if (referenceLowerStr == QLatin1String("n")) {
        result = EntryReferenceType::Notes;
    } else if (referenceLowerStr == QLatin1String("i")) {
        result = EntryReferenceType::QUuid;
    } else if (referenceLowerStr == QLatin1String("o")) {
        result = EntryReferenceType::CustomAttributes;
    }

    return result;
}

const QUuid& Entry::uuid() const
{
    return m_uuid;
}

const QString Entry::uuidToHex() const
{
    return Tools::uuidToHex(m_uuid);
}

int Entry::iconNumber() const
{
    return m_data.iconNumber;
}

const QUuid& Entry::iconUuid() const
{
    return m_data.customIcon;
}

QString Entry::foregroundColor() const
{
    return m_data.foregroundColor;
}

QString Entry::backgroundColor() const
{
    return m_data.backgroundColor;
}

QString Entry::overrideUrl() const
{
    return m_data.overrideUrl;
}

QString Entry::tags() const
{
    return m_data.tags.join(",");
}

QStringList Entry::tagList() const
{
    return m_data.tags;
}

const TimeInfo& Entry::timeInfo() const
{
    return m_data.timeInfo;
}

bool Entry::autoTypeEnabled() const
{
    return m_data.autoTypeEnabled;
}

int Entry::autoTypeObfuscation() const
{
    return m_data.autoTypeObfuscation;
}

QString Entry::defaultAutoTypeSequence() const
{
    return m_data.defaultAutoTypeSequence;
}

const QSharedPointer<PasswordHealth> Entry::passwordHealth()
{
    if (!m_data.passwordHealth) {
        m_data.passwordHealth.reset(new PasswordHealth(resolvePlaceholder(password())));
    }
    return m_data.passwordHealth;
}

const QSharedPointer<PasswordHealth> Entry::passwordHealth() const
{
    if (!m_data.passwordHealth) {
        return QSharedPointer<PasswordHealth>::create(resolvePlaceholder(password()));
    }
    return m_data.passwordHealth;
}

bool Entry::excludeFromReports() const
{
    return m_data.excludeFromReports
           || (customData()->contains(CustomData::ExcludeFromReportsLegacy)
               && customData()->value(CustomData::ExcludeFromReportsLegacy) == TRUE_STR);
}

void Entry::setExcludeFromReports(bool state)
{
    set(m_data.excludeFromReports, state);
}

/**
 * Determine the effective sequence that will be injected
 * This function return an empty string if a parent group has autotype disabled or if the entry has no parent
 */
QString Entry::effectiveAutoTypeSequence() const
{
    if (!autoTypeEnabled()) {
        return {};
    }

    const Group* parent = group();
    if (!parent) {
        return {};
    }

    QString sequence = parent->effectiveAutoTypeSequence();
    if (sequence.isEmpty()) {
        return {};
    }

    if (!m_data.defaultAutoTypeSequence.isEmpty()) {
        return m_data.defaultAutoTypeSequence;
    }

    if (sequence == Group::RootAutoTypeSequence && (!username().isEmpty() || !password().isEmpty())) {
        if (username().isEmpty()) {
            return AutoTypeSequencePassword;
        } else if (password().isEmpty()) {
            return AutoTypeSequenceUsername;
        }
        return Group::RootAutoTypeSequence;
    }

    return sequence;
}

/**
 * Retrieve the Auto-Type sequences matches for a given windowTitle
 * This returns a list with priority ordering. If you don't want duplicates call .toSet() on it.
 */
QList<QString> Entry::autoTypeSequences(const QString& windowTitle) const
{
    // If no window just return the effective sequence
    if (windowTitle.isEmpty()) {
        return {effectiveAutoTypeSequence()};
    }

    // Define helper functions to match window titles
    auto windowMatches = [&](const QString& pattern) {
        // Regex searching
        if (pattern.startsWith("//") && pattern.endsWith("//") && pattern.size() >= 4) {
            QRegularExpression regExp(pattern.mid(2, pattern.size() - 4), QRegularExpression::CaseInsensitiveOption);
            return regExp.match(windowTitle).hasMatch();
        }

        // Wildcard searching
        const auto regExp = Tools::convertToRegex(
            pattern, Tools::RegexConvertOpts::EXACT_MATCH | Tools::RegexConvertOpts::WILDCARD_UNLIMITED_MATCH);
        return regExp.match(windowTitle).hasMatch();
    };

    auto windowMatchesTitle = [&](const QString& entryTitle) {
        return !entryTitle.isEmpty() && windowTitle.contains(entryTitle, Qt::CaseInsensitive);
    };

    auto windowMatchesUrl = [&](const QString& entryUrl) {
        if (!entryUrl.isEmpty() && windowTitle.contains(entryUrl, Qt::CaseInsensitive)) {
            return true;
        }

        QUrl url(entryUrl);
        if (url.isValid() && !url.host().isEmpty()) {
            return windowTitle.contains(url.host(), Qt::CaseInsensitive);
        }

        return false;
    };

    QList<QString> sequenceList;

    // Add window association matches
    const auto assocList = autoTypeAssociations()->getAll();
    for (const auto& assoc : assocList) {
        auto window = resolveMultiplePlaceholders(assoc.window);
        if (!assoc.window.isEmpty() && windowMatches(window)) {
            if (!assoc.sequence.isEmpty()) {
                sequenceList << assoc.sequence;
            } else {
                sequenceList << effectiveAutoTypeSequence();
            }
        }
    }

    // Try to match window title
    if (config()->get(Config::AutoTypeEntryTitleMatch).toBool() && windowMatchesTitle(resolvePlaceholder(title()))) {
        sequenceList << effectiveAutoTypeSequence();
    }

    // Try to match url in window title
    if (config()->get(Config::AutoTypeEntryURLMatch).toBool() && windowMatchesUrl(resolvePlaceholder(url()))) {
        sequenceList << effectiveAutoTypeSequence();
    }

    return sequenceList;
}

AutoTypeAssociations* Entry::autoTypeAssociations()
{
    return m_autoTypeAssociations;
}

const AutoTypeAssociations* Entry::autoTypeAssociations() const
{
    return m_autoTypeAssociations;
}

QString Entry::title() const
{
    return m_attributes->value(EntryAttributes::TitleKey);
}

QString Entry::url() const
{
    return m_attributes->value(EntryAttributes::URLKey);
}

QStringList Entry::getAllUrls() const
{
    QStringList urlList;

    if (!url().isEmpty()) {
        urlList << url();
    }

    for (const auto& key : m_attributes->keys()) {
        if (key.startsWith("KP2A_URL")) {
            auto additionalUrl = m_attributes->value(key);
            if (!additionalUrl.isEmpty()) {
                urlList << additionalUrl;
            }
        }
    }

    return urlList;
}

QString Entry::webUrl() const
{
    QString url = resolveMultiplePlaceholders(m_attributes->value(EntryAttributes::URLKey));
    return resolveUrl(url);
}

QString Entry::displayUrl() const
{
    QString url = maskPasswordPlaceholders(m_attributes->value(EntryAttributes::URLKey));
    return resolveMultiplePlaceholders(url);
}

QString Entry::username() const
{
    return m_attributes->value(EntryAttributes::UserNameKey);
}

QString Entry::password() const
{
    return m_attributes->value(EntryAttributes::PasswordKey);
}

QString Entry::notes() const
{
    return m_attributes->value(EntryAttributes::NotesKey);
}

QString Entry::attribute(const QString& key) const
{
    return m_attributes->value(key);
}

int Entry::size() const
{
    int size = 0;
    const QRegularExpression delimiter(",|:|;");

    size += this->attributes()->attributesSize();
    size += this->autoTypeAssociations()->associationsSize();
    size += this->attachments()->attachmentsSize();
    size += this->customData()->dataSize();
    const QStringList tags = this->tags().split(delimiter, QString::SkipEmptyParts);
    for (const QString& tag : tags) {
        size += tag.toUtf8().size();
    }

    return size;
}

bool Entry::isExpired() const
{
    return willExpireInDays(0);
}

bool Entry::willExpireInDays(int days) const
{
    return m_data.timeInfo.expires() && m_data.timeInfo.expiryTime() < Clock::currentDateTime().addDays(days);
}

bool Entry::isRecycled() const
{
    const Database* db = database();
    if (!db) {
        return false;
    }

    return m_group == db->metadata()->recycleBin() || m_group->isRecycled();
}

bool Entry::isAttributeReference(const QString& key) const
{
    return m_attributes->isReference(key);
}

bool Entry::isAttributeReferenceOf(const QString& key, const QUuid& uuid) const
{
    if (!m_attributes->isReference(key)) {
        return false;
    }

    return m_attributes->value(key).contains(Tools::uuidToHex(uuid), Qt::CaseInsensitive);
}

bool Entry::hasReferences() const
{
    const QList<QString> keyList = EntryAttributes::DefaultAttributes;
    for (const QString& key : keyList) {
        if (m_attributes->isReference(key)) {
            return true;
        }
    }
    return false;
}

bool Entry::hasReferencesTo(const QUuid& uuid) const
{
    const QList<QString> keyList = EntryAttributes::DefaultAttributes;
    for (const QString& key : keyList) {
        if (isAttributeReferenceOf(key, uuid)) {
            return true;
        }
    }
    return false;
}

void Entry::replaceReferencesWithValues(const Entry* other)
{
    for (const QString& key : EntryAttributes::DefaultAttributes) {
        if (isAttributeReferenceOf(key, other->uuid())) {
            setDefaultAttribute(key, other->attribute(key));
        }
    }
}

EntryAttributes* Entry::attributes()
{
    return m_attributes;
}

const EntryAttributes* Entry::attributes() const
{
    return m_attributes;
}

EntryAttachments* Entry::attachments()
{
    return m_attachments;
}

const EntryAttachments* Entry::attachments() const
{
    return m_attachments;
}

CustomData* Entry::customData()
{
    return m_customData;
}

const CustomData* Entry::customData() const
{
    return m_customData;
}

bool Entry::hasTotp() const
{
    return !m_data.totpSettings.isNull();
}

QString Entry::totp() const
{
    if (hasTotp()) {
        return Totp::generateTotp(m_data.totpSettings);
    }
    return {};
}

void Entry::setTotp(QSharedPointer<Totp::Settings> settings)
{
    beginUpdate();
    m_attributes->remove(Totp::ATTRIBUTE_OTP);
    m_attributes->remove(Totp::ATTRIBUTE_SEED);
    m_attributes->remove(Totp::ATTRIBUTE_SETTINGS);

    if (settings->key.isEmpty()) {
        m_data.totpSettings.reset();
    } else {
        m_data.totpSettings = std::move(settings);
        auto text = Totp::writeSettings(
            m_data.totpSettings, resolveMultiplePlaceholders(title()), resolveMultiplePlaceholders(username()));
        if (m_data.totpSettings->format != Totp::StorageFormat::LEGACY) {
            m_attributes->set(Totp::ATTRIBUTE_OTP, text, true);
        } else {
            m_attributes->set(Totp::ATTRIBUTE_SEED, m_data.totpSettings->key, true);
            m_attributes->set(Totp::ATTRIBUTE_SETTINGS, text);
        }
    }
    endUpdate();
}

void Entry::updateTotp()
{
    if (m_attributes->contains(Totp::ATTRIBUTE_SETTINGS)) {
        m_data.totpSettings = Totp::parseSettings(m_attributes->value(Totp::ATTRIBUTE_SETTINGS),
                                                  m_attributes->value(Totp::ATTRIBUTE_SEED));
    } else if (m_attributes->contains(Totp::ATTRIBUTE_OTP)) {
        m_data.totpSettings = Totp::parseSettings(m_attributes->value(Totp::ATTRIBUTE_OTP));
    } else {
        m_data.totpSettings.reset();
    }
}

QSharedPointer<Totp::Settings> Entry::totpSettings() const
{
    return m_data.totpSettings;
}

QString Entry::totpSettingsString() const
{
    if (m_data.totpSettings) {
        return Totp::writeSettings(
            m_data.totpSettings, resolveMultiplePlaceholders(title()), resolveMultiplePlaceholders(username()), true);
    }
    return {};
}

QString Entry::path() const
{
    auto path = group()->hierarchy();
    path << title();
    return path.mid(1).join("/");
}

void Entry::setUuid(const QUuid& uuid)
{
    Q_ASSERT(!uuid.isNull());
    set(m_uuid, uuid);
}

void Entry::setIcon(int iconNumber)
{
    Q_ASSERT(iconNumber >= 0);

    if (m_data.iconNumber != iconNumber || !m_data.customIcon.isNull()) {
        m_data.iconNumber = iconNumber;
        m_data.customIcon = QUuid();

        emitModified();
        emitDataChanged();
    }
}

void Entry::setIcon(const QUuid& uuid)
{
    Q_ASSERT(!uuid.isNull());

    if (m_data.customIcon != uuid) {
        m_data.customIcon = uuid;
        m_data.iconNumber = 0;

        emitModified();
        emitDataChanged();
    }
}

void Entry::setForegroundColor(const QString& colorStr)
{
    set(m_data.foregroundColor, colorStr);
}

void Entry::setBackgroundColor(const QString& colorStr)
{
    set(m_data.backgroundColor, colorStr);
}

void Entry::setOverrideUrl(const QString& url)
{
    set(m_data.overrideUrl, url);
}

void Entry::setTags(const QString& tags)
{
    static QRegExp rx("(\\,|\\t|\\;)");
    auto taglist = tags.split(rx, QString::SkipEmptyParts);
    // Trim whitespace before/after tag text
    for (auto itr = taglist.begin(); itr != taglist.end(); ++itr) {
        *itr = itr->trimmed();
    }
    // Remove duplicates
    auto tagSet = QSet<QString>::fromList(taglist);
    taglist = tagSet.toList();
    // Sort alphabetically
    taglist.sort();
    set(m_data.tags, taglist);
}

void Entry::addTag(const QString& tag)
{
    auto cleanTag = tag.trimmed();
    cleanTag.remove(QRegExp("(\\,|\\t|\\;)"));

    auto taglist = m_data.tags;
    if (!taglist.contains(cleanTag)) {
        taglist.append(cleanTag);
        taglist.sort();
        set(m_data.tags, taglist);
    }
}

void Entry::removeTag(const QString& tag)
{
    auto cleanTag = tag.trimmed();
    cleanTag.remove(QRegExp("(\\,|\\t|\\;)"));

    auto taglist = m_data.tags;
    if (taglist.removeAll(tag) > 0) {
        set(m_data.tags, taglist);
    }
}

void Entry::setTimeInfo(const TimeInfo& timeInfo)
{
    m_data.timeInfo = timeInfo;
}

void Entry::setAutoTypeEnabled(bool enable)
{
    set(m_data.autoTypeEnabled, enable);
}

void Entry::setAutoTypeObfuscation(int obfuscation)
{
    set(m_data.autoTypeObfuscation, obfuscation);
}

void Entry::setDefaultAutoTypeSequence(const QString& sequence)
{
    set(m_data.defaultAutoTypeSequence, sequence);
}

void Entry::setTitle(const QString& title)
{
    m_attributes->set(EntryAttributes::TitleKey, title, m_attributes->isProtected(EntryAttributes::TitleKey));
}

void Entry::setUrl(const QString& url)
{
    bool remove = url != m_attributes->value(EntryAttributes::URLKey)
                  && (m_attributes->value(EntryAttributes::RememberCmdExecAttr) == "1"
                      || m_attributes->value(EntryAttributes::RememberCmdExecAttr) == "0");
    if (remove) {
        m_attributes->remove(EntryAttributes::RememberCmdExecAttr);
    }
    m_attributes->set(EntryAttributes::URLKey, url, m_attributes->isProtected(EntryAttributes::URLKey));
}

void Entry::setUsername(const QString& username)
{
    m_attributes->set(EntryAttributes::UserNameKey, username, m_attributes->isProtected(EntryAttributes::UserNameKey));
}

void Entry::setPassword(const QString& password)
{
    // Reset Password Health
    m_data.passwordHealth.reset();
    m_attributes->set(EntryAttributes::PasswordKey, password, m_attributes->isProtected(EntryAttributes::PasswordKey));
}

void Entry::setNotes(const QString& notes)
{
    m_attributes->set(EntryAttributes::NotesKey, notes, m_attributes->isProtected(EntryAttributes::NotesKey));
}

void Entry::setDefaultAttribute(const QString& attribute, const QString& value)
{
    Q_ASSERT(EntryAttributes::isDefaultAttribute(attribute));

    if (!EntryAttributes::isDefaultAttribute(attribute)) {
        return;
    }

    m_attributes->set(attribute, value, m_attributes->isProtected(attribute));
}

void Entry::setExpires(const bool& value)
{
    if (m_data.timeInfo.expires() != value) {
        m_data.timeInfo.setExpires(value);
        emitModified();
    }
}

void Entry::setExpiryTime(const QDateTime& dateTime)
{
    if (m_data.timeInfo.expiryTime() != dateTime) {
        m_data.timeInfo.setExpiryTime(dateTime);
        emitModified();
    }
}

QList<Entry*> Entry::historyItems()
{
    return m_history;
}

const QList<Entry*>& Entry::historyItems() const
{
    return m_history;
}

void Entry::addHistoryItem(Entry* entry)
{
    Q_ASSERT(!entry->parent());

    m_history.append(entry);
    emitModified();
}

void Entry::removeHistoryItems(const QList<Entry*>& historyEntries)
{
    if (historyEntries.isEmpty()) {
        return;
    }

    for (Entry* entry : historyEntries) {
        Q_ASSERT(!entry->parent());
        Q_ASSERT(entry->uuid().isNull() || entry->uuid() == uuid());
        Q_ASSERT(m_history.contains(entry));

        m_history.removeOne(entry);
        delete entry;
    }

    emitModified();
}

void Entry::truncateHistory()
{
    const Database* db = database();

    if (!db) {
        return;
    }

    bool changed = false;
    int histMaxItems = db->metadata()->historyMaxItems();
    if (histMaxItems > -1) {
        int historyCount = 0;
        QMutableListIterator<Entry*> i(m_history);
        i.toBack();
        while (i.hasPrevious()) {
            historyCount++;
            Entry* entry = i.previous();
            if (historyCount > histMaxItems) {
                delete entry;
                i.remove();
                changed = true;
            }
        }
    }

    int histMaxSize = db->metadata()->historyMaxSize();
    if (histMaxSize > -1) {
        int size = 0;

        QMutableListIterator<Entry*> i(m_history);
        i.toBack();
        while (i.hasPrevious()) {
            Entry* historyItem = i.previous();

            // don't calculate size if it's already above the maximum
            if (size <= histMaxSize) {
                size += historyItem->size();
            }

            if (size > histMaxSize) {
                delete historyItem;
                i.remove();
                changed = true;
            }
        }
    }

    if (changed) {
        emitModified();
    }
}

bool Entry::equals(const Entry* other, CompareItemOptions options) const
{
    if (!other) {
        return false;
    }
    if (m_uuid != other->uuid()) {
        return false;
    }
    if (!m_data.equals(other->m_data, options)) {
        return false;
    }
    if (*m_customData != *other->m_customData) {
        return false;
    }
    if (*m_attributes != *other->m_attributes) {
        return false;
    }
    if (*m_attachments != *other->m_attachments) {
        return false;
    }
    if (*m_autoTypeAssociations != *other->m_autoTypeAssociations) {
        return false;
    }
    if (!options.testFlag(CompareItemIgnoreHistory)) {
        if (m_history.count() != other->m_history.count()) {
            return false;
        }
        for (int i = 0; i < m_history.count(); ++i) {
            if (!m_history[i]->equals(other->m_history[i], options)) {
                return false;
            }
        }
    }
    return true;
}

Entry* Entry::clone(CloneFlags flags) const
{
    auto entry = new Entry();
    entry->setUpdateTimeinfo(false);
    if (flags & CloneNewUuid) {
        entry->m_uuid = QUuid::createUuid();
    } else {
        entry->m_uuid = m_uuid;
    }
    entry->m_data = m_data;
    entry->m_customData->copyDataFrom(m_customData);
    entry->m_attributes->copyDataFrom(m_attributes);
    entry->m_attachments->copyDataFrom(m_attachments);

    if (flags & CloneUserAsRef) {
        entry->m_attributes->set(EntryAttributes::UserNameKey,
                                 buildReference(uuid(), EntryAttributes::UserNameKey),
                                 m_attributes->isProtected(EntryAttributes::UserNameKey));
    }

    if (flags & ClonePassAsRef) {
        entry->m_attributes->set(EntryAttributes::PasswordKey,
                                 buildReference(uuid(), EntryAttributes::PasswordKey),
                                 m_attributes->isProtected(EntryAttributes::PasswordKey));
    }

    entry->m_autoTypeAssociations->copyDataFrom(m_autoTypeAssociations);
    if (flags & CloneIncludeHistory) {
        for (Entry* historyItem : m_history) {
            Entry* historyItemClone =
                historyItem->clone(flags & ~CloneIncludeHistory & ~CloneNewUuid & ~CloneResetTimeInfo);
            historyItemClone->setUpdateTimeinfo(false);
            historyItemClone->setUuid(entry->uuid());
            historyItemClone->setUpdateTimeinfo(true);
            entry->addHistoryItem(historyItemClone);
        }
    }

    if (flags & CloneResetTimeInfo) {
        QDateTime now = Clock::currentDateTimeUtc();
        entry->m_data.timeInfo.setCreationTime(now);
        entry->m_data.timeInfo.setLastModificationTime(now);
        entry->m_data.timeInfo.setLastAccessTime(now);
        entry->m_data.timeInfo.setLocationChanged(now);
    }

    if (flags & CloneRenameTitle) {
        entry->setTitle(tr("%1 - Clone").arg(entry->title()));
    }

    entry->setUpdateTimeinfo(true);

    return entry;
}

void Entry::copyDataFrom(const Entry* other)
{
    setUpdateTimeinfo(false);
    m_data = other->m_data;
    m_customData->copyDataFrom(other->m_customData);
    m_attributes->copyDataFrom(other->m_attributes);
    m_attachments->copyDataFrom(other->m_attachments);
    m_autoTypeAssociations->copyDataFrom(other->m_autoTypeAssociations);
    setUpdateTimeinfo(true);
}

void Entry::beginUpdate()
{
    Q_ASSERT(m_tmpHistoryItem.isNull());

    m_tmpHistoryItem.reset(new Entry());
    m_tmpHistoryItem->setUpdateTimeinfo(false);
    m_tmpHistoryItem->m_uuid = m_uuid;
    m_tmpHistoryItem->m_data = m_data;
    m_tmpHistoryItem->m_attributes->copyDataFrom(m_attributes);
    m_tmpHistoryItem->m_attachments->copyDataFrom(m_attachments);
    m_tmpHistoryItem->m_autoTypeAssociations->copyDataFrom(m_autoTypeAssociations);

    m_modifiedSinceBegin = false;
}

bool Entry::endUpdate()
{
    Q_ASSERT(!m_tmpHistoryItem.isNull());
    if (m_modifiedSinceBegin) {
        m_tmpHistoryItem->setUpdateTimeinfo(true);
        addHistoryItem(m_tmpHistoryItem.take());
        truncateHistory();
    }

    m_tmpHistoryItem.reset();

    return m_modifiedSinceBegin;
}

void Entry::updateModifiedSinceBegin()
{
    m_modifiedSinceBegin = true;
}

QString Entry::resolveMultiplePlaceholdersRecursive(const QString& str, int maxDepth) const
{
    if (maxDepth <= 0) {
        qWarning("Maximum depth of replacement has been reached. Entry uuid: %s", uuid().toString().toLatin1().data());
        return str;
    }

    QString result = str;
    QRegExp placeholderRegEx("(\\{[^\\}]+\\})", Qt::CaseInsensitive, QRegExp::RegExp2);
    placeholderRegEx.setMinimal(true);
    int pos = 0;
    while ((pos = placeholderRegEx.indexIn(str, pos)) != -1) {
        const QString found = placeholderRegEx.cap(1);
        result.replace(found, resolvePlaceholderRecursive(found, maxDepth - 1));
        pos += placeholderRegEx.matchedLength();
    }

    if (result != str) {
        result = resolveMultiplePlaceholdersRecursive(result, maxDepth - 1);
    }

    return result;
}

QString Entry::resolvePlaceholderRecursive(const QString& placeholder, int maxDepth) const
{
    if (maxDepth <= 0) {
        qWarning("Maximum depth of replacement has been reached. Entry uuid: %s", uuid().toString().toLatin1().data());
        return placeholder;
    }

    const PlaceholderType typeOfPlaceholder = placeholderType(placeholder);
    switch (typeOfPlaceholder) {
    case PlaceholderType::NotPlaceholder:
    case PlaceholderType::Unknown:
        return resolveMultiplePlaceholdersRecursive(placeholder, maxDepth - 1);
    case PlaceholderType::Title:
        if (placeholderType(title()) == PlaceholderType::Title) {
            return title();
        }
        return resolveMultiplePlaceholdersRecursive(title(), maxDepth - 1);
    case PlaceholderType::UserName:
        if (placeholderType(username()) == PlaceholderType::UserName) {
            return username();
        }
        return resolveMultiplePlaceholdersRecursive(username(), maxDepth - 1);
    case PlaceholderType::Password:
        if (placeholderType(password()) == PlaceholderType::Password) {
            return password();
        }
        return resolveMultiplePlaceholdersRecursive(password(), maxDepth - 1);
    case PlaceholderType::Notes:
        if (placeholderType(notes()) == PlaceholderType::Notes) {
            return notes();
        }
        return resolveMultiplePlaceholdersRecursive(notes(), maxDepth - 1);
    case PlaceholderType::Url:
        if (placeholderType(url()) == PlaceholderType::Url) {
            return url();
        }
        return resolveMultiplePlaceholdersRecursive(url(), maxDepth - 1);
    case PlaceholderType::DbDir: {
        QFileInfo fileInfo(database()->filePath());
        return fileInfo.absoluteDir().absolutePath();
    }
    case PlaceholderType::UrlWithoutScheme:
    case PlaceholderType::UrlScheme:
    case PlaceholderType::UrlHost:
    case PlaceholderType::UrlPort:
    case PlaceholderType::UrlPath:
    case PlaceholderType::UrlQuery:
    case PlaceholderType::UrlFragment:
    case PlaceholderType::UrlUserInfo:
    case PlaceholderType::UrlUserName:
    case PlaceholderType::UrlPassword: {
        const QString strUrl = resolveMultiplePlaceholdersRecursive(url(), maxDepth - 1);
        return resolveUrlPlaceholder(strUrl, typeOfPlaceholder);
    }
    case PlaceholderType::Totp:
        // totp can't have placeholder inside
        return totp();
    case PlaceholderType::CustomAttribute: {
        const QString key = placeholder.mid(3, placeholder.length() - 4); // {S:attr} => mid(3, len - 4)
        return attributes()->hasKey(key) ? attributes()->value(key) : QString();
    }
    case PlaceholderType::Reference:
        return resolveReferencePlaceholderRecursive(placeholder, maxDepth);
    case PlaceholderType::DateTimeSimple:
    case PlaceholderType::DateTimeYear:
    case PlaceholderType::DateTimeMonth:
    case PlaceholderType::DateTimeDay:
    case PlaceholderType::DateTimeHour:
    case PlaceholderType::DateTimeMinute:
    case PlaceholderType::DateTimeSecond:
    case PlaceholderType::DateTimeUtcSimple:
    case PlaceholderType::DateTimeUtcYear:
    case PlaceholderType::DateTimeUtcMonth:
    case PlaceholderType::DateTimeUtcDay:
    case PlaceholderType::DateTimeUtcHour:
    case PlaceholderType::DateTimeUtcMinute:
    case PlaceholderType::DateTimeUtcSecond:
        return resolveMultiplePlaceholdersRecursive(resolveDateTimePlaceholder(typeOfPlaceholder), maxDepth - 1);
    }

    return placeholder;
}

QString Entry::resolveDateTimePlaceholder(Entry::PlaceholderType placeholderType) const
{
    QDateTime time = Clock::currentDateTime();
    QDateTime time_utc = Clock::currentDateTimeUtc();
    QString date_formatted{};

    switch (placeholderType) {
    case PlaceholderType::DateTimeSimple:
        date_formatted = time.toString("yyyyMMddhhmmss");
        break;
    case PlaceholderType::DateTimeYear:
        date_formatted = time.toString("yyyy");
        break;
    case PlaceholderType::DateTimeMonth:
        date_formatted = time.toString("MM");
        break;
    case PlaceholderType::DateTimeDay:
        date_formatted = time.toString("dd");
        break;
    case PlaceholderType::DateTimeHour:
        date_formatted = time.toString("hh");
        break;
    case PlaceholderType::DateTimeMinute:
        date_formatted = time.toString("mm");
        break;
    case PlaceholderType::DateTimeSecond:
        date_formatted = time.toString("ss");
        break;
    case PlaceholderType::DateTimeUtcSimple:
        date_formatted = time_utc.toString("yyyyMMddhhmmss");
        break;
    case PlaceholderType::DateTimeUtcYear:
        date_formatted = time_utc.toString("yyyy");
        break;
    case PlaceholderType::DateTimeUtcMonth:
        date_formatted = time_utc.toString("MM");
        break;
    case PlaceholderType::DateTimeUtcDay:
        date_formatted = time_utc.toString("dd");
        break;
    case PlaceholderType::DateTimeUtcHour:
        date_formatted = time_utc.toString("hh");
        break;
    case PlaceholderType::DateTimeUtcMinute:
        date_formatted = time_utc.toString("mm");
        break;
    case PlaceholderType::DateTimeUtcSecond:
        date_formatted = time_utc.toString("ss");
        break;
    default: {
        Q_ASSERT_X(false, "Entry::resolveDateTimePlaceholder", "Bad DateTime placeholder type");
        break;
    }
    }

    return date_formatted;
}

QString Entry::resolveReferencePlaceholderRecursive(const QString& placeholder, int maxDepth) const
{
    if (maxDepth <= 0) {
        qWarning("Maximum depth of replacement has been reached. Entry uuid: %s", uuid().toString().toLatin1().data());
        return placeholder;
    }

    // resolving references in format: {REF:<WantedField>@<SearchIn>:<SearchText>}
    // using format from http://keepass.info/help/base/fieldrefs.html at the time of writing

    QRegularExpressionMatch match = EntryAttributes::matchReference(placeholder);
    if (!match.hasMatch() || !m_group || !m_group->database()) {
        return placeholder;
    }

    QString result;
    const QString searchIn = match.captured(EntryAttributes::SearchInGroupName);
    const QString searchText = match.captured(EntryAttributes::SearchTextGroupName);

    const EntryReferenceType searchInType = Entry::referenceType(searchIn);

    const Entry* refEntry = m_group->database()->rootGroup()->findEntryBySearchTerm(searchText, searchInType);

    if (refEntry) {
        const QString wantedField = match.captured(EntryAttributes::WantedFieldGroupName);
        result = refEntry->referenceFieldValue(Entry::referenceType(wantedField));

        // Referencing fields of other entries only works with standard fields, not with custom user strings.
        // If you want to reference a custom user string, you need to place a redirection in a standard field
        // of the entry with the custom string, using {S:<Name>}, and reference the standard field.
        result = refEntry->resolveMultiplePlaceholdersRecursive(result, maxDepth - 1);
    }

    return result;
}

QString Entry::referenceFieldValue(EntryReferenceType referenceType) const
{
    switch (referenceType) {
    case EntryReferenceType::Title:
        return title();
    case EntryReferenceType::UserName:
        return username();
    case EntryReferenceType::Password:
        return password();
    case EntryReferenceType::Url:
        return url();
    case EntryReferenceType::Notes:
        return notes();
    case EntryReferenceType::QUuid:
        return uuidToHex();
    default:
        break;
    }
    return QString();
}

void Entry::moveUp()
{
    if (m_group) {
        m_group->moveEntryUp(this);
    }
}

void Entry::moveDown()
{
    if (m_group) {
        m_group->moveEntryDown(this);
    }
}

Group* Entry::group()
{
    return m_group;
}

const Group* Entry::group() const
{
    return m_group;
}

void Entry::setGroup(Group* group, bool trackPrevious)
{
    Q_ASSERT(group);

    if (m_group == group) {
        return;
    }

    if (m_group) {
        m_group->removeEntry(this);
        if (m_group->database() && m_group->database() != group->database()) {
            setPreviousParentGroup(nullptr);
            m_group->database()->addDeletedObject(m_uuid);

            // copy custom icon to the new database
            if (!iconUuid().isNull() && group->database() && m_group->database()->metadata()->hasCustomIcon(iconUuid())
                && !group->database()->metadata()->hasCustomIcon(iconUuid())) {
                group->database()->metadata()->addCustomIcon(iconUuid(),
                                                             m_group->database()->metadata()->customIcon(iconUuid()));
            }
        } else if (trackPrevious && m_group->database() && group != m_group) {
            setPreviousParentGroup(m_group);
        }
    }

    m_group = group;
    group->addEntry(this);

    QObject::setParent(group);

    if (m_updateTimeinfo) {
        m_data.timeInfo.setLocationChanged(Clock::currentDateTimeUtc());
    }
}

void Entry::emitDataChanged()
{
    emit entryDataChanged(this);
}

const Database* Entry::database() const
{
    if (m_group) {
        return m_group->database();
    }
    return nullptr;
}

Database* Entry::database()
{
    if (m_group) {
        return m_group->database();
    }
    return nullptr;
}

QString Entry::maskPasswordPlaceholders(const QString& str) const
{
    QString result = str;
    result.replace(QRegExp("(\\{PASSWORD\\})", Qt::CaseInsensitive, QRegExp::RegExp2), "******");
    return result;
}

Entry* Entry::resolveReference(const QString& str) const
{
    QRegularExpressionMatch match = EntryAttributes::matchReference(str);
    if (!match.hasMatch()) {
        return nullptr;
    }

    const QString searchIn = match.captured(EntryAttributes::SearchInGroupName);
    const QString searchText = match.captured(EntryAttributes::SearchTextGroupName);

    const EntryReferenceType searchInType = Entry::referenceType(searchIn);
    return m_group->database()->rootGroup()->findEntryBySearchTerm(searchText, searchInType);
}

QString Entry::resolveMultiplePlaceholders(const QString& str) const
{
    return resolveMultiplePlaceholdersRecursive(str, ResolveMaximumDepth);
}

QString Entry::resolvePlaceholder(const QString& placeholder) const
{
    return resolvePlaceholderRecursive(placeholder, ResolveMaximumDepth);
}

QString Entry::resolveUrlPlaceholder(const QString& str, Entry::PlaceholderType placeholderType) const
{
    if (str.isEmpty()) {
        return QString();
    }

    const QUrl qurl(str);
    switch (placeholderType) {
    case PlaceholderType::UrlWithoutScheme:
        return qurl.toString(QUrl::RemoveScheme | QUrl::FullyDecoded);
    case PlaceholderType::UrlScheme:
        return qurl.scheme();
    case PlaceholderType::UrlHost:
        return qurl.host();
    case PlaceholderType::UrlPort:
        return QString::number(qurl.port());
    case PlaceholderType::UrlPath:
        return qurl.path();
    case PlaceholderType::UrlQuery:
        return qurl.query();
    case PlaceholderType::UrlFragment:
        return qurl.fragment();
    case PlaceholderType::UrlUserInfo:
        return qurl.userInfo();
    case PlaceholderType::UrlUserName:
        return qurl.userName();
    case PlaceholderType::UrlPassword:
        return qurl.password();
    default: {
        Q_ASSERT_X(false, "Entry::resolveUrlPlaceholder", "Bad url placeholder type");
        break;
    }
    }

    return QString();
}

Entry::PlaceholderType Entry::placeholderType(const QString& placeholder) const
{
    if (!placeholder.startsWith(QLatin1Char('{')) || !placeholder.endsWith(QLatin1Char('}'))) {
        return PlaceholderType::NotPlaceholder;
    }
    if (placeholder.startsWith(QLatin1Literal("{S:"))) {
        return PlaceholderType::CustomAttribute;
    }
    if (placeholder.startsWith(QLatin1Literal("{REF:"))) {
        return PlaceholderType::Reference;
    }

    static const QMap<QString, PlaceholderType> placeholders{
        {QStringLiteral("{TITLE}"), PlaceholderType::Title},
        {QStringLiteral("{USERNAME}"), PlaceholderType::UserName},
        {QStringLiteral("{PASSWORD}"), PlaceholderType::Password},
        {QStringLiteral("{NOTES}"), PlaceholderType::Notes},
        {QStringLiteral("{TOTP}"), PlaceholderType::Totp},
        {QStringLiteral("{URL}"), PlaceholderType::Url},
        {QStringLiteral("{URL:RMVSCM}"), PlaceholderType::UrlWithoutScheme},
        {QStringLiteral("{URL:WITHOUTSCHEME}"), PlaceholderType::UrlWithoutScheme},
        {QStringLiteral("{URL:SCM}"), PlaceholderType::UrlScheme},
        {QStringLiteral("{URL:SCHEME}"), PlaceholderType::UrlScheme},
        {QStringLiteral("{URL:HOST}"), PlaceholderType::UrlHost},
        {QStringLiteral("{URL:PORT}"), PlaceholderType::UrlPort},
        {QStringLiteral("{URL:PATH}"), PlaceholderType::UrlPath},
        {QStringLiteral("{URL:QUERY}"), PlaceholderType::UrlQuery},
        {QStringLiteral("{URL:FRAGMENT}"), PlaceholderType::UrlFragment},
        {QStringLiteral("{URL:USERINFO}"), PlaceholderType::UrlUserInfo},
        {QStringLiteral("{URL:USERNAME}"), PlaceholderType::UrlUserName},
        {QStringLiteral("{URL:PASSWORD}"), PlaceholderType::UrlPassword},
        {QStringLiteral("{DT_SIMPLE}"), PlaceholderType::DateTimeSimple},
        {QStringLiteral("{DT_YEAR}"), PlaceholderType::DateTimeYear},
        {QStringLiteral("{DT_MONTH}"), PlaceholderType::DateTimeMonth},
        {QStringLiteral("{DT_DAY}"), PlaceholderType::DateTimeDay},
        {QStringLiteral("{DT_HOUR}"), PlaceholderType::DateTimeHour},
        {QStringLiteral("{DT_MINUTE}"), PlaceholderType::DateTimeMinute},
        {QStringLiteral("{DT_SECOND}"), PlaceholderType::DateTimeSecond},
        {QStringLiteral("{DT_UTC_SIMPLE}"), PlaceholderType::DateTimeUtcSimple},
        {QStringLiteral("{DT_UTC_YEAR}"), PlaceholderType::DateTimeUtcYear},
        {QStringLiteral("{DT_UTC_MONTH}"), PlaceholderType::DateTimeUtcMonth},
        {QStringLiteral("{DT_UTC_DAY}"), PlaceholderType::DateTimeUtcDay},
        {QStringLiteral("{DT_UTC_HOUR}"), PlaceholderType::DateTimeUtcHour},
        {QStringLiteral("{DT_UTC_MINUTE}"), PlaceholderType::DateTimeUtcMinute},
        {QStringLiteral("{DT_UTC_SECOND}"), PlaceholderType::DateTimeUtcSecond},
        {QStringLiteral("{DB_DIR}"), PlaceholderType::DbDir}};

    return placeholders.value(placeholder.toUpper(), PlaceholderType::Unknown);
}

QString Entry::resolveUrl(const QString& url) const
{
    QString newUrl = url;

    QRegExp fileRegEx("^([a-z]:)?[\\\\/]", Qt::CaseInsensitive, QRegExp::RegExp2);
    if (fileRegEx.indexIn(newUrl) != -1) {
        // Match possible file paths without the scheme and convert it to a file URL
        newUrl = QDir::fromNativeSeparators(newUrl);
        newUrl = QUrl::fromLocalFile(newUrl).toString();
    } else if (newUrl.startsWith("cmd://")) {
        QStringList cmdList = newUrl.split(" ");
        for (int i = 1; i < cmdList.size(); ++i) {
            // Don't pass arguments to the resolveUrl function (they look like URL's)
            if (!cmdList[i].startsWith("-") && !cmdList[i].startsWith("/")) {
                return resolveUrl(cmdList[i].remove(QRegExp("'|\"")));
            }
        }

        // No URL in this command
        return QString("");
    }

    if (!newUrl.isEmpty() && !newUrl.contains("://")) {
        // URL doesn't have a protocol, add https by default
        newUrl.prepend("https://");
    }

    // Validate the URL
    QUrl tempUrl = QUrl(newUrl);
    if (tempUrl.isValid()
        && (tempUrl.scheme() == "http" || tempUrl.scheme() == "https" || tempUrl.scheme() == "file")) {
        return tempUrl.url();
    }

    // No valid http URL's found
    return {};
}

Group* Entry::previousParentGroup()
{
    if (!database() || !database()->rootGroup()) {
        return nullptr;
    }
    return database()->rootGroup()->findGroupByUuid(m_data.previousParentGroupUuid);
}

const Group* Entry::previousParentGroup() const
{
    if (!database() || !database()->rootGroup()) {
        return nullptr;
    }
    return database()->rootGroup()->findGroupByUuid(m_data.previousParentGroupUuid);
}

QUuid Entry::previousParentGroupUuid() const
{
    return m_data.previousParentGroupUuid;
}

void Entry::setPreviousParentGroupUuid(const QUuid& uuid)
{
    set(m_data.previousParentGroupUuid, uuid);
}

void Entry::setPreviousParentGroup(const Group* group)
{
    setPreviousParentGroupUuid(group ? group->uuid() : QUuid());
}

bool EntryData::operator==(const EntryData& other) const
{
    return equals(other, CompareItemDefault);
}

bool EntryData::operator!=(const EntryData& other) const
{
    return !(*this == other);
}

bool EntryData::equals(const EntryData& other, CompareItemOptions options) const
{
    if (::compare(iconNumber, other.iconNumber, options) != 0) {
        return false;
    }
    if (::compare(customIcon, other.customIcon, options) != 0) {
        return false;
    }
    if (::compare(foregroundColor, other.foregroundColor, options) != 0) {
        return false;
    }
    if (::compare(backgroundColor, other.backgroundColor, options) != 0) {
        return false;
    }
    if (::compare(overrideUrl, other.overrideUrl, options) != 0) {
        return false;
    }
    if (::compare(tags, other.tags, options) != 0) {
        return false;
    }
    if (::compare(autoTypeEnabled, other.autoTypeEnabled, options) != 0) {
        return false;
    }
    if (::compare(autoTypeObfuscation, other.autoTypeObfuscation, options) != 0) {
        return false;
    }
    if (::compare(defaultAutoTypeSequence, other.defaultAutoTypeSequence, options) != 0) {
        return false;
    }
    if (!timeInfo.equals(other.timeInfo, options)) {
        return false;
    }
    if (!totpSettings.isNull() && !other.totpSettings.isNull()) {
        // Both have TOTP settings, compare them
        if (::compare(totpSettings->key, other.totpSettings->key, options) != 0) {
            return false;
        }
        if (::compare(totpSettings->digits, other.totpSettings->digits, options) != 0) {
            return false;
        }
        if (::compare(totpSettings->step, other.totpSettings->step, options) != 0) {
            return false;
        }
    } else if (totpSettings.isNull() != other.totpSettings.isNull()) {
        // The existance of TOTP has changed between these entries
        return false;
    }
    if (::compare(excludeFromReports, other.excludeFromReports, options) != 0) {
        return false;
    }
    if (::compare(previousParentGroupUuid, other.previousParentGroupUuid, options) != 0) {
        return false;
    }

    return true;
}