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
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "nsNavBookmarks.h"
#include "nsNavHistory.h"
#include "nsPlacesMacros.h"
#include "Helpers.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsITaggingService.h"
#include "nsNetUtil.h"
#include "nsIProtocolHandler.h"
#include "nsIObserverService.h"
#include "nsUnicharUtils.h"
#include "nsPrintfCString.h"
#include "nsQueryObject.h"
#include "mozIStorageValueArray.h"
#include "mozilla/Preferences.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/storage.h"
#include "mozilla/dom/PlacesBookmarkAddition.h"
#include "mozilla/dom/PlacesBookmarkRemoved.h"
#include "mozilla/dom/PlacesBookmarkTags.h"
#include "mozilla/dom/PlacesBookmarkTime.h"
#include "mozilla/dom/PlacesBookmarkTitle.h"
#include "mozilla/dom/PlacesObservers.h"
#include "mozilla/dom/PlacesVisit.h"
using namespace mozilla;
// These columns sit to the right of the kGetInfoIndex_* columns.
const int32_t nsNavBookmarks::kGetChildrenIndex_Guid = 18;
const int32_t nsNavBookmarks::kGetChildrenIndex_Position = 19;
const int32_t nsNavBookmarks::kGetChildrenIndex_Type = 20;
const int32_t nsNavBookmarks::kGetChildrenIndex_PlaceID = 21;
const int32_t nsNavBookmarks::kGetChildrenIndex_SyncStatus = 22;
using namespace mozilla::dom;
using namespace mozilla::places;
extern "C" {
// Returns the total number of Sync changes recorded since Places startup for
// all bookmarks. This function uses C linkage because it's called from the
// Rust synced bookmarks mirror, on the storage thread. Using `get_service` to
// access the bookmarks service from Rust trips a thread-safety assertion, so
// we can't use `nsNavBookmarks::GetTotalSyncChanges`.
int64_t NS_NavBookmarksTotalSyncChanges() {
return nsNavBookmarks::sTotalSyncChanges;
}
} // extern "C"
PLACES_FACTORY_SINGLETON_IMPLEMENTATION(nsNavBookmarks, gBookmarksService)
namespace {
// Returns the sync change counter increment for a change source constant.
inline int64_t DetermineSyncChangeDelta(uint16_t aSource) {
return aSource == nsINavBookmarksService::SOURCE_SYNC ? 0 : 1;
}
// Returns the sync status for a new item inserted by a change source.
inline int32_t DetermineInitialSyncStatus(uint16_t aSource) {
if (aSource == nsINavBookmarksService::SOURCE_SYNC) {
return nsINavBookmarksService::SYNC_STATUS_NORMAL;
}
if (aSource == nsINavBookmarksService::SOURCE_RESTORE_ON_STARTUP) {
return nsINavBookmarksService::SYNC_STATUS_UNKNOWN;
}
return nsINavBookmarksService::SYNC_STATUS_NEW;
}
// Indicates whether an item has been uploaded to the server and
// needs a tombstone on deletion.
inline bool NeedsTombstone(const BookmarkData& aBookmark) {
return aBookmark.syncStatus == nsINavBookmarksService::SYNC_STATUS_NORMAL;
}
inline nsresult GetTags(nsIURI* aURI, nsTArray<nsString>& aResult) {
nsresult rv;
nsCOMPtr<nsITaggingService> taggingService =
do_GetService("@mozilla.org/browser/tagging-service;1", &rv);
if (NS_FAILED(rv)) {
return rv;
}
return taggingService->GetTagsForURI(aURI, aResult);
}
} // namespace
nsNavBookmarks::nsNavBookmarks() : mCanNotify(false) {
NS_ASSERTION(!gBookmarksService,
"Attempting to create two instances of the service!");
gBookmarksService = this;
}
nsNavBookmarks::~nsNavBookmarks() {
NS_ASSERTION(gBookmarksService == this,
"Deleting a non-singleton instance of the service");
if (gBookmarksService == this) gBookmarksService = nullptr;
}
NS_IMPL_ISUPPORTS(nsNavBookmarks, nsINavBookmarksService, nsIObserver,
nsISupportsWeakReference)
Atomic<int64_t> nsNavBookmarks::sLastInsertedItemId(0);
void // static
nsNavBookmarks::StoreLastInsertedId(const nsACString& aTable,
const int64_t aLastInsertedId) {
MOZ_ASSERT(aTable.EqualsLiteral("moz_bookmarks"));
sLastInsertedItemId = aLastInsertedId;
}
Atomic<int64_t> nsNavBookmarks::sTotalSyncChanges(0);
void // static
nsNavBookmarks::NoteSyncChange() {
sTotalSyncChanges++;
}
nsresult nsNavBookmarks::Init() {
mDB = Database::GetDatabase();
NS_ENSURE_STATE(mDB);
nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
if (os) {
(void)os->AddObserver(this, TOPIC_PLACES_CONNECTION_CLOSED, true);
}
mCanNotify = true;
// DO NOT PUT STUFF HERE that can fail. See observer comment above.
return NS_OK;
}
nsresult nsNavBookmarks::AdjustIndices(int64_t aFolderId, int32_t aStartIndex,
int32_t aEndIndex, int32_t aDelta) {
NS_ASSERTION(
aStartIndex >= 0 && aEndIndex <= INT32_MAX && aStartIndex <= aEndIndex,
"Bad indices");
nsCOMPtr<mozIStorageStatement> stmt = mDB->GetStatement(
"UPDATE moz_bookmarks SET position = position + :delta "
"WHERE parent = :parent "
"AND position BETWEEN :from_index AND :to_index");
NS_ENSURE_STATE(stmt);
mozStorageStatementScoper scoper(stmt);
nsresult rv = stmt->BindInt32ByName("delta"_ns, aDelta);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->BindInt64ByName("parent"_ns, aFolderId);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->BindInt32ByName("from_index"_ns, aStartIndex);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->BindInt32ByName("to_index"_ns, aEndIndex);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->Execute();
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
nsresult nsNavBookmarks::AdjustSeparatorsSyncCounter(int64_t aFolderId,
int32_t aStartIndex,
int64_t aSyncChangeDelta) {
MOZ_ASSERT(aStartIndex >= 0, "Bad start position");
if (!aSyncChangeDelta) {
return NS_OK;
}
nsCOMPtr<mozIStorageStatement> stmt = mDB->GetStatement(
"UPDATE moz_bookmarks SET syncChangeCounter = syncChangeCounter + :delta "
"WHERE parent = :parent AND position >= :start_index "
"AND type = :item_type ");
NS_ENSURE_STATE(stmt);
mozStorageStatementScoper scoper(stmt);
nsresult rv = stmt->BindInt64ByName("delta"_ns, aSyncChangeDelta);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->BindInt64ByName("parent"_ns, aFolderId);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->BindInt32ByName("start_index"_ns, aStartIndex);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->BindInt32ByName("item_type"_ns, TYPE_SEPARATOR);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->Execute();
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
NS_IMETHODIMP
nsNavBookmarks::GetTagsFolder(int64_t* aRoot) {
int64_t id = mDB->GetTagsFolderId();
NS_ENSURE_TRUE(id > 0, NS_ERROR_UNEXPECTED);
*aRoot = id;
return NS_OK;
}
NS_IMETHODIMP
nsNavBookmarks::GetTotalSyncChanges(int64_t* aTotalSyncChanges) {
*aTotalSyncChanges = sTotalSyncChanges;
return NS_OK;
}
nsresult nsNavBookmarks::InsertBookmarkInDB(
int64_t aPlaceId, enum ItemType aItemType, int64_t aParentId,
int32_t aIndex, const nsACString& aTitle, PRTime aDateAdded,
PRTime aLastModified, const nsACString& aParentGuid, int64_t aGrandParentId,
nsIURI* aURI, uint16_t aSource, int64_t* _itemId, nsACString& _guid) {
// Check for a valid itemId.
MOZ_ASSERT(_itemId && (*_itemId == -1 || *_itemId > 0));
// Check for a valid placeId.
MOZ_ASSERT(aPlaceId && (aPlaceId == -1 || aPlaceId > 0));
nsCOMPtr<mozIStorageStatement> stmt = mDB->GetStatement(
"INSERT INTO moz_bookmarks "
"(id, fk, type, parent, position, title, "
"dateAdded, lastModified, guid, syncStatus, syncChangeCounter) "
"VALUES (:item_id, :page_id, :item_type, :parent, :item_index, "
":item_title, :date_added, :last_modified, "
":item_guid, :sync_status, :change_counter)");
NS_ENSURE_STATE(stmt);
mozStorageStatementScoper scoper(stmt);
nsresult rv;
if (*_itemId != -1)
rv = stmt->BindInt64ByName("item_id"_ns, *_itemId);
else
rv = stmt->BindNullByName("item_id"_ns);
NS_ENSURE_SUCCESS(rv, rv);
if (aPlaceId != -1)
rv = stmt->BindInt64ByName("page_id"_ns, aPlaceId);
else
rv = stmt->BindNullByName("page_id"_ns);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->BindInt32ByName("item_type"_ns, aItemType);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->BindInt64ByName("parent"_ns, aParentId);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->BindInt32ByName("item_index"_ns, aIndex);
NS_ENSURE_SUCCESS(rv, rv);
if (aTitle.IsEmpty())
rv = stmt->BindNullByName("item_title"_ns);
else
rv = stmt->BindUTF8StringByName("item_title"_ns, aTitle);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->BindInt64ByName("date_added"_ns, aDateAdded);
NS_ENSURE_SUCCESS(rv, rv);
if (aLastModified) {
rv = stmt->BindInt64ByName("last_modified"_ns, aLastModified);
} else {
rv = stmt->BindInt64ByName("last_modified"_ns, aDateAdded);
}
NS_ENSURE_SUCCESS(rv, rv);
// Could use IsEmpty because our callers check for GUID validity,
// but it doesn't hurt.
bool hasExistingGuid = _guid.Length() == 12;
if (hasExistingGuid) {
MOZ_ASSERT(IsValidGUID(_guid));
rv = stmt->BindUTF8StringByName("item_guid"_ns, _guid);
NS_ENSURE_SUCCESS(rv, rv);
} else {
nsAutoCString guid;
rv = GenerateGUID(guid);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->BindUTF8StringByName("item_guid"_ns, guid);
NS_ENSURE_SUCCESS(rv, rv);
_guid.Assign(guid);
}
int64_t syncChangeDelta = DetermineSyncChangeDelta(aSource);
rv = stmt->BindInt64ByName("change_counter"_ns, syncChangeDelta);
NS_ENSURE_SUCCESS(rv, rv);
uint16_t syncStatus = DetermineInitialSyncStatus(aSource);
rv = stmt->BindInt32ByName("sync_status"_ns, syncStatus);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->Execute();
NS_ENSURE_SUCCESS(rv, rv);
// Remove stale tombstones if we're reinserting an item.
if (hasExistingGuid) {
rv = RemoveTombstone(_guid);
NS_ENSURE_SUCCESS(rv, rv);
}
if (*_itemId == -1) {
*_itemId = sLastInsertedItemId;
}
if (aParentId > 0) {
// Update last modified date of the ancestors.
// TODO (bug 408991): Doing this for all ancestors would be slow without a
// nested tree, so for now update only the parent.
rv = SetItemDateInternal(LAST_MODIFIED, syncChangeDelta, aParentId,
aDateAdded);
NS_ENSURE_SUCCESS(rv, rv);
}
int64_t tagsRootId = mDB->GetTagsFolderId();
bool isTagging = aGrandParentId == tagsRootId;
if (isTagging) {
// If we're tagging a bookmark, increment the change counter for all
// bookmarks with the URI.
rv = AddSyncChangesForBookmarksWithURI(aURI, syncChangeDelta);
NS_ENSURE_SUCCESS(rv, rv);
}
// Mark all affected separators as changed
rv = AdjustSeparatorsSyncCounter(aParentId, aIndex + 1, syncChangeDelta);
NS_ENSURE_SUCCESS(rv, rv);
// Add a cache entry since we know everything about this bookmark.
BookmarkData bookmark;
bookmark.id = *_itemId;
bookmark.guid.Assign(_guid);
if (!aTitle.IsEmpty()) {
bookmark.title.Assign(aTitle);
}
bookmark.position = aIndex;
bookmark.placeId = aPlaceId;
bookmark.parentId = aParentId;
bookmark.type = aItemType;
bookmark.dateAdded = aDateAdded;
if (aLastModified)
bookmark.lastModified = aLastModified;
else
bookmark.lastModified = aDateAdded;
if (aURI) {
rv = aURI->GetSpec(bookmark.url);
NS_ENSURE_SUCCESS(rv, rv);
}
bookmark.parentGuid = aParentGuid;
bookmark.grandParentId = aGrandParentId;
bookmark.syncStatus = syncStatus;
return NS_OK;
}
NS_IMETHODIMP
nsNavBookmarks::InsertBookmark(int64_t aFolder, nsIURI* aURI, int32_t aIndex,
const nsACString& aTitle,
const nsACString& aGUID, uint16_t aSource,
int64_t* aNewBookmarkId) {
NS_ENSURE_ARG(aURI);
NS_ENSURE_ARG_POINTER(aNewBookmarkId);
NS_ENSURE_ARG_MIN(aIndex, nsINavBookmarksService::DEFAULT_INDEX);
if (!aGUID.IsEmpty() && !IsValidGUID(aGUID)) return NS_ERROR_INVALID_ARG;
mozStorageTransaction transaction(mDB->MainConn(), false);
// XXX Handle the error, bug 1696133.
Unused << NS_WARN_IF(NS_FAILED(transaction.Start()));
nsNavHistory* history = nsNavHistory::GetHistoryService();
NS_ENSURE_TRUE(history, NS_ERROR_OUT_OF_MEMORY);
int64_t placeId;
nsAutoCString placeGuid;
nsresult rv = history->GetOrCreateIdForPage(aURI, &placeId, placeGuid);
NS_ENSURE_SUCCESS(rv, rv);
// Get the correct index for insertion. This also ensures the parent exists.
int32_t index, folderCount;
int64_t grandParentId;
nsAutoCString folderGuid;
rv = FetchFolderInfo(aFolder, &folderCount, folderGuid, &grandParentId);
NS_ENSURE_SUCCESS(rv, rv);
if (aIndex == nsINavBookmarksService::DEFAULT_INDEX ||
aIndex >= folderCount) {
index = folderCount;
} else {
index = aIndex;
// Create space for the insertion.
rv = AdjustIndices(aFolder, index, INT32_MAX, 1);
NS_ENSURE_SUCCESS(rv, rv);
}
*aNewBookmarkId = -1;
PRTime dateAdded = RoundedPRNow();
nsAutoCString guid(aGUID);
nsCString title;
TruncateTitle(aTitle, title);
rv = InsertBookmarkInDB(placeId, BOOKMARK, aFolder, index, title, dateAdded,
0, folderGuid, grandParentId, aURI, aSource,
aNewBookmarkId, guid);
NS_ENSURE_SUCCESS(rv, rv);
rv = transaction.Commit();
NS_ENSURE_SUCCESS(rv, rv);
if (!mCanNotify) {
return NS_OK;
}
Sequence<OwningNonNull<PlacesEvent>> notifications;
nsAutoCString utf8spec;
aURI->GetSpec(utf8spec);
int64_t tagsRootId = mDB->GetTagsFolderId();
RefPtr<PlacesBookmarkAddition> bookmark = new PlacesBookmarkAddition();
bookmark->mItemType = TYPE_BOOKMARK;
bookmark->mId = *aNewBookmarkId;
bookmark->mParentId = aFolder;
bookmark->mIndex = index;
bookmark->mUrl.Assign(NS_ConvertUTF8toUTF16(utf8spec));
bookmark->mTitle.Assign(NS_ConvertUTF8toUTF16(title));
bookmark->mDateAdded = dateAdded / 1000;
bookmark->mGuid.Assign(guid);
bookmark->mParentGuid.Assign(folderGuid);
bookmark->mSource = aSource;
bookmark->mIsTagging = grandParentId == tagsRootId;
nsCOMPtr<mozIStorageStatement> stmt = mDB->GetStatement(
"SELECT "
" h.frecency, "
" h.hidden, "
" h.visit_count, "
" h.last_visit_date, "
" (SELECT group_concat(p.title ORDER BY p.title) "
" FROM moz_bookmarks b "
" JOIN moz_bookmarks p ON p.id = b.parent "
" JOIN moz_bookmarks g ON g.id = p.parent "
" WHERE g.guid = " SQL_QUOTE(TAGS_ROOT_GUID)
" AND b.fk = h.id "
" ) AS tags, "
" t.guid, t.id, t.title "
"FROM moz_places h "
"LEFT JOIN moz_bookmarks t ON t.guid = target_folder_guid(h.url) "
"WHERE h.id = :id");
NS_ENSURE_STATE(stmt);
mozStorageStatementScoper scoper(stmt);
rv = stmt->BindInt64ByName("id"_ns, placeId);
NS_ENSURE_SUCCESS(rv, rv);
bool exists;
if (NS_SUCCEEDED(stmt->ExecuteStep(&exists)) && exists) {
int32_t frecency;
rv = stmt->GetInt32(0, &frecency);
NS_ENSURE_SUCCESS(rv, rv);
bookmark->mFrecency = frecency;
int32_t hidden;
rv = stmt->GetInt32(1, &hidden);
NS_ENSURE_SUCCESS(rv, rv);
bookmark->mHidden = !!hidden;
int32_t visitCount;
rv = stmt->GetInt32(2, &visitCount);
NS_ENSURE_SUCCESS(rv, rv);
bookmark->mVisitCount = visitCount;
bool isLastVisitDateNull;
rv = stmt->GetIsNull(3, &isLastVisitDateNull);
NS_ENSURE_SUCCESS(rv, rv);
if (isLastVisitDateNull) {
bookmark->mLastVisitDate.SetNull();
} else {
int64_t lastVisitDate;
rv = stmt->GetInt64(3, &lastVisitDate);
NS_ENSURE_SUCCESS(rv, rv);
bookmark->mLastVisitDate = lastVisitDate;
}
nsString tags;
rv = stmt->GetString(4, tags);
NS_ENSURE_SUCCESS(rv, rv);
bookmark->mTags.Assign(tags);
bool isTargetFolderNull;
rv = stmt->GetIsNull(5, &isTargetFolderNull);
NS_ENSURE_SUCCESS(rv, rv);
if (!isTargetFolderNull) {
nsCString targetFolderGuid;
rv = stmt->GetUTF8String(5, targetFolderGuid);
NS_ENSURE_SUCCESS(rv, rv);
bookmark->mTargetFolderGuid.Assign(targetFolderGuid);
int64_t targetFolderItemId = -1;
rv = stmt->GetInt64(6, &targetFolderItemId);
NS_ENSURE_SUCCESS(rv, rv);
bookmark->mTargetFolderItemId = targetFolderItemId;
nsString targetFolderTitle;
rv = stmt->GetString(7, targetFolderTitle);
NS_ENSURE_SUCCESS(rv, rv);
bookmark->mTargetFolderTitle.Assign(targetFolderTitle);
} else {
bookmark->mTargetFolderGuid.SetIsVoid(true);
bookmark->mTargetFolderItemId = -1;
bookmark->mTargetFolderTitle.SetIsVoid(true);
}
} else {
MOZ_ASSERT(false);
bookmark->mTags.SetIsVoid(true);
bookmark->mFrecency = 0;
bookmark->mHidden = false;
bookmark->mVisitCount = 0;
bookmark->mLastVisitDate.SetNull();
bookmark->mTargetFolderGuid.SetIsVoid(true);
bookmark->mTargetFolderItemId = -1;
bookmark->mTargetFolderTitle.SetIsVoid(true);
}
bool success = !!notifications.AppendElement(bookmark.forget(), fallible);
MOZ_RELEASE_ASSERT(success);
// If the bookmark has been added to a tag container, notify all
// bookmark-folder result nodes which contain a bookmark for the new
// bookmark's url.
if (grandParentId == tagsRootId) {
// Notify a tags change to all bookmarks for this URI.
nsTArray<BookmarkData> bookmarks;
rv = GetBookmarksForURI(aURI, bookmarks);
NS_ENSURE_SUCCESS(rv, rv);
nsTArray<nsString> tags;
rv = GetTags(aURI, tags);
NS_ENSURE_SUCCESS(rv, rv);
for (uint32_t i = 0; i < bookmarks.Length(); ++i) {
// Check that bookmarks doesn't include the current tag itemId.
MOZ_ASSERT(bookmarks[i].id != *aNewBookmarkId);
RefPtr<PlacesBookmarkTags> tagsChanged = new PlacesBookmarkTags();
tagsChanged->mId = bookmarks[i].id;
tagsChanged->mItemType = TYPE_BOOKMARK;
tagsChanged->mUrl.Assign(NS_ConvertUTF8toUTF16(utf8spec));
tagsChanged->mGuid = bookmarks[i].guid;
tagsChanged->mParentGuid = bookmarks[i].parentGuid;
tagsChanged->mTags.Assign(tags);
tagsChanged->mLastModified = bookmarks[i].lastModified / 1000;
tagsChanged->mSource = aSource;
tagsChanged->mIsTagging = false;
success = !!notifications.AppendElement(tagsChanged.forget(), fallible);
MOZ_RELEASE_ASSERT(success);
}
}
PlacesObservers::NotifyListeners(notifications);
return NS_OK;
}
NS_IMETHODIMP
nsNavBookmarks::RemoveItem(int64_t aItemId, uint16_t aSource) {
AUTO_PROFILER_LABEL("nsNavBookmarks::RemoveItem", OTHER);
BookmarkData bookmark;
nsresult rv = FetchItemInfo(aItemId, bookmark);
NS_ENSURE_SUCCESS(rv, rv);
// Check we're not trying to remove a root.
NS_ENSURE_ARG(bookmark.parentId > 0 && bookmark.grandParentId > 0);
mozStorageTransaction transaction(mDB->MainConn(), false);
// XXX Handle the error, bug 1696133.
Unused << NS_WARN_IF(NS_FAILED(transaction.Start()));
if (bookmark.type == TYPE_FOLDER) {
// Remove all of the folder's children.
rv = RemoveFolderChildren(bookmark.id, aSource);
NS_ENSURE_SUCCESS(rv, rv);
}
nsCOMPtr<mozIStorageStatement> stmt =
mDB->GetStatement("DELETE FROM moz_bookmarks WHERE id = :item_id");
NS_ENSURE_STATE(stmt);
mozStorageStatementScoper scoper(stmt);
rv = stmt->BindInt64ByName("item_id"_ns, bookmark.id);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->Execute();
NS_ENSURE_SUCCESS(rv, rv);
// Fix indices in the parent.
if (bookmark.position != DEFAULT_INDEX) {
rv = AdjustIndices(bookmark.parentId, bookmark.position + 1, INT32_MAX, -1);
NS_ENSURE_SUCCESS(rv, rv);
}
int64_t syncChangeDelta = DetermineSyncChangeDelta(aSource);
// Add a tombstone for synced items.
if (syncChangeDelta) {
rv = InsertTombstone(bookmark);
NS_ENSURE_SUCCESS(rv, rv);
}
bookmark.lastModified = RoundedPRNow();
rv = SetItemDateInternal(LAST_MODIFIED, syncChangeDelta, bookmark.parentId,
bookmark.lastModified);
NS_ENSURE_SUCCESS(rv, rv);
// Mark all affected separators as changed
rv = AdjustSeparatorsSyncCounter(bookmark.parentId, bookmark.position,
syncChangeDelta);
NS_ENSURE_SUCCESS(rv, rv);
int64_t tagsRootId = mDB->GetTagsFolderId();
if (bookmark.grandParentId == tagsRootId) {
// If we're removing a tag, increment the change counter for all bookmarks
// with the URI.
rv = AddSyncChangesForBookmarksWithURL(bookmark.url, syncChangeDelta);
NS_ENSURE_SUCCESS(rv, rv);
}
rv = transaction.Commit();
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIURI> uri;
if (bookmark.type == TYPE_BOOKMARK) {
// A broken url should not interrupt the removal process.
(void)NS_NewURI(getter_AddRefs(uri), bookmark.url);
// We cannot assert since some automated tests are checking this path.
NS_WARNING_ASSERTION(uri, "Invalid URI in RemoveItem");
}
if (!mCanNotify) {
return NS_OK;
}
Sequence<OwningNonNull<PlacesEvent>> notifications;
RefPtr<PlacesBookmarkRemoved> bookmarkRef = new PlacesBookmarkRemoved();
bookmarkRef->mItemType = bookmark.type;
bookmarkRef->mId = bookmark.id;
bookmarkRef->mParentId = bookmark.parentId;
bookmarkRef->mIndex = bookmark.position;
if (bookmark.type == TYPE_BOOKMARK) {
bookmarkRef->mUrl.Assign(NS_ConvertUTF8toUTF16(bookmark.url));
}
bookmarkRef->mTitle.Assign(NS_ConvertUTF8toUTF16(bookmark.title));
bookmarkRef->mGuid.Assign(bookmark.guid);
bookmarkRef->mParentGuid.Assign(bookmark.parentGuid);
bookmarkRef->mSource = aSource;
bookmarkRef->mIsTagging =
bookmark.parentId == tagsRootId || bookmark.grandParentId == tagsRootId;
bookmarkRef->mIsDescendantRemoval = false;
bool success = !!notifications.AppendElement(bookmarkRef.forget(), fallible);
MOZ_RELEASE_ASSERT(success);
if (bookmark.type == TYPE_BOOKMARK && bookmark.grandParentId == tagsRootId &&
uri) {
// If the removed bookmark was child of a tag container, notify a tags
// change to all bookmarks for this URI.
nsTArray<BookmarkData> bookmarks;
rv = GetBookmarksForURI(uri, bookmarks);
NS_ENSURE_SUCCESS(rv, rv);
nsAutoCString utf8spec;
uri->GetSpec(utf8spec);
nsTArray<nsString> tags;
rv = GetTags(uri, tags);
NS_ENSURE_SUCCESS(rv, rv);
for (uint32_t i = 0; i < bookmarks.Length(); ++i) {
RefPtr<PlacesBookmarkTags> tagsChanged = new PlacesBookmarkTags();
tagsChanged->mId = bookmarks[i].id;
tagsChanged->mItemType = TYPE_BOOKMARK;
tagsChanged->mUrl.Assign(NS_ConvertUTF8toUTF16(utf8spec));
tagsChanged->mGuid = bookmarks[i].guid;
tagsChanged->mParentGuid = bookmarks[i].parentGuid;
tagsChanged->mTags.Assign(tags);
tagsChanged->mLastModified = bookmarks[i].lastModified / 1000;
tagsChanged->mSource = aSource;
tagsChanged->mIsTagging = false;
success = !!notifications.AppendElement(tagsChanged.forget(), fallible);
MOZ_RELEASE_ASSERT(success);
}
}
PlacesObservers::NotifyListeners(notifications);
return NS_OK;
}
NS_IMETHODIMP
nsNavBookmarks::CreateFolder(int64_t aParent, const nsACString& aTitle,
int32_t aIndex, const nsACString& aGUID,
uint16_t aSource, int64_t* aNewFolderId) {
// NOTE: aParent can be null for root creation, so not checked
NS_ENSURE_ARG_POINTER(aNewFolderId);
NS_ENSURE_ARG_MIN(aIndex, nsINavBookmarksService::DEFAULT_INDEX);
if (!aGUID.IsEmpty() && !IsValidGUID(aGUID)) return NS_ERROR_INVALID_ARG;
// Get the correct index for insertion. This also ensures the parent exists.
int32_t index = aIndex, folderCount;
int64_t grandParentId;
nsAutoCString folderGuid;
nsresult rv =
FetchFolderInfo(aParent, &folderCount, folderGuid, &grandParentId);
NS_ENSURE_SUCCESS(rv, rv);
mozStorageTransaction transaction(mDB->MainConn(), false);
// XXX Handle the error, bug 1696133.
Unused << NS_WARN_IF(NS_FAILED(transaction.Start()));
if (aIndex == nsINavBookmarksService::DEFAULT_INDEX ||
aIndex >= folderCount) {
index = folderCount;
} else {
// Create space for the insertion.
rv = AdjustIndices(aParent, index, INT32_MAX, 1);
NS_ENSURE_SUCCESS(rv, rv);
}
*aNewFolderId = -1;
PRTime dateAdded = RoundedPRNow();
nsAutoCString guid(aGUID);
nsCString title;
TruncateTitle(aTitle, title);
rv = InsertBookmarkInDB(-1, FOLDER, aParent, index, title, dateAdded, 0,
folderGuid, grandParentId, nullptr, aSource,
aNewFolderId, guid);
NS_ENSURE_SUCCESS(rv, rv);
rv = transaction.Commit();
NS_ENSURE_SUCCESS(rv, rv);
int64_t tagsRootId = mDB->GetTagsFolderId();
if (mCanNotify) {
Sequence<OwningNonNull<PlacesEvent>> events;
RefPtr<PlacesBookmarkAddition> folder = new PlacesBookmarkAddition();
folder->mItemType = TYPE_FOLDER;
folder->mId = *aNewFolderId;
folder->mParentId = aParent;
folder->mIndex = index;
folder->mTitle.Assign(NS_ConvertUTF8toUTF16(title));
folder->mDateAdded = dateAdded / 1000;
folder->mGuid.Assign(guid);
folder->mParentGuid.Assign(folderGuid);
folder->mSource = aSource;
folder->mIsTagging = aParent == tagsRootId;
folder->mTags.SetIsVoid(true);
folder->mFrecency = 0;
folder->mHidden = false;
folder->mVisitCount = 0;
folder->mLastVisitDate.SetNull();
folder->mTargetFolderGuid.SetIsVoid(true);
folder->mTargetFolderItemId = -1;
folder->mTargetFolderTitle.SetIsVoid(true);
bool success = !!events.AppendElement(folder.forget(), fallible);
MOZ_RELEASE_ASSERT(success);
PlacesObservers::NotifyListeners(events);
}
return NS_OK;
}
nsresult nsNavBookmarks::GetDescendantChildren(
int64_t aFolderId, const nsACString& aFolderGuid, int64_t aGrandParentId,
nsTArray<BookmarkData>& aFolderChildrenArray) {
// New children will be added from this index on.
uint32_t startIndex = aFolderChildrenArray.Length();
nsresult rv;
{
// Collect children informations.
// Select all children of a given folder, sorted by position.
// This is a LEFT JOIN because not all bookmarks types have a place.
// We construct a result where the first columns exactly match
// kGetInfoIndex_* order, and additionally contains columns for position,
// item_child, and folder_child from moz_bookmarks.
nsCOMPtr<mozIStorageStatement> stmt = mDB->GetStatement(
"SELECT h.id, h.url, b.title, h.rev_host, h.visit_count, "
"h.last_visit_date, null, b.id, b.dateAdded, b.lastModified, "
"b.parent, null, h.frecency, h.hidden, h.guid, null, null, null, "
"b.guid, b.position, b.type, b.fk, b.syncStatus "
"FROM moz_bookmarks b "
"LEFT JOIN moz_places h ON b.fk = h.id "
"WHERE b.parent = :parent "
"ORDER BY b.position ASC");
NS_ENSURE_STATE(stmt);
mozStorageStatementScoper scoper(stmt);
rv = stmt->BindInt64ByName("parent"_ns, aFolderId);
NS_ENSURE_SUCCESS(rv, rv);
bool hasMore;
while (NS_SUCCEEDED(stmt->ExecuteStep(&hasMore)) && hasMore) {
BookmarkData child;
rv = stmt->GetInt64(nsNavHistory::kGetInfoIndex_ItemId, &child.id);
NS_ENSURE_SUCCESS(rv, rv);
child.parentId = aFolderId;
child.grandParentId = aGrandParentId;
child.parentGuid = aFolderGuid;
rv = stmt->GetInt32(kGetChildrenIndex_Type, &child.type);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetInt64(kGetChildrenIndex_PlaceID, &child.placeId);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetInt32(kGetChildrenIndex_Position, &child.position);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetUTF8String(kGetChildrenIndex_Guid, child.guid);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetInt32(kGetChildrenIndex_SyncStatus, &child.syncStatus);
NS_ENSURE_SUCCESS(rv, rv);
if (child.type == TYPE_BOOKMARK) {
rv = stmt->GetUTF8String(nsNavHistory::kGetInfoIndex_URL, child.url);
NS_ENSURE_SUCCESS(rv, rv);
}
bool isNull;
rv = stmt->GetIsNull(nsNavHistory::kGetInfoIndex_Title, &isNull);
NS_ENSURE_SUCCESS(rv, rv);
if (!isNull) {
rv =
stmt->GetUTF8String(nsNavHistory::kGetInfoIndex_Title, child.title);
NS_ENSURE_SUCCESS(rv, rv);
}
// Append item to children's array.
aFolderChildrenArray.AppendElement(child);
}
}
// Recursively call GetDescendantChildren for added folders.
// We start at startIndex since previous folders are checked
// by previous calls to this method.
uint32_t childCount = aFolderChildrenArray.Length();
for (uint32_t i = startIndex; i < childCount; ++i) {
if (aFolderChildrenArray[i].type == TYPE_FOLDER) {
// nsTarray assumes that all children can be memmove()d, thus we can't
// just pass aFolderChildrenArray[i].guid to a method that will change
// the array itself. Otherwise, since it's passed by reference, after a
// memmove() it could point to garbage and cause intermittent crashes.
nsCString guid = aFolderChildrenArray[i].guid;
GetDescendantChildren(aFolderChildrenArray[i].id, guid, aFolderId,
aFolderChildrenArray);
}
}
return NS_OK;
}
nsresult nsNavBookmarks::RemoveFolderChildren(int64_t aFolderId,
uint16_t aSource) {
AUTO_PROFILER_LABEL("nsNavBookmarks::RemoveFolderChilder", OTHER);
NS_ENSURE_ARG_MIN(aFolderId, 1);
BookmarkData folder;
nsresult rv = FetchItemInfo(aFolderId, folder);
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_ARG(folder.type == TYPE_FOLDER);
NS_ENSURE_ARG(folder.parentId != 0);
// Fill folder children array recursively.
nsTArray<BookmarkData> folderChildrenArray;
rv = GetDescendantChildren(folder.id, folder.guid, folder.parentId,
folderChildrenArray);
NS_ENSURE_SUCCESS(rv, rv);
// Build a string of folders whose children will be removed.
nsCString foldersToRemove;
for (uint32_t i = 0; i < folderChildrenArray.Length(); ++i) {
BookmarkData& child = folderChildrenArray[i];
if (child.type == TYPE_FOLDER) {
foldersToRemove.Append(',');
foldersToRemove.AppendInt(child.id);
}
}
int64_t syncChangeDelta = DetermineSyncChangeDelta(aSource);
// Delete items from the database now.
mozStorageTransaction transaction(mDB->MainConn(), false);
// XXX Handle the error, bug 1696133.
Unused << NS_WARN_IF(NS_FAILED(transaction.Start()));
nsCOMPtr<mozIStorageStatement> deleteStatement =
mDB->GetStatement(nsLiteralCString("DELETE FROM moz_bookmarks "
"WHERE parent IN (:parent") +
foldersToRemove + ")"_ns);
NS_ENSURE_STATE(deleteStatement);
mozStorageStatementScoper deleteStatementScoper(deleteStatement);
rv = deleteStatement->BindInt64ByName("parent"_ns, folder.id);
NS_ENSURE_SUCCESS(rv, rv);
rv = deleteStatement->Execute();
NS_ENSURE_SUCCESS(rv, rv);
// Clean up orphan items annotations.
nsCOMPtr<mozIStorageConnection> conn = mDB->MainConn();
if (!conn) {
return NS_ERROR_UNEXPECTED;
}
rv = conn->ExecuteSimpleSQL(
nsLiteralCString("DELETE FROM moz_items_annos "
"WHERE id IN ("
"SELECT a.id from moz_items_annos a "
"LEFT JOIN moz_bookmarks b ON a.item_id = b.id "
"WHERE b.id ISNULL)"));
NS_ENSURE_SUCCESS(rv, rv);
// Set the lastModified date.
rv = SetItemDateInternal(LAST_MODIFIED, syncChangeDelta, folder.id,
RoundedPRNow());
NS_ENSURE_SUCCESS(rv, rv);
int64_t tagsRootId = mDB->GetTagsFolderId();
if (syncChangeDelta) {
nsTArray<TombstoneData> tombstones(folderChildrenArray.Length());
PRTime dateRemoved = RoundedPRNow();
for (uint32_t i = 0; i < folderChildrenArray.Length(); ++i) {
BookmarkData& child = folderChildrenArray[i];
if (NeedsTombstone(child)) {
// Write tombstones for synced children.
TombstoneData childTombstone = {child.guid, dateRemoved};
tombstones.AppendElement(childTombstone);
}
bool isUntagging = child.grandParentId == tagsRootId;
if (isUntagging) {
// Bump the change counter for all tagged bookmarks when removing a tag
// folder.
rv = AddSyncChangesForBookmarksWithURL(child.url, syncChangeDelta);
NS_ENSURE_SUCCESS(rv, rv);
}
}
rv = InsertTombstones(tombstones);
NS_ENSURE_SUCCESS(rv, rv);
}
rv = transaction.Commit();
NS_ENSURE_SUCCESS(rv, rv);
Sequence<OwningNonNull<PlacesEvent>> notifications;
// Call observers in reverse order to serve children before their parent.
for (int32_t i = folderChildrenArray.Length() - 1; i >= 0; --i) {
BookmarkData& child = folderChildrenArray[i];
nsCOMPtr<nsIURI> uri;
if (child.type == TYPE_BOOKMARK) {
// A broken url should not interrupt the removal process.
(void)NS_NewURI(getter_AddRefs(uri), child.url);
// We cannot assert since some automated tests are checking this path.
NS_WARNING_ASSERTION(uri, "Invalid URI in RemoveFolderChildren");
}
if (!mCanNotify) {
return NS_OK;
}
RefPtr<PlacesBookmarkRemoved> bookmark = new PlacesBookmarkRemoved();
bookmark->mItemType = TYPE_BOOKMARK;
bookmark->mId = child.id;
bookmark->mParentId = child.parentId;
bookmark->mIndex = child.position;
bookmark->mUrl.Assign(NS_ConvertUTF8toUTF16(child.url));
bookmark->mTitle.Assign(NS_ConvertUTF8toUTF16(child.title));
bookmark->mGuid.Assign(child.guid);
bookmark->mParentGuid.Assign(child.parentGuid);
bookmark->mSource = aSource;
bookmark->mIsTagging = (child.grandParentId == tagsRootId);
bookmark->mIsDescendantRemoval = (child.grandParentId != tagsRootId);
bool success = !!notifications.AppendElement(bookmark.forget(), fallible);
MOZ_RELEASE_ASSERT(success);
if (child.type == TYPE_BOOKMARK && child.grandParentId == tagsRootId &&
uri) {
// If the removed bookmark was a child of a tag container, notify all
// bookmark-folder result nodes which contain a bookmark for the removed
// bookmark's url.
nsTArray<BookmarkData> bookmarks;
rv = GetBookmarksForURI(uri, bookmarks);
NS_ENSURE_SUCCESS(rv, rv);
nsAutoCString utf8spec;
uri->GetSpec(utf8spec);
nsTArray<nsString> tags;
rv = GetTags(uri, tags);
NS_ENSURE_SUCCESS(rv, rv);
for (uint32_t i = 0; i < bookmarks.Length(); ++i) {
RefPtr<PlacesBookmarkTags> tagsChanged = new PlacesBookmarkTags();
tagsChanged->mId = bookmarks[i].id;
tagsChanged->mItemType = TYPE_BOOKMARK;
tagsChanged->mUrl.Assign(NS_ConvertUTF8toUTF16(utf8spec));
tagsChanged->mGuid = bookmarks[i].guid;
tagsChanged->mParentGuid = bookmarks[i].parentGuid;
tagsChanged->mTags.Assign(tags);
tagsChanged->mLastModified = bookmarks[i].lastModified / 1000;
tagsChanged->mSource = aSource;
tagsChanged->mIsTagging = false;
success = !!notifications.AppendElement(tagsChanged.forget(), fallible);
MOZ_RELEASE_ASSERT(success);
}
}
}
if (notifications.Length()) {
PlacesObservers::NotifyListeners(notifications);
}
return NS_OK;
}
nsresult nsNavBookmarks::FetchItemInfo(int64_t aItemId,
BookmarkData& _bookmark) {
// LEFT JOIN since not all bookmarks have an associated place.
nsCOMPtr<mozIStorageStatement> stmt = mDB->GetStatement(
"SELECT b.id, h.url, b.title, b.position, b.fk, b.parent, b.type, "
"b.dateAdded, b.lastModified, b.guid, t.guid, t.parent, "
"b.syncStatus "
"FROM moz_bookmarks b "
"LEFT JOIN moz_bookmarks t ON t.id = b.parent "
"LEFT JOIN moz_places h ON h.id = b.fk "
"WHERE b.id = :item_id");
NS_ENSURE_STATE(stmt);
mozStorageStatementScoper scoper(stmt);
nsresult rv = stmt->BindInt64ByName("item_id"_ns, aItemId);
NS_ENSURE_SUCCESS(rv, rv);
bool hasResult;
rv = stmt->ExecuteStep(&hasResult);
NS_ENSURE_SUCCESS(rv, rv);
if (!hasResult) {
return NS_ERROR_INVALID_ARG;
}
_bookmark.id = aItemId;
rv = stmt->GetUTF8String(1, _bookmark.url);
NS_ENSURE_SUCCESS(rv, rv);
bool isNull;
rv = stmt->GetIsNull(2, &isNull);
NS_ENSURE_SUCCESS(rv, rv);
if (!isNull) {
rv = stmt->GetUTF8String(2, _bookmark.title);
NS_ENSURE_SUCCESS(rv, rv);
}
rv = stmt->GetInt32(3, &_bookmark.position);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetInt64(4, &_bookmark.placeId);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetInt64(5, &_bookmark.parentId);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetInt32(6, &_bookmark.type);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetInt64(7, reinterpret_cast<int64_t*>(&_bookmark.dateAdded));
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetInt64(8, reinterpret_cast<int64_t*>(&_bookmark.lastModified));
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetUTF8String(9, _bookmark.guid);
NS_ENSURE_SUCCESS(rv, rv);
// Getting properties of the root would show no parent.
rv = stmt->GetIsNull(10, &isNull);
NS_ENSURE_SUCCESS(rv, rv);
if (!isNull) {
rv = stmt->GetUTF8String(10, _bookmark.parentGuid);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetInt64(11, &_bookmark.grandParentId);
NS_ENSURE_SUCCESS(rv, rv);
} else {
_bookmark.grandParentId = -1;
}
rv = stmt->GetInt32(12, &_bookmark.syncStatus);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
nsresult nsNavBookmarks::FetchItemInfo(const nsCString& aGUID,
BookmarkData& _bookmark) {
// LEFT JOIN since not all bookmarks have an associated place.
nsCOMPtr<mozIStorageStatement> stmt = mDB->GetStatement(
"SELECT b.id, h.url, b.title, b.position, b.fk, b.parent, b.type, "
"b.dateAdded, b.lastModified, t.guid, t.parent, "
"b.syncStatus "
"FROM moz_bookmarks b "
"LEFT JOIN moz_bookmarks t ON t.id = b.parent "
"LEFT JOIN moz_places h ON h.id = b.fk "
"WHERE b.guid = :item_guid");
NS_ENSURE_STATE(stmt);
mozStorageStatementScoper scoper(stmt);
nsresult rv = stmt->BindUTF8StringByName("item_guid"_ns, aGUID);
NS_ENSURE_SUCCESS(rv, rv);
_bookmark.guid = aGUID;
bool hasResult;
rv = stmt->ExecuteStep(&hasResult);
NS_ENSURE_SUCCESS(rv, rv);
if (!hasResult) {
return NS_ERROR_INVALID_ARG;
}
rv = stmt->GetInt64(0, &_bookmark.id);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetUTF8String(1, _bookmark.url);
NS_ENSURE_SUCCESS(rv, rv);
bool isNull;
rv = stmt->GetIsNull(2, &isNull);
NS_ENSURE_SUCCESS(rv, rv);
if (!isNull) {
rv = stmt->GetUTF8String(2, _bookmark.title);
NS_ENSURE_SUCCESS(rv, rv);
}
rv = stmt->GetInt32(3, &_bookmark.position);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetInt64(4, &_bookmark.placeId);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetInt64(5, &_bookmark.parentId);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetInt32(6, &_bookmark.type);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetInt64(7, reinterpret_cast<int64_t*>(&_bookmark.dateAdded));
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetInt64(8, reinterpret_cast<int64_t*>(&_bookmark.lastModified));
NS_ENSURE_SUCCESS(rv, rv);
// Getting properties of the root would show no parent.
rv = stmt->GetIsNull(9, &isNull);
NS_ENSURE_SUCCESS(rv, rv);
if (!isNull) {
rv = stmt->GetUTF8String(9, _bookmark.parentGuid);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetInt64(10, &_bookmark.grandParentId);
NS_ENSURE_SUCCESS(rv, rv);
} else {
_bookmark.grandParentId = -1;
}
rv = stmt->GetInt32(11, &_bookmark.syncStatus);
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
nsresult nsNavBookmarks::SetItemDateInternal(enum BookmarkDate aDateType,
int64_t aSyncChangeDelta,
int64_t aItemId, PRTime aValue) {
aValue = RoundToMilliseconds(aValue);
nsCOMPtr<mozIStorageStatement> stmt = mDB->GetStatement(
"UPDATE moz_bookmarks SET lastModified = :date, "
"syncChangeCounter = syncChangeCounter + :delta "
"WHERE id = :item_id");
NS_ENSURE_STATE(stmt);
mozStorageStatementScoper scoper(stmt);
nsresult rv = stmt->BindInt64ByName("date"_ns, aValue);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->BindInt64ByName("item_id"_ns, aItemId);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->BindInt64ByName("delta"_ns, aSyncChangeDelta);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->Execute();
NS_ENSURE_SUCCESS(rv, rv);
// note, we are not notifying the observers
// that the item has changed.
return NS_OK;
}
NS_IMETHODIMP
nsNavBookmarks::SetItemLastModified(int64_t aItemId, PRTime aLastModified,
uint16_t aSource) {
NS_ENSURE_ARG_MIN(aItemId, 1);
BookmarkData bookmark;
nsresult rv = FetchItemInfo(aItemId, bookmark);
NS_ENSURE_SUCCESS(rv, rv);
int64_t tagsRootId = mDB->GetTagsFolderId();
bool isTagging = bookmark.grandParentId == tagsRootId;
int64_t syncChangeDelta = DetermineSyncChangeDelta(aSource);
// Round here so that we notify with the right value.
bookmark.lastModified = RoundToMilliseconds(aLastModified);
if (isTagging) {
// If we're changing a tag, bump the change counter for all tagged
// bookmarks. We use a separate code path to avoid a transaction for
// non-tags.
mozStorageTransaction transaction(mDB->MainConn(), false);
// XXX Handle the error, bug 1696133.
Unused << NS_WARN_IF(NS_FAILED(transaction.Start()));
rv = SetItemDateInternal(LAST_MODIFIED, syncChangeDelta, bookmark.id,
bookmark.lastModified);
NS_ENSURE_SUCCESS(rv, rv);
rv = AddSyncChangesForBookmarksWithURL(bookmark.url, syncChangeDelta);
NS_ENSURE_SUCCESS(rv, rv);
rv = transaction.Commit();
NS_ENSURE_SUCCESS(rv, rv);
} else {
rv = SetItemDateInternal(LAST_MODIFIED, syncChangeDelta, bookmark.id,
bookmark.lastModified);
NS_ENSURE_SUCCESS(rv, rv);
}
// Note: mDBSetItemDateAdded also sets lastModified to aDateAdded.
if (mCanNotify) {
Sequence<OwningNonNull<PlacesEvent>> events;
RefPtr<PlacesBookmarkTime> timeChanged = new PlacesBookmarkTime();
timeChanged->mId = bookmark.id;
timeChanged->mItemType = bookmark.type;
timeChanged->mUrl.Assign(NS_ConvertUTF8toUTF16(bookmark.url));
timeChanged->mGuid = bookmark.guid;
timeChanged->mParentGuid = bookmark.parentGuid;
timeChanged->mDateAdded = bookmark.dateAdded / 1000;
timeChanged->mLastModified = bookmark.lastModified / 1000;
timeChanged->mSource = aSource;
timeChanged->mIsTagging =
bookmark.parentId == tagsRootId || bookmark.grandParentId == tagsRootId;
bool success = !!events.AppendElement(timeChanged.forget(), fallible);
MOZ_RELEASE_ASSERT(success);
PlacesObservers::NotifyListeners(events);
}
return NS_OK;
}
nsresult nsNavBookmarks::AddSyncChangesForBookmarksWithURL(
const nsACString& aURL, int64_t aSyncChangeDelta) {
if (!aSyncChangeDelta) {
return NS_OK;
}
nsCOMPtr<nsIURI> uri;
nsresult rv = NS_NewURI(getter_AddRefs(uri), aURL);
if (NS_WARN_IF(NS_FAILED(rv))) {
// Ignore sync changes for invalid URLs.
return NS_OK;
}
return AddSyncChangesForBookmarksWithURI(uri, aSyncChangeDelta);
}
nsresult nsNavBookmarks::AddSyncChangesForBookmarksWithURI(
nsIURI* aURI, int64_t aSyncChangeDelta) {
if (NS_WARN_IF(!aURI) || !aSyncChangeDelta) {
// Ignore sync changes for invalid URIs.
return NS_OK;
}
nsCOMPtr<mozIStorageStatement> statement = mDB->GetStatement(
"UPDATE moz_bookmarks SET "
"syncChangeCounter = syncChangeCounter + :delta "
"WHERE type = :type AND "
"fk = (SELECT id FROM moz_places WHERE url_hash = hash(:url) AND "
"url = :url)");
NS_ENSURE_STATE(statement);
mozStorageStatementScoper scoper(statement);
nsresult rv = statement->BindInt64ByName("delta"_ns, aSyncChangeDelta);
NS_ENSURE_SUCCESS(rv, rv);
rv = statement->BindInt64ByName("type"_ns,
nsINavBookmarksService::TYPE_BOOKMARK);
NS_ENSURE_SUCCESS(rv, rv);
rv = URIBinder::Bind(statement, "url"_ns, aURI);
NS_ENSURE_SUCCESS(rv, rv);
return statement->Execute();
}
nsresult nsNavBookmarks::AddSyncChangesForBookmarksInFolder(
int64_t aFolderId, int64_t aSyncChangeDelta) {
if (!aSyncChangeDelta) {
return NS_OK;
}
nsCOMPtr<mozIStorageStatement> statement = mDB->GetStatement(
"UPDATE moz_bookmarks SET "
"syncChangeCounter = syncChangeCounter + :delta "
"WHERE type = :type AND "
"fk = (SELECT fk FROM moz_bookmarks WHERE parent = :parent)");
NS_ENSURE_STATE(statement);
mozStorageStatementScoper scoper(statement);
nsresult rv = statement->BindInt64ByName("delta"_ns, aSyncChangeDelta);
NS_ENSURE_SUCCESS(rv, rv);
rv = statement->BindInt64ByName("type"_ns,
nsINavBookmarksService::TYPE_BOOKMARK);
NS_ENSURE_SUCCESS(rv, rv);
rv = statement->BindInt64ByName("parent"_ns, aFolderId);
NS_ENSURE_SUCCESS(rv, rv);
rv = statement->Execute();
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
nsresult nsNavBookmarks::InsertTombstone(const BookmarkData& aBookmark) {
if (!NeedsTombstone(aBookmark)) {
return NS_OK;
}
nsCOMPtr<mozIStorageStatement> stmt = mDB->GetStatement(
"INSERT INTO moz_bookmarks_deleted (guid, dateRemoved) "
"VALUES (:guid, :date_removed)");
NS_ENSURE_STATE(stmt);
mozStorageStatementScoper scoper(stmt);
nsresult rv = stmt->BindUTF8StringByName("guid"_ns, aBookmark.guid);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->BindInt64ByName("date_removed"_ns, RoundedPRNow());
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->Execute();
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
nsresult nsNavBookmarks::InsertTombstones(
const nsTArray<TombstoneData>& aTombstones) {
if (aTombstones.IsEmpty()) {
return NS_OK;
}
nsCOMPtr<mozIStorageConnection> conn = mDB->MainConn();
NS_ENSURE_STATE(conn);
int32_t variableLimit = 0;
nsresult rv = conn->GetVariableLimit(&variableLimit);
NS_ENSURE_SUCCESS(rv, rv);
size_t maxRowsPerChunk = variableLimit / 2;
for (uint32_t startIndex = 0; startIndex < aTombstones.Length();
startIndex += maxRowsPerChunk) {
size_t rowsPerChunk =
std::min(maxRowsPerChunk, aTombstones.Length() - startIndex);
// Build a query to insert all tombstones in a single statement, chunking to
// avoid the SQLite bound parameter limit.
nsAutoCString tombstonesToInsert;
tombstonesToInsert.AppendLiteral("VALUES (?, ?)");
for (uint32_t i = 1; i < rowsPerChunk; ++i) {
tombstonesToInsert.AppendLiteral(", (?, ?)");
}
#ifdef DEBUG
MOZ_ASSERT(tombstonesToInsert.CountChar('?') == rowsPerChunk * 2,
"Expected one binding param per column for each tombstone");
#endif
nsCOMPtr<mozIStorageStatement> stmt =
mDB->GetStatement(nsLiteralCString("INSERT INTO moz_bookmarks_deleted "
"(guid, dateRemoved) ") +
tombstonesToInsert);
NS_ENSURE_STATE(stmt);
mozStorageStatementScoper scoper(stmt);
uint32_t paramIndex = 0;
for (uint32_t i = 0; i < rowsPerChunk; ++i) {
const TombstoneData& tombstone = aTombstones[startIndex + i];
rv = stmt->BindUTF8StringByIndex(paramIndex++, tombstone.guid);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->BindInt64ByIndex(paramIndex++, tombstone.dateRemoved);
NS_ENSURE_SUCCESS(rv, rv);
}
rv = stmt->Execute();
NS_ENSURE_SUCCESS(rv, rv);
}
return NS_OK;
}
nsresult nsNavBookmarks::RemoveTombstone(const nsACString& aGUID) {
nsCOMPtr<mozIStorageStatement> stmt =
mDB->GetStatement("DELETE FROM moz_bookmarks_deleted WHERE guid = :guid");
NS_ENSURE_STATE(stmt);
mozStorageStatementScoper scoper(stmt);
nsresult rv = stmt->BindUTF8StringByName("guid"_ns, aGUID);
NS_ENSURE_SUCCESS(rv, rv);
return stmt->Execute();
}
NS_IMETHODIMP
nsNavBookmarks::SetItemTitle(int64_t aItemId, const nsACString& aTitle,
uint16_t aSource) {
NS_ENSURE_ARG_MIN(aItemId, 1);
BookmarkData bookmark;
nsresult rv = FetchItemInfo(aItemId, bookmark);
NS_ENSURE_SUCCESS(rv, rv);
int64_t tagsRootId = mDB->GetTagsFolderId();
bool isChangingTagFolder = bookmark.parentId == tagsRootId;
int64_t syncChangeDelta = DetermineSyncChangeDelta(aSource);
nsAutoCString title;
TruncateTitle(aTitle, title);
if (isChangingTagFolder) {
// If we're changing the title of a tag folder, bump the change counter
// for all tagged bookmarks. We use a separate code path to avoid a
// transaction for non-tags.
mozStorageTransaction transaction(mDB->MainConn(), false);
// XXX Handle the error, bug 1696133.
Unused << NS_WARN_IF(NS_FAILED(transaction.Start()));
rv = SetItemTitleInternal(bookmark, title, syncChangeDelta);
NS_ENSURE_SUCCESS(rv, rv);
rv = AddSyncChangesForBookmarksInFolder(bookmark.id, syncChangeDelta);
NS_ENSURE_SUCCESS(rv, rv);
rv = transaction.Commit();
NS_ENSURE_SUCCESS(rv, rv);
} else {
rv = SetItemTitleInternal(bookmark, title, syncChangeDelta);
NS_ENSURE_SUCCESS(rv, rv);
}
if (mCanNotify) {
Sequence<OwningNonNull<PlacesEvent>> events;
RefPtr<PlacesBookmarkTitle> titleChanged = new PlacesBookmarkTitle();
titleChanged->mId = bookmark.id;
titleChanged->mItemType = bookmark.type;
titleChanged->mUrl.Assign(NS_ConvertUTF8toUTF16(bookmark.url));
titleChanged->mGuid = bookmark.guid;
titleChanged->mParentGuid = bookmark.parentGuid;
titleChanged->mTitle.Assign(NS_ConvertUTF8toUTF16(title));
titleChanged->mLastModified = bookmark.lastModified / 1000;
titleChanged->mSource = aSource;
titleChanged->mIsTagging =
bookmark.parentId == tagsRootId || bookmark.grandParentId == tagsRootId;
bool success = !!events.AppendElement(titleChanged.forget(), fallible);
MOZ_RELEASE_ASSERT(success);
PlacesObservers::NotifyListeners(events);
}
return NS_OK;
}
nsresult nsNavBookmarks::SetItemTitleInternal(BookmarkData& aBookmark,
const nsACString& aTitle,
int64_t aSyncChangeDelta) {
nsCOMPtr<mozIStorageStatement> statement = mDB->GetStatement(
"UPDATE moz_bookmarks SET "
"title = :item_title, lastModified = :date, "
"syncChangeCounter = syncChangeCounter + :delta "
"WHERE id = :item_id");
NS_ENSURE_STATE(statement);
mozStorageStatementScoper scoper(statement);
nsresult rv;
if (aTitle.IsEmpty()) {
rv = statement->BindNullByName("item_title"_ns);
} else {
rv = statement->BindUTF8StringByName("item_title"_ns, aTitle);
}
NS_ENSURE_SUCCESS(rv, rv);
aBookmark.lastModified = RoundToMilliseconds(RoundedPRNow());
rv = statement->BindInt64ByName("date"_ns, aBookmark.lastModified);
NS_ENSURE_SUCCESS(rv, rv);
rv = statement->BindInt64ByName("item_id"_ns, aBookmark.id);
NS_ENSURE_SUCCESS(rv, rv);
rv = statement->BindInt64ByName("delta"_ns, aSyncChangeDelta);
NS_ENSURE_SUCCESS(rv, rv);
rv = statement->Execute();
NS_ENSURE_SUCCESS(rv, rv);
return NS_OK;
}
NS_IMETHODIMP
nsNavBookmarks::GetItemTitle(int64_t aItemId, nsACString& _title) {
NS_ENSURE_ARG_MIN(aItemId, 1);
BookmarkData bookmark;
nsresult rv = FetchItemInfo(aItemId, bookmark);
NS_ENSURE_SUCCESS(rv, rv);
_title = bookmark.title;
return NS_OK;
}
nsresult nsNavBookmarks::QueryFolderChildren(
int64_t aFolderId, nsNavHistoryQueryOptions* aOptions,
nsCOMArray<nsNavHistoryResultNode>* aChildren) {
NS_ENSURE_ARG_POINTER(aOptions);
NS_ENSURE_ARG_POINTER(aChildren);
// Select all children of a given folder, sorted by position.
// This is a LEFT JOIN because not all bookmarks types have a place.
// We construct a result where the first columns exactly match those returned
// by mDBGetURLPageInfo, and additionally contains columns for position,
// item_child, and folder_child from moz_bookmarks.
nsCOMPtr<mozIStorageStatement> stmt = mDB->GetStatement(
nsNavHistory::GetTagsSqlFragment(
nsINavHistoryQueryOptions::QUERY_TYPE_BOOKMARKS,
aOptions->ExcludeItems()) +
"SELECT "
" h.id, h.url, b.title, h.rev_host, h.visit_count, "
" h.last_visit_date, null, b.id, b.dateAdded, b.lastModified, b.parent, "
" (SELECT tags FROM tagged WHERE place_id = h.id) AS tags, "
" h.frecency, h.hidden, h.guid, null, null, null, "
" b.guid, b.position, b.type, b.fk, t.guid, t.id, t.title "
"FROM moz_bookmarks b "
"LEFT JOIN moz_places h ON b.fk = h.id "
"LEFT JOIN moz_bookmarks t ON t.guid = target_folder_guid(h.url) "
"WHERE b.parent = :parent "
"AND (NOT :excludeItems OR "
"b.type = :folder OR "
"h.url_hash BETWEEN hash('place', 'prefix_lo') "
" AND hash('place', 'prefix_hi')) "
"ORDER BY b.position ASC"_ns);
NS_ENSURE_STATE(stmt);
mozStorageStatementScoper scoper(stmt);
nsresult rv = stmt->BindInt64ByName("parent"_ns, aFolderId);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->BindInt32ByName("folder"_ns, TYPE_FOLDER);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->BindInt32ByName("excludeItems"_ns, aOptions->ExcludeItems());
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<mozIStorageValueArray> row = do_QueryInterface(stmt, &rv);
NS_ENSURE_SUCCESS(rv, rv);
int32_t index = -1;
bool hasResult;
while (NS_SUCCEEDED(stmt->ExecuteStep(&hasResult)) && hasResult) {
rv = ProcessFolderNodeRow(row, aOptions, aChildren, index);
NS_ENSURE_SUCCESS(rv, rv);
}
return NS_OK;
}
nsresult nsNavBookmarks::ProcessFolderNodeRow(
mozIStorageValueArray* aRow, nsNavHistoryQueryOptions* aOptions,
nsCOMArray<nsNavHistoryResultNode>* aChildren, int32_t& aCurrentIndex) {
NS_ENSURE_ARG_POINTER(aRow);
NS_ENSURE_ARG_POINTER(aOptions);
NS_ENSURE_ARG_POINTER(aChildren);
// The results will be in order of aCurrentIndex. Even if we don't add a node
// because it was excluded, we need to count its index, so do that before
// doing anything else.
aCurrentIndex++;
int32_t itemType;
nsresult rv = aRow->GetInt32(kGetChildrenIndex_Type, &itemType);
NS_ENSURE_SUCCESS(rv, rv);
int64_t id;
rv = aRow->GetInt64(nsNavHistory::kGetInfoIndex_ItemId, &id);
NS_ENSURE_SUCCESS(rv, rv);
RefPtr<nsNavHistoryResultNode> node;
if (itemType == TYPE_BOOKMARK) {
nsNavHistory* history = nsNavHistory::GetHistoryService();
NS_ENSURE_TRUE(history, NS_ERROR_OUT_OF_MEMORY);
rv = history->RowToResult(aRow, aOptions, getter_AddRefs(node));
NS_ENSURE_SUCCESS(rv, rv);
uint32_t nodeType;
node->GetType(&nodeType);
if (nodeType == nsINavHistoryResultNode::RESULT_TYPE_QUERY &&
aOptions->ExcludeQueries()) {
return NS_OK;
}
} else if (itemType == TYPE_FOLDER) {
nsAutoCString title;
bool isNull;
rv = aRow->GetIsNull(nsNavHistory::kGetInfoIndex_Title, &isNull);
NS_ENSURE_SUCCESS(rv, rv);
if (!isNull) {
rv = aRow->GetUTF8String(nsNavHistory::kGetInfoIndex_Title, title);
NS_ENSURE_SUCCESS(rv, rv);
}
nsAutoCString guid;
rv = aRow->GetUTF8String(kGetChildrenIndex_Guid, guid);
NS_ENSURE_SUCCESS(rv, rv);
// Don't use options from the parent to build the new folder node, it will
// inherit those later when it's inserted in the result.
node = new nsNavHistoryFolderResultNode(id, guid, id, guid, title,
new nsNavHistoryQueryOptions());
rv = aRow->GetInt64(nsNavHistory::kGetInfoIndex_ItemDateAdded,
reinterpret_cast<int64_t*>(&node->mDateAdded));
NS_ENSURE_SUCCESS(rv, rv);
rv = aRow->GetInt64(nsNavHistory::kGetInfoIndex_ItemLastModified,
reinterpret_cast<int64_t*>(&node->mLastModified));
NS_ENSURE_SUCCESS(rv, rv);
} else {
// This is a separator.
node = new nsNavHistorySeparatorResultNode();
node->mItemId = id;
rv = aRow->GetUTF8String(kGetChildrenIndex_Guid, node->mBookmarkGuid);
NS_ENSURE_SUCCESS(rv, rv);
rv = aRow->GetInt64(nsNavHistory::kGetInfoIndex_ItemDateAdded,
reinterpret_cast<int64_t*>(&node->mDateAdded));
NS_ENSURE_SUCCESS(rv, rv);
rv = aRow->GetInt64(nsNavHistory::kGetInfoIndex_ItemLastModified,
reinterpret_cast<int64_t*>(&node->mLastModified));
NS_ENSURE_SUCCESS(rv, rv);
}
// Store the index of the node within this container. Note that this is not
// moz_bookmarks.position.
node->mBookmarkIndex = aCurrentIndex;
NS_ENSURE_TRUE(aChildren->AppendObject(node), NS_ERROR_OUT_OF_MEMORY);
return NS_OK;
}
nsresult nsNavBookmarks::QueryFolderChildrenAsync(
nsNavHistoryFolderResultNode* aNode,
mozIStoragePendingStatement** _pendingStmt) {
NS_ENSURE_ARG_POINTER(aNode);
NS_ENSURE_ARG_POINTER(_pendingStmt);
// Select all children of a given folder, sorted by position.
// This is a LEFT JOIN because not all bookmarks types have a place.
// We construct a result where the first columns exactly match those returned
// by mDBGetURLPageInfo, and additionally contains columns for position,
// item_child, and folder_child from moz_bookmarks.
nsCOMPtr<mozIStorageAsyncStatement> stmt = mDB->GetAsyncStatement(
"SELECT h.id, h.url, b.title, h.rev_host, h.visit_count, "
"h.last_visit_date, null, b.id, b.dateAdded, b.lastModified, "
"b.parent, null, h.frecency, h.hidden, h.guid, null, null, null, "
"b.guid, b.position, b.type, b.fk, t.guid, t.id, t.title "
"FROM moz_bookmarks b "
"LEFT JOIN moz_places h ON b.fk = h.id "
"LEFT JOIN moz_bookmarks t ON t.guid = target_folder_guid(h.url) "
"WHERE b.parent = :parent "
"AND (NOT :excludeItems OR "
"b.type = :folder OR "
"h.url_hash BETWEEN hash('place', 'prefix_lo') AND hash('place', "
"'prefix_hi')) "
"ORDER BY b.position ASC");
NS_ENSURE_STATE(stmt);
nsresult rv = stmt->BindInt64ByName("parent"_ns, aNode->mTargetFolderItemId);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->BindInt32ByName("folder"_ns, TYPE_FOLDER);
NS_ENSURE_SUCCESS(rv, rv);
rv =
stmt->BindInt32ByName("excludeItems"_ns, aNode->mOptions->ExcludeItems());
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<mozIStoragePendingStatement> pendingStmt;
rv = stmt->ExecuteAsync(aNode, getter_AddRefs(pendingStmt));
NS_ENSURE_SUCCESS(rv, rv);
NS_IF_ADDREF(*_pendingStmt = pendingStmt);
return NS_OK;
}
nsresult nsNavBookmarks::FetchFolderInfo(int64_t aFolderId,
int32_t* _folderCount,
nsACString& _guid,
int64_t* _parentId) {
*_folderCount = 0;
*_parentId = -1;
// This query has to always return results, so it can't be written as a join,
// though a left join of 2 subqueries would have the same cost.
nsCOMPtr<mozIStorageStatement> stmt = mDB->GetStatement(
"SELECT count(*), "
"(SELECT guid FROM moz_bookmarks WHERE id = :parent), "
"(SELECT parent FROM moz_bookmarks WHERE id = :parent) "
"FROM moz_bookmarks "
"WHERE parent = :parent");
NS_ENSURE_STATE(stmt);
mozStorageStatementScoper scoper(stmt);
nsresult rv = stmt->BindInt64ByName("parent"_ns, aFolderId);
NS_ENSURE_SUCCESS(rv, rv);
bool hasResult;
rv = stmt->ExecuteStep(&hasResult);
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_TRUE(hasResult, NS_ERROR_UNEXPECTED);
// Ensure that the folder we are looking for exists.
// Can't rely only on parent, since the root has parent 0, that doesn't exist.
bool isNull;
rv = stmt->GetIsNull(2, &isNull);
NS_ENSURE_TRUE(NS_SUCCEEDED(rv) && (!isNull || aFolderId == 0),
NS_ERROR_INVALID_ARG);
rv = stmt->GetInt32(0, _folderCount);
NS_ENSURE_SUCCESS(rv, rv);
if (!isNull) {
rv = stmt->GetUTF8String(1, _guid);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetInt64(2, _parentId);
NS_ENSURE_SUCCESS(rv, rv);
}
return NS_OK;
}
nsresult nsNavBookmarks::GetBookmarksForURI(
nsIURI* aURI, nsTArray<BookmarkData>& aBookmarks) {
NS_ENSURE_ARG(aURI);
// Double ordering covers possible lastModified ties, that could happen when
// importing, syncing or due to extensions.
// Note: not using a JOIN is cheaper in this case.
nsCOMPtr<mozIStorageStatement> stmt = mDB->GetStatement(
"/* do not warn (bug 1175249) */ "
"SELECT b.id, b.guid, b.parent, b.lastModified, t.guid, t.parent, "
"b.syncStatus "
"FROM moz_bookmarks b "
"JOIN moz_bookmarks t on t.id = b.parent "
"WHERE b.fk = (SELECT id FROM moz_places WHERE url_hash = "
"hash(:page_url) AND url = :page_url) "
"ORDER BY b.lastModified DESC, b.id DESC ");
NS_ENSURE_STATE(stmt);
mozStorageStatementScoper scoper(stmt);
nsresult rv = URIBinder::Bind(stmt, "page_url"_ns, aURI);
NS_ENSURE_SUCCESS(rv, rv);
int64_t tagsRootId = mDB->GetTagsFolderId();
bool more;
nsAutoString tags;
while (NS_SUCCEEDED((rv = stmt->ExecuteStep(&more))) && more) {
// Skip tags.
int64_t grandParentId;
nsresult rv = stmt->GetInt64(5, &grandParentId);
NS_ENSURE_SUCCESS(rv, rv);
if (grandParentId == tagsRootId) {
continue;
}
BookmarkData bookmark;
bookmark.grandParentId = grandParentId;
rv = stmt->GetInt64(0, &bookmark.id);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetUTF8String(1, bookmark.guid);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetInt64(2, &bookmark.parentId);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetInt64(3, reinterpret_cast<int64_t*>(&bookmark.lastModified));
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetUTF8String(4, bookmark.parentGuid);
NS_ENSURE_SUCCESS(rv, rv);
rv = stmt->GetInt32(6, &bookmark.syncStatus);
NS_ENSURE_SUCCESS(rv, rv);
aBookmarks.AppendElement(bookmark);
}
return NS_OK;
}
////////////////////////////////////////////////////////////////////////////////
//// nsIObserver
NS_IMETHODIMP
nsNavBookmarks::Observe(nsISupports* aSubject, const char* aTopic,
const char16_t* aData) {
NS_ASSERTION(NS_IsMainThread(), "This can only be called on the main thread");
if (strcmp(aTopic, TOPIC_PLACES_CONNECTION_CLOSED) == 0) {
// Don't even try to notify observers from this point on, the category
// cache would init services that could try to use our APIs.
mCanNotify = false;
}
return NS_OK;
}
|