Source code

Revision control

Other Tools

1
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
2
/* This Source Code Form is subject to the terms of the Mozilla Public
3
* License, v. 2.0. If a copy of the MPL was not distributed with this
4
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5
6
var EXPORTED_SYMBOLS = ["PlacesUtils"];
7
8
const { XPCOMUtils } = ChromeUtils.import(
10
);
11
const { AppConstants } = ChromeUtils.import(
13
);
14
15
XPCOMUtils.defineLazyGlobalGetters(this, ["URL"]);
16
17
XPCOMUtils.defineLazyModuleGetters(this, {
24
});
25
26
XPCOMUtils.defineLazyGetter(this, "MOZ_ACTION_REGEX", () => {
27
return /^moz-action:([^,]+),(.*)$/;
28
});
29
30
// On Mac OSX, the transferable system converts "\r\n" to "\n\n", where
31
// we really just want "\n". On other platforms, the transferable system
32
// converts "\r\n" to "\n".
33
const NEWLINE = AppConstants.platform == "macosx" ? "\n" : "\r\n";
34
35
// Timers resolution is not always good, it can have a 16ms precision on Win.
36
const TIMERS_RESOLUTION_SKEW_MS = 16;
37
38
function QI_node(aNode, aIID) {
39
try {
40
return aNode.QueryInterface(aIID);
41
} catch (ex) {}
42
return null;
43
}
44
function asContainer(aNode) {
45
return QI_node(aNode, Ci.nsINavHistoryContainerResultNode);
46
}
47
function asQuery(aNode) {
48
return QI_node(aNode, Ci.nsINavHistoryQueryResultNode);
49
}
50
51
/**
52
* Sends a bookmarks notification through the given observers.
53
*
54
* @param observers
55
* array of nsINavBookmarkObserver objects.
56
* @param notification
57
* the notification name.
58
* @param args
59
* array of arguments to pass to the notification.
60
*/
61
function notify(observers, notification, args) {
62
for (let observer of observers) {
63
try {
64
observer[notification](...args);
65
} catch (ex) {}
66
}
67
}
68
69
/**
70
* Sends a keyword change notification.
71
*
72
* @param url
73
* the url to notify about.
74
* @param keyword
75
* The keyword to notify, or empty string if a keyword was removed.
76
*/
77
async function notifyKeywordChange(url, keyword, source) {
78
// Notify bookmarks about the removal.
79
let bookmarks = [];
80
await PlacesUtils.bookmarks.fetch({ url }, b => bookmarks.push(b));
81
for (let bookmark of bookmarks) {
82
let ids = await PlacesUtils.promiseManyItemIds([
83
bookmark.guid,
84
bookmark.parentGuid,
85
]);
86
bookmark.id = ids.get(bookmark.guid);
87
bookmark.parentId = ids.get(bookmark.parentGuid);
88
}
89
let observers = PlacesUtils.bookmarks.getObservers();
90
for (let bookmark of bookmarks) {
91
notify(observers, "onItemChanged", [
92
bookmark.id,
93
"keyword",
94
false,
95
keyword,
96
bookmark.lastModified * 1000,
97
bookmark.type,
98
bookmark.parentId,
99
bookmark.guid,
100
bookmark.parentGuid,
101
"",
102
source,
103
]);
104
}
105
}
106
107
/**
108
* Serializes the given node in JSON format.
109
*
110
* @param aNode
111
* An nsINavHistoryResultNode
112
*/
113
function serializeNode(aNode) {
114
let data = {};
115
116
data.title = aNode.title;
117
// The id is no longer used for copying within the same instance/session of
118
// Firefox as of at least 61. However, we keep the id for now to maintain
119
// backwards compat of drag and drop with older Firefox versions.
120
data.id = aNode.itemId;
121
data.itemGuid = aNode.bookmarkGuid;
122
// Add an instanceId so we can tell which instance of an FF session the data
123
// is coming from.
124
data.instanceId = PlacesUtils.instanceId;
125
126
let guid = aNode.bookmarkGuid;
127
128
// Some nodes, e.g. the unfiled/menu/toolbar ones can have a virtual guid, so
129
// we ignore any that are a folder shortcut. These will be handled below.
130
if (
131
guid &&
132
!PlacesUtils.bookmarks.isVirtualRootItem(guid) &&
133
!PlacesUtils.isVirtualLeftPaneItem(guid)
134
) {
135
if (aNode.parent) {
136
data.parent = aNode.parent.itemId;
137
data.parentGuid = aNode.parent.bookmarkGuid;
138
}
139
140
data.dateAdded = aNode.dateAdded;
141
data.lastModified = aNode.lastModified;
142
}
143
144
if (PlacesUtils.nodeIsURI(aNode)) {
145
// Check for url validity.
146
new URL(aNode.uri);
147
data.type = PlacesUtils.TYPE_X_MOZ_PLACE;
148
data.uri = aNode.uri;
149
if (aNode.tags) {
150
data.tags = aNode.tags;
151
}
152
} else if (PlacesUtils.nodeIsFolder(aNode)) {
153
if (aNode.type == Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER_SHORTCUT) {
154
data.type = PlacesUtils.TYPE_X_MOZ_PLACE;
155
data.uri = aNode.uri;
156
data.concreteId = PlacesUtils.getConcreteItemId(aNode);
157
data.concreteGuid = PlacesUtils.getConcreteItemGuid(aNode);
158
} else {
159
data.type = PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER;
160
}
161
} else if (PlacesUtils.nodeIsQuery(aNode)) {
162
data.type = PlacesUtils.TYPE_X_MOZ_PLACE;
163
data.uri = aNode.uri;
164
} else if (PlacesUtils.nodeIsSeparator(aNode)) {
165
data.type = PlacesUtils.TYPE_X_MOZ_PLACE_SEPARATOR;
166
}
167
168
return JSON.stringify(data);
169
}
170
171
// Imposed to limit database size.
172
const DB_URL_LENGTH_MAX = 65536;
173
const DB_TITLE_LENGTH_MAX = 4096;
174
const DB_DESCRIPTION_LENGTH_MAX = 256;
175
176
/**
177
* Executes a boolean validate function, throwing if it returns false.
178
*
179
* @param boolValidateFn
180
* A boolean validate function.
181
* @return the input value.
182
* @throws if input doesn't pass the validate function.
183
*/
184
function simpleValidateFunc(boolValidateFn) {
185
return (v, input) => {
186
if (!boolValidateFn(v, input)) {
187
throw new Error("Invalid value");
188
}
189
return v;
190
};
191
}
192
193
/**
194
* List of bookmark object validators, one per each known property.
195
* Validators must throw if the property value is invalid and return a fixed up
196
* version of the value, if needed.
197
*/
198
const BOOKMARK_VALIDATORS = Object.freeze({
199
guid: simpleValidateFunc(v => PlacesUtils.isValidGuid(v)),
200
parentGuid: simpleValidateFunc(v => PlacesUtils.isValidGuid(v)),
201
guidPrefix: simpleValidateFunc(v => PlacesUtils.isValidGuidPrefix(v)),
202
index: simpleValidateFunc(
203
v => Number.isInteger(v) && v >= PlacesUtils.bookmarks.DEFAULT_INDEX
204
),
205
dateAdded: simpleValidateFunc(v => v.constructor.name == "Date"),
206
lastModified: simpleValidateFunc(v => v.constructor.name == "Date"),
207
type: simpleValidateFunc(
208
v =>
209
Number.isInteger(v) &&
210
[
211
PlacesUtils.bookmarks.TYPE_BOOKMARK,
212
PlacesUtils.bookmarks.TYPE_FOLDER,
213
PlacesUtils.bookmarks.TYPE_SEPARATOR,
214
].includes(v)
215
),
216
title: v => {
217
if (v === null) {
218
return "";
219
}
220
if (typeof v == "string") {
221
return v.slice(0, DB_TITLE_LENGTH_MAX);
222
}
223
throw new Error("Invalid title");
224
},
225
url: v => {
226
simpleValidateFunc(
227
val =>
228
(typeof val == "string" && val.length <= DB_URL_LENGTH_MAX) ||
229
(val instanceof Ci.nsIURI && val.spec.length <= DB_URL_LENGTH_MAX) ||
230
(val instanceof URL && val.href.length <= DB_URL_LENGTH_MAX)
231
).call(this, v);
232
if (typeof v === "string") {
233
return new URL(v);
234
}
235
if (v instanceof Ci.nsIURI) {
236
return new URL(v.spec);
237
}
238
return v;
239
},
240
source: simpleValidateFunc(
241
v =>
242
Number.isInteger(v) &&
243
Object.values(PlacesUtils.bookmarks.SOURCES).includes(v)
244
),
245
keyword: simpleValidateFunc(v => typeof v == "string" && v.length),
246
charset: simpleValidateFunc(v => typeof v == "string" && v.length),
247
postData: simpleValidateFunc(v => typeof v == "string" && v.length),
248
tags: simpleValidateFunc(
249
v =>
250
Array.isArray(v) &&
251
v.length &&
252
v.every(item => item && typeof item == "string")
253
),
254
});
255
256
// Sync bookmark records can contain additional properties.
257
const SYNC_BOOKMARK_VALIDATORS = Object.freeze({
258
// Sync uses Places GUIDs for all records except roots.
259
recordId: simpleValidateFunc(
260
v =>
261
typeof v == "string" &&
262
(PlacesSyncUtils.bookmarks.ROOTS.includes(v) ||
263
PlacesUtils.isValidGuid(v))
264
),
265
parentRecordId: v => SYNC_BOOKMARK_VALIDATORS.recordId(v),
266
// Sync uses kinds instead of types.
267
kind: simpleValidateFunc(
268
v =>
269
typeof v == "string" &&
270
Object.values(PlacesSyncUtils.bookmarks.KINDS).includes(v)
271
),
272
query: simpleValidateFunc(v => v === null || (typeof v == "string" && v)),
273
folder: simpleValidateFunc(
274
v =>
275
typeof v == "string" &&
276
v &&
277
v.length <= PlacesUtils.bookmarks.MAX_TAG_LENGTH
278
),
279
tags: v => {
280
if (v === null) {
281
return [];
282
}
283
if (!Array.isArray(v)) {
284
throw new Error("Invalid tag array");
285
}
286
for (let tag of v) {
287
if (
288
typeof tag != "string" ||
289
!tag ||
290
tag.length > PlacesUtils.bookmarks.MAX_TAG_LENGTH
291
) {
292
throw new Error(`Invalid tag: ${tag}`);
293
}
294
}
295
return v;
296
},
297
keyword: simpleValidateFunc(v => v === null || typeof v == "string"),
298
dateAdded: simpleValidateFunc(
299
v =>
300
typeof v === "number" &&
301
v > PlacesSyncUtils.bookmarks.EARLIEST_BOOKMARK_TIMESTAMP
302
),
303
feed: v => (v === null ? v : BOOKMARK_VALIDATORS.url(v)),
304
site: v => (v === null ? v : BOOKMARK_VALIDATORS.url(v)),
305
title: BOOKMARK_VALIDATORS.title,
306
url: BOOKMARK_VALIDATORS.url,
307
});
308
309
// Sync change records are passed between `PlacesSyncUtils` and the Sync
310
// bookmarks engine, and are used to update an item's sync status and change
311
// counter at the end of a sync.
312
const SYNC_CHANGE_RECORD_VALIDATORS = Object.freeze({
313
modified: simpleValidateFunc(v => typeof v == "number" && v >= 0),
314
counter: simpleValidateFunc(v => typeof v == "number" && v >= 0),
315
status: simpleValidateFunc(
316
v =>
317
typeof v == "number" &&
318
Object.values(PlacesUtils.bookmarks.SYNC_STATUS).includes(v)
319
),
320
tombstone: simpleValidateFunc(v => v === true || v === false),
321
synced: simpleValidateFunc(v => v === true || v === false),
322
});
323
/**
324
* List PageInfo bookmark object validators.
325
*/
326
const PAGEINFO_VALIDATORS = Object.freeze({
327
guid: BOOKMARK_VALIDATORS.guid,
328
url: BOOKMARK_VALIDATORS.url,
329
title: v => {
330
if (v == null || v == undefined) {
331
return undefined;
332
} else if (typeof v === "string") {
333
return v;
334
}
335
throw new TypeError(
336
`title property of PageInfo object: ${v} must be a string if provided`
337
);
338
},
339
previewImageURL: v => {
340
if (!v) {
341
return null;
342
}
343
return BOOKMARK_VALIDATORS.url(v);
344
},
345
description: v => {
346
if (typeof v === "string" || v === null) {
347
return v ? v.slice(0, DB_DESCRIPTION_LENGTH_MAX) : null;
348
}
349
throw new TypeError(
350
`description property of pageInfo object: ${v} must be either a string or null if provided`
351
);
352
},
353
annotations: v => {
354
if (typeof v != "object" || v.constructor.name != "Map") {
355
throw new TypeError("annotations must be a Map");
356
}
357
358
if (v.size == 0) {
359
throw new TypeError("there must be at least one annotation");
360
}
361
362
for (let [key, value] of v.entries()) {
363
if (typeof key != "string") {
364
throw new TypeError("all annotation keys must be strings");
365
}
366
if (
367
typeof value != "string" &&
368
typeof value != "number" &&
369
typeof value != "boolean" &&
370
value !== null &&
371
value !== undefined
372
) {
373
throw new TypeError(
374
"all annotation values must be Boolean, Numbers or Strings"
375
);
376
}
377
}
378
return v;
379
},
380
visits: v => {
381
if (!Array.isArray(v) || !v.length) {
382
throw new TypeError("PageInfo object must have an array of visits");
383
}
384
let visits = [];
385
for (let inVisit of v) {
386
let visit = {
387
date: new Date(),
388
transition: inVisit.transition || History.TRANSITIONS.LINK,
389
};
390
391
if (!PlacesUtils.history.isValidTransition(visit.transition)) {
392
throw new TypeError(
393
`transition: ${visit.transition} is not a valid transition type`
394
);
395
}
396
397
if (inVisit.date) {
398
PlacesUtils.history.ensureDate(inVisit.date);
399
if (inVisit.date > Date.now() + TIMERS_RESOLUTION_SKEW_MS) {
400
throw new TypeError(`date: ${inVisit.date} cannot be a future date`);
401
}
402
visit.date = inVisit.date;
403
}
404
405
if (inVisit.referrer) {
406
visit.referrer = PlacesUtils.normalizeToURLOrGUID(inVisit.referrer);
407
}
408
visits.push(visit);
409
}
410
return visits;
411
},
412
});
413
414
var PlacesUtils = {
415
// Place entries that are containers, e.g. bookmark folders or queries.
416
TYPE_X_MOZ_PLACE_CONTAINER: "text/x-moz-place-container",
417
// Place entries that are bookmark separators.
418
TYPE_X_MOZ_PLACE_SEPARATOR: "text/x-moz-place-separator",
419
// Place entries that are not containers or separators
420
TYPE_X_MOZ_PLACE: "text/x-moz-place",
421
// Place entries in shortcut url format (url\ntitle)
422
TYPE_X_MOZ_URL: "text/x-moz-url",
423
// Place entries formatted as HTML anchors
424
TYPE_HTML: "text/html",
425
// Place entries as raw URL text
426
TYPE_UNICODE: "text/unicode",
427
// Used to track the action that populated the clipboard.
428
TYPE_X_MOZ_PLACE_ACTION: "text/x-moz-place-action",
429
430
// Deprecated: Remaining only for supporting migration of old livemarks.
431
LMANNO_FEEDURI: "livemark/feedURI",
432
LMANNO_SITEURI: "livemark/siteURI",
433
CHARSET_ANNO: "URIProperties/characterSet",
434
// Deprecated: This is only used for supporting import from older datasets.
435
MOBILE_ROOT_ANNO: "mobile/bookmarksRoot",
436
437
TOPIC_SHUTDOWN: "places-shutdown",
438
TOPIC_INIT_COMPLETE: "places-init-complete",
439
TOPIC_DATABASE_LOCKED: "places-database-locked",
440
TOPIC_EXPIRATION_FINISHED: "places-expiration-finished",
441
TOPIC_FEEDBACK_UPDATED: "places-autocomplete-feedback-updated",
442
TOPIC_FAVICONS_EXPIRED: "places-favicons-expired",
443
TOPIC_VACUUM_STARTING: "places-vacuum-starting",
444
TOPIC_BOOKMARKS_RESTORE_BEGIN: "bookmarks-restore-begin",
445
TOPIC_BOOKMARKS_RESTORE_SUCCESS: "bookmarks-restore-success",
446
TOPIC_BOOKMARKS_RESTORE_FAILED: "bookmarks-restore-failed",
447
448
ACTION_SCHEME: "moz-action:",
449
observers: PlacesObservers,
450
451
/**
452
* GUIDs associated with virtual queries that are used for displaying the
453
* top-level folders in the left pane.
454
*/
455
virtualAllBookmarksGuid: "allbms_____v",
456
virtualHistoryGuid: "history____v",
457
virtualDownloadsGuid: "downloads__v",
458
virtualTagsGuid: "tags_______v",
459
460
/**
461
* Checks if a guid is a virtual left-pane root.
462
*
463
* @param {String} guid The guid of the item to look for.
464
* @returns {Boolean} true if guid is a virtual root, false otherwise.
465
*/
466
isVirtualLeftPaneItem(guid) {
467
return (
468
guid == PlacesUtils.virtualAllBookmarksGuid ||
469
guid == PlacesUtils.virtualHistoryGuid ||
470
guid == PlacesUtils.virtualDownloadsGuid ||
471
guid == PlacesUtils.virtualTagsGuid
472
);
473
},
474
475
asContainer: aNode => asContainer(aNode),
476
asQuery: aNode => asQuery(aNode),
477
478
endl: NEWLINE,
479
480
/**
481
* Is a string a valid GUID?
482
*
483
* @param guid: (String)
484
* @return (Boolean)
485
*/
486
isValidGuid(guid) {
487
return typeof guid == "string" && guid && /^[a-zA-Z0-9\-_]{12}$/.test(guid);
488
},
489
490
/**
491
* Is a string a valid GUID prefix?
492
*
493
* @param guidPrefix: (String)
494
* @return (Boolean)
495
*/
496
isValidGuidPrefix(guidPrefix) {
497
return (
498
typeof guidPrefix == "string" &&
499
guidPrefix &&
500
/^[a-zA-Z0-9\-_]{1,11}$/.test(guidPrefix)
501
);
502
},
503
504
/**
505
* Generates a random GUID and replace its beginning with the given
506
* prefix. We do this instead of just prepending the prefix to keep
507
* the correct character length.
508
*
509
* @param prefix: (String)
510
* @return (String)
511
*/
512
generateGuidWithPrefix(prefix) {
513
return prefix + this.history.makeGuid().substring(prefix.length);
514
},
515
516
/**
517
* Converts a string or n URL object to an nsIURI.
518
*
519
* @param url (URL) or (String)
520
* the URL to convert.
521
* @return nsIURI for the given URL.
522
*/
523
toURI(url) {
524
url = url instanceof URL ? url.href : url;
525
526
return NetUtil.newURI(url);
527
},
528
529
/**
530
* Convert a Date object to a PRTime (microseconds).
531
*
532
* @param date
533
* the Date object to convert.
534
* @return microseconds from the epoch.
535
*/
536
toPRTime(date) {
537
if (typeof date != "number" && date.constructor.name != "Date") {
538
throw new Error("Invalid value passed to toPRTime");
539
}
540
return date * 1000;
541
},
542
543
/**
544
* Convert a PRTime to a Date object.
545
*
546
* @param time
547
* microseconds from the epoch.
548
* @return a Date object.
549
*/
550
toDate(time) {
551
if (typeof time != "number") {
552
throw new Error("Invalid value passed to toDate");
553
}
554
return new Date(parseInt(time / 1000));
555
},
556
557
/**
558
* Wraps a string in a nsISupportsString wrapper.
559
* @param aString
560
* The string to wrap.
561
* @returns A nsISupportsString object containing a string.
562
*/
563
toISupportsString: function PU_toISupportsString(aString) {
564
let s = Cc["@mozilla.org/supports-string;1"].createInstance(
565
Ci.nsISupportsString
566
);
567
s.data = aString;
568
return s;
569
},
570
571
getFormattedString: function PU_getFormattedString(key, params) {
572
return bundle.formatStringFromName(key, params);
573
},
574
575
getString: function PU_getString(key) {
576
return bundle.GetStringFromName(key);
577
},
578
579
/**
580
* Makes a moz-action URI for the given action and set of parameters.
581
*
582
* @param type
583
* The action type.
584
* @param params
585
* A JS object of action params.
586
* @returns A moz-action URI as a string.
587
*/
588
mozActionURI(type, params) {
589
let encodedParams = {};
590
for (let key in params) {
591
// Strip null or undefined.
592
// Regardless, don't encode them or they would be converted to a string.
593
if (params[key] === null || params[key] === undefined) {
594
continue;
595
}
596
encodedParams[key] = encodeURIComponent(params[key]);
597
}
598
return this.ACTION_SCHEME + type + "," + JSON.stringify(encodedParams);
599
},
600
601
/**
602
* Parses a moz-action URL and returns its parts.
603
*
604
* @param url A moz-action URI.
605
* @note URL is in the format moz-action:ACTION,JSON_ENCODED_PARAMS
606
*/
607
parseActionUrl(url) {
608
if (url instanceof Ci.nsIURI) {
609
url = url.spec;
610
} else if (url instanceof URL) {
611
url = url.href;
612
}
613
// Faster bailout.
614
if (!url.startsWith(this.ACTION_SCHEME)) {
615
return null;
616
}
617
618
try {
619
let [, type, params] = url.match(MOZ_ACTION_REGEX);
620
let action = {
621
type,
622
params: JSON.parse(params),
623
};
624
for (let key in action.params) {
625
action.params[key] = decodeURIComponent(action.params[key]);
626
}
627
return action;
628
} catch (ex) {
629
Cu.reportError(`Invalid action url "${url}"`);
630
return null;
631
}
632
},
633
634
/**
635
* Parses matchBuckets strings (for example, "suggestion:4,general:Infinity")
636
* like those used in the browser.urlbar.matchBuckets preference.
637
*
638
* @param str
639
* A matchBuckets string.
640
* @returns An array of the form: [
641
* [bucketName_0, bucketPriority_0],
642
* [bucketName_1, bucketPriority_1],
643
* ...
644
* [bucketName_n, bucketPriority_n]
645
* ]
646
*/
647
convertMatchBucketsStringToArray(str) {
648
return str.split(",").map(v => {
649
let bucket = v.split(":");
650
return [bucket[0].trim().toLowerCase(), Number(bucket[1])];
651
});
652
},
653
654
/**
655
* Determines if a folder is generated from a query.
656
* @param aNode a result true.
657
* @returns true if the node is a folder generated from a query.
658
*/
659
isQueryGeneratedFolder(node) {
660
if (!node.parent) {
661
return false;
662
}
663
return this.nodeIsFolder(node) && this.nodeIsQuery(node.parent);
664
},
665
666
/**
667
* Determines whether or not a ResultNode is a Bookmark folder.
668
* @param aNode
669
* A result node
670
* @returns true if the node is a Bookmark folder, false otherwise
671
*/
672
nodeIsFolder: function PU_nodeIsFolder(aNode) {
673
return (
674
aNode.type == Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER ||
675
aNode.type == Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER_SHORTCUT
676
);
677
},
678
679
/**
680
* Determines whether or not a ResultNode represents a bookmarked URI.
681
* @param aNode
682
* A result node
683
* @returns true if the node represents a bookmarked URI, false otherwise
684
*/
685
nodeIsBookmark: function PU_nodeIsBookmark(aNode) {
686
return (
687
aNode.type == Ci.nsINavHistoryResultNode.RESULT_TYPE_URI &&
688
aNode.itemId != -1
689
);
690
},
691
692
/**
693
* Determines whether or not a ResultNode is a Bookmark separator.
694
* @param aNode
695
* A result node
696
* @returns true if the node is a Bookmark separator, false otherwise
697
*/
698
nodeIsSeparator: function PU_nodeIsSeparator(aNode) {
699
return aNode.type == Ci.nsINavHistoryResultNode.RESULT_TYPE_SEPARATOR;
700
},
701
702
/**
703
* Determines whether or not a ResultNode is a URL item.
704
* @param aNode
705
* A result node
706
* @returns true if the node is a URL item, false otherwise
707
*/
708
nodeIsURI: function PU_nodeIsURI(aNode) {
709
return aNode.type == Ci.nsINavHistoryResultNode.RESULT_TYPE_URI;
710
},
711
712
/**
713
* Determines whether or not a ResultNode is a Query item.
714
* @param aNode
715
* A result node
716
* @returns true if the node is a Query item, false otherwise
717
*/
718
nodeIsQuery: function PU_nodeIsQuery(aNode) {
719
return aNode.type == Ci.nsINavHistoryResultNode.RESULT_TYPE_QUERY;
720
},
721
722
/**
723
* Generator for a node's ancestors.
724
* @param aNode
725
* A result node
726
*/
727
nodeAncestors: function* PU_nodeAncestors(aNode) {
728
let node = aNode.parent;
729
while (node) {
730
yield node;
731
node = node.parent;
732
}
733
},
734
735
/**
736
* Checks validity of an object, filling up default values for optional
737
* properties.
738
*
739
* @param {string} name
740
* The operation name. This is included in the error message if
741
* validation fails.
742
* @param validators (object)
743
* An object containing input validators. Keys should be field names;
744
* values should be validation functions.
745
* @param props (object)
746
* The object to validate.
747
* @param behavior (object) [optional]
748
* Object defining special behavior for some of the properties.
749
* The following behaviors may be optionally set:
750
* - required: this property is required.
751
* - replaceWith: this property will be overwritten with the value
752
* provided
753
* - requiredIf: if the provided condition is satisfied, then this
754
* property is required.
755
* - validIf: if the provided condition is not satisfied, then this
756
* property is invalid.
757
* - defaultValue: an undefined property should default to this value.
758
* - fixup: a function invoked when validation fails, takes the input
759
* object as argument and must fix the property.
760
*
761
* @return a validated and normalized item.
762
* @throws if the object contains invalid data.
763
* @note any unknown properties are pass-through.
764
*/
765
validateItemProperties(name, validators, props, behavior = {}) {
766
if (typeof props != "object" || !props) {
767
throw new Error(`${name}: Input should be a valid object`);
768
}
769
// Make a shallow copy of `props` to avoid mutating the original object
770
// when filling in defaults.
771
let input = Object.assign({}, props);
772
let normalizedInput = {};
773
let required = new Set();
774
for (let prop in behavior) {
775
if (
776
behavior[prop].hasOwnProperty("required") &&
777
behavior[prop].required
778
) {
779
required.add(prop);
780
}
781
if (
782
behavior[prop].hasOwnProperty("requiredIf") &&
783
behavior[prop].requiredIf(input)
784
) {
785
required.add(prop);
786
}
787
if (
788
behavior[prop].hasOwnProperty("validIf") &&
789
input[prop] !== undefined &&
790
!behavior[prop].validIf(input)
791
) {
792
if (behavior[prop].hasOwnProperty("fixup")) {
793
behavior[prop].fixup(input);
794
} else {
795
throw new Error(
796
`${name}: Invalid value for property '${prop}': ${JSON.stringify(
797
input[prop]
798
)}`
799
);
800
}
801
}
802
if (
803
behavior[prop].hasOwnProperty("defaultValue") &&
804
input[prop] === undefined
805
) {
806
input[prop] = behavior[prop].defaultValue;
807
}
808
if (behavior[prop].hasOwnProperty("replaceWith")) {
809
input[prop] = behavior[prop].replaceWith;
810
}
811
}
812
813
for (let prop in input) {
814
if (required.has(prop)) {
815
required.delete(prop);
816
} else if (input[prop] === undefined) {
817
// Skip undefined properties that are not required.
818
continue;
819
}
820
if (validators.hasOwnProperty(prop)) {
821
try {
822
normalizedInput[prop] = validators[prop](input[prop], input);
823
} catch (ex) {
824
if (
825
behavior.hasOwnProperty(prop) &&
826
behavior[prop].hasOwnProperty("fixup")
827
) {
828
behavior[prop].fixup(input);
829
normalizedInput[prop] = input[prop];
830
} else {
831
throw new Error(
832
`${name}: Invalid value for property '${prop}': ${JSON.stringify(
833
input[prop]
834
)}`
835
);
836
}
837
}
838
}
839
}
840
if (required.size > 0) {
841
throw new Error(
842
`${name}: The following properties were expected: ${[...required].join(
843
", "
844
)}`
845
);
846
}
847
return normalizedInput;
848
},
849
850
BOOKMARK_VALIDATORS,
851
SYNC_BOOKMARK_VALIDATORS,
852
SYNC_CHANGE_RECORD_VALIDATORS,
853
854
QueryInterface: ChromeUtils.generateQI([Ci.nsIObserver]),
855
856
_shutdownFunctions: [],
857
registerShutdownFunction: function PU_registerShutdownFunction(aFunc) {
858
// If this is the first registered function, add the shutdown observer.
859
if (!this._shutdownFunctions.length) {
860
Services.obs.addObserver(this, this.TOPIC_SHUTDOWN);
861
}
862
this._shutdownFunctions.push(aFunc);
863
},
864
865
// nsIObserver
866
observe: function PU_observe(aSubject, aTopic, aData) {
867
switch (aTopic) {
868
case this.TOPIC_SHUTDOWN:
869
Services.obs.removeObserver(this, this.TOPIC_SHUTDOWN);
870
while (this._shutdownFunctions.length) {
871
this._shutdownFunctions.shift().apply(this);
872
}
873
break;
874
}
875
},
876
877
/**
878
* Determines whether or not a ResultNode is a host container.
879
* @param aNode
880
* A result node
881
* @returns true if the node is a host container, false otherwise
882
*/
883
nodeIsHost: function PU_nodeIsHost(aNode) {
884
return (
885
aNode.type == Ci.nsINavHistoryResultNode.RESULT_TYPE_QUERY &&
886
aNode.parent &&
887
asQuery(aNode.parent).queryOptions.resultType ==
888
Ci.nsINavHistoryQueryOptions.RESULTS_AS_SITE_QUERY
889
);
890
},
891
892
/**
893
* Determines whether or not a ResultNode is a day container.
894
* @param node
895
* A NavHistoryResultNode
896
* @returns true if the node is a day container, false otherwise
897
*/
898
nodeIsDay: function PU_nodeIsDay(aNode) {
899
var resultType;
900
return (
901
aNode.type == Ci.nsINavHistoryResultNode.RESULT_TYPE_QUERY &&
902
aNode.parent &&
903
((resultType = asQuery(aNode.parent).queryOptions.resultType) ==
904
Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_QUERY ||
905
resultType == Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_SITE_QUERY)
906
);
907
},
908
909
/**
910
* Determines whether or not a result-node is a tag container.
911
* @param aNode
912
* A result-node
913
* @returns true if the node is a tag container, false otherwise
914
*/
915
nodeIsTagQuery: function PU_nodeIsTagQuery(aNode) {
916
if (aNode.type != Ci.nsINavHistoryResultNode.RESULT_TYPE_QUERY) {
917
return false;
918
}
919
// Direct child of RESULTS_AS_TAGS_ROOT.
920
let parent = aNode.parent;
921
if (
922
parent &&
923
PlacesUtils.asQuery(parent).queryOptions.resultType ==
924
Ci.nsINavHistoryQueryOptions.RESULTS_AS_TAGS_ROOT
925
) {
926
return true;
927
}
928
// We must also support the right pane of the Library, when the tag query
929
// is the root node. Unfortunately this is also valid for any tag query
930
// selected in the left pane that is not a direct child of RESULTS_AS_TAGS_ROOT.
931
if (
932
!parent &&
933
aNode == aNode.parentResult.root &&
934
PlacesUtils.asQuery(aNode).query.tags.length == 1
935
) {
936
return true;
937
}
938
return false;
939
},
940
941
/**
942
* Determines whether or not a ResultNode is a container.
943
* @param aNode
944
* A result node
945
* @returns true if the node is a container item, false otherwise
946
*/
947
containerTypes: [
948
Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER,
949
Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER_SHORTCUT,
950
Ci.nsINavHistoryResultNode.RESULT_TYPE_QUERY,
951
],
952
nodeIsContainer: function PU_nodeIsContainer(aNode) {
953
return this.containerTypes.includes(aNode.type);
954
},
955
956
/**
957
* Determines whether or not a ResultNode is an history related container.
958
* @param node
959
* A result node
960
* @returns true if the node is an history related container, false otherwise
961
*/
962
nodeIsHistoryContainer: function PU_nodeIsHistoryContainer(aNode) {
963
var resultType;
964
return (
965
this.nodeIsQuery(aNode) &&
966
((resultType = asQuery(aNode).queryOptions.resultType) ==
967
Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_SITE_QUERY ||
968
resultType == Ci.nsINavHistoryQueryOptions.RESULTS_AS_DATE_QUERY ||
969
resultType == Ci.nsINavHistoryQueryOptions.RESULTS_AS_SITE_QUERY ||
970
this.nodeIsDay(aNode) ||
971
this.nodeIsHost(aNode))
972
);
973
},
974
975
/**
976
* Gets the concrete item-id for the given node. Generally, this is just
977
* node.itemId, but for folder-shortcuts that's node.folderItemId.
978
*/
979
getConcreteItemId: function PU_getConcreteItemId(aNode) {
980
return aNode.type == Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER_SHORTCUT
981
? asQuery(aNode).folderItemId
982
: aNode.itemId;
983
},
984
985
/**
986
* Gets the concrete item-guid for the given node. For everything but folder
987
* shortcuts, this is just node.bookmarkGuid. For folder shortcuts, this is
988
* node.targetFolderGuid (see nsINavHistoryService.idl for the semantics).
989
*
990
* @param aNode
991
* a result node.
992
* @return the concrete item-guid for aNode.
993
*/
994
getConcreteItemGuid(aNode) {
995
if (aNode.type == Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER_SHORTCUT) {
996
return asQuery(aNode).targetFolderGuid;
997
}
998
return aNode.bookmarkGuid;
999
},
1000
1001
/**
1002
* Reverse a host based on the moz_places algorithm, that is reverse the host
1003
* string and add a trailing period. For example "google.com" becomes
1004
* "moc.elgoog.".
1005
*
1006
* @param url
1007
* the URL to generate a rev host for.
1008
* @return the reversed host string.
1009
*/
1010
getReversedHost(url) {
1011
return (
1012
url.host
1013
.split("")
1014
.reverse()
1015
.join("") + "."
1016
);
1017
},
1018
1019
/**
1020
* String-wraps a result node according to the rules of the specified
1021
* content type for copy or move operations.
1022
*
1023
* @param aNode
1024
* The Result node to wrap (serialize)
1025
* @param aType
1026
* The content type to serialize as
1027
* @return A string serialization of the node
1028
*/
1029
wrapNode(aNode, aType) {
1030
// when wrapping a node, we want all the items, even if the original
1031
// query options are excluding them.
1032
// This can happen when copying from the left hand pane of the bookmarks
1033
// organizer.
1034
// @return [node, shouldClose]
1035
function gatherDataFromNode(node, gatherDataFunc) {
1036
if (
1037
PlacesUtils.nodeIsFolder(node) &&
1038
node.type != Ci.nsINavHistoryResultNode.RESULT_TYPE_FOLDER_SHORTCUT &&
1039
asQuery(node).queryOptions.excludeItems
1040
) {
1041
let folderRoot = PlacesUtils.getFolderContents(
1042
node.bookmarkGuid,
1043
false,
1044
true
1045
).root;
1046
try {
1047
return gatherDataFunc(folderRoot);
1048
} finally {
1049
folderRoot.containerOpen = false;
1050
}
1051
}
1052
// If we didn't create our own query, do not alter the node's state.
1053
return gatherDataFunc(node);
1054
}
1055
1056
function gatherDataHtml(node) {
1057
let htmlEscape = s =>
1058
s
1059
.replace(/&/g, "&amp;")
1060
.replace(/>/g, "&gt;")
1061
.replace(/</g, "&lt;")
1062
.replace(/"/g, "&quot;")
1063
.replace(/'/g, "&apos;");
1064
1065
// escape out potential HTML in the title
1066
let escapedTitle = node.title ? htmlEscape(node.title) : "";
1067
1068
if (PlacesUtils.nodeIsContainer(node)) {
1069
asContainer(node);
1070
let wasOpen = node.containerOpen;
1071
if (!wasOpen) {
1072
node.containerOpen = true;
1073
}
1074
1075
let childString = "<DL><DT>" + escapedTitle + "</DT>" + NEWLINE;
1076
let cc = node.childCount;
1077
for (let i = 0; i < cc; ++i) {
1078
childString +=
1079
"<DD>" +
1080
NEWLINE +
1081
gatherDataHtml(node.getChild(i)) +
1082
"</DD>" +
1083
NEWLINE;
1084
}
1085
node.containerOpen = wasOpen;
1086
return childString + "</DL>" + NEWLINE;
1087
}
1088
if (PlacesUtils.nodeIsURI(node)) {
1089
return `<A HREF="${node.uri}">${escapedTitle}</A>${NEWLINE}`;
1090
}
1091
if (PlacesUtils.nodeIsSeparator(node)) {
1092
return "<HR>" + NEWLINE;
1093
}
1094
return "";
1095
}
1096
1097
function gatherDataText(node) {
1098
if (PlacesUtils.nodeIsContainer(node)) {
1099
asContainer(node);
1100
let wasOpen = node.containerOpen;
1101
if (!wasOpen) {
1102
node.containerOpen = true;
1103
}
1104
1105
let childString = node.title + NEWLINE;
1106
let cc = node.childCount;
1107
for (let i = 0; i < cc; ++i) {
1108
let child = node.getChild(i);
1109
let suffix = i < cc - 1 ? NEWLINE : "";
1110
childString += gatherDataText(child) + suffix;
1111
}
1112
node.containerOpen = wasOpen;
1113
return childString;
1114
}
1115
if (PlacesUtils.nodeIsURI(node)) {
1116
return node.uri;
1117
}
1118
if (PlacesUtils.nodeIsSeparator(node)) {
1119
return "--------------------";
1120
}
1121
return "";
1122
}
1123
1124
switch (aType) {
1125
case this.TYPE_X_MOZ_PLACE:
1126
case this.TYPE_X_MOZ_PLACE_SEPARATOR:
1127
case this.TYPE_X_MOZ_PLACE_CONTAINER: {
1128
// Serialize the node to JSON.
1129
return serializeNode(aNode);
1130
}
1131
case this.TYPE_X_MOZ_URL: {
1132
if (PlacesUtils.nodeIsURI(aNode)) {
1133
return aNode.uri + NEWLINE + aNode.title;
1134
}
1135
if (PlacesUtils.nodeIsContainer(aNode)) {
1136
return PlacesUtils.getURLsForContainerNode(aNode)
1137
.map(item => item.uri + "\n" + item.title)
1138
.join("\n");
1139
}
1140
return "";
1141
}
1142
case this.TYPE_HTML: {
1143
return gatherDataFromNode(aNode, gatherDataHtml);
1144
}
1145
}
1146
1147
// Otherwise, we wrap as TYPE_UNICODE.
1148
return gatherDataFromNode(aNode, gatherDataText);
1149
},
1150
1151
/**
1152
* Unwraps data from the Clipboard or the current Drag Session.
1153
* @param blob
1154
* A blob (string) of data, in some format we potentially know how
1155
* to parse.
1156
* @param type
1157
* The content type of the blob.
1158
* @returns An array of objects representing each item contained by the source.
1159
* @throws if the blob contains invalid data.
1160
*/
1161
unwrapNodes: function PU_unwrapNodes(blob, type) {
1162
// We split on "\n" because the transferable system converts "\r\n" to "\n"
1163
var nodes = [];
1164
switch (type) {
1165
case this.TYPE_X_MOZ_PLACE:
1166
case this.TYPE_X_MOZ_PLACE_SEPARATOR:
1167
case this.TYPE_X_MOZ_PLACE_CONTAINER:
1168
nodes = JSON.parse("[" + blob + "]");
1169
break;
1170
case this.TYPE_X_MOZ_URL: {
1171
let parts = blob.split("\n");
1172
// data in this type has 2 parts per entry, so if there are fewer
1173
// than 2 parts left, the blob is malformed and we should stop
1174
// but drag and drop of files from the shell has parts.length = 1
1175
if (parts.length != 1 && parts.length % 2) {
1176
break;
1177
}
1178
for (let i = 0; i < parts.length; i = i + 2) {
1179
let uriString = parts[i];
1180
let titleString = "";
1181
if (parts.length > i + 1) {
1182
titleString = parts[i + 1];
1183
} else {
1184
// for drag and drop of files, try to use the leafName as title
1185
try {
1186
titleString = Services.io
1187
.newURI(uriString)
1188
.QueryInterface(Ci.nsIURL).fileName;
1189
} catch (ex) {}
1190
}
1191
// note: Services.io.newURI() will throw if uriString is not a valid URI
1192
let uri = Services.io.newURI(uriString);
1193
if (Services.io.newURI(uriString) && uri.scheme != "place") {
1194
nodes.push({
1195
uri: uriString,
1196
title: titleString ? titleString : uriString,
1197
type: this.TYPE_X_MOZ_URL,
1198
});
1199
}
1200
}
1201
break;
1202
}
1203
case this.TYPE_UNICODE: {
1204
let parts = blob.split("\n");
1205
for (let i = 0; i < parts.length; i++) {
1206
let uriString = parts[i];
1207
// text/uri-list is converted to TYPE_UNICODE but it could contain
1208
// comments line prepended by #, we should skip them, as well as
1209
// empty uris.
1210
if (uriString.substr(0, 1) == "\x23" || uriString == "") {
1211
continue;
1212
}
1213
// note: Services.io.newURI) will throw if uriString is not a valid URI
1214
let uri = Services.io.newURI(uriString);
1215
if (uri.scheme != "place") {
1216
nodes.push({
1217
uri: uriString,
1218
title: uriString,
1219
type: this.TYPE_X_MOZ_URL,
1220
});
1221
}
1222
}
1223
break;
1224
}
1225
default:
1226
throw Cr.NS_ERROR_INVALID_ARG;
1227
}
1228
return nodes;
1229
},
1230
1231
/**
1232
* Validate an input PageInfo object, returning a valid PageInfo object.
1233
*
1234
* @param pageInfo: (PageInfo)
1235
* @return (PageInfo)
1236
*/
1237
validatePageInfo(pageInfo, validateVisits = true) {
1238
return this.validateItemProperties(
1239
"PageInfo",
1240
PAGEINFO_VALIDATORS,
1241
pageInfo,
1242
{
1243
url: { requiredIf: b => !b.guid },
1244
guid: { requiredIf: b => !b.url },
1245
visits: { requiredIf: b => validateVisits },
1246
}
1247
);
1248
},
1249
/**
1250
* Normalize a key to either a string (if it is a valid GUID) or an
1251
* instance of `URL` (if it is a `URL`, `nsIURI`, or a string
1252
* representing a valid url).
1253
*
1254
* @throws (TypeError)
1255
* If the key is neither a valid guid nor a valid url.
1256
*/
1257
normalizeToURLOrGUID(key) {
1258
if (typeof key === "string") {
1259
// A string may be a URL or a guid
1260
if (this.isValidGuid(key)) {
1261
return key;
1262
}
1263
return new URL(key);
1264
}
1265
if (key instanceof URL) {
1266
return key;
1267
}
1268
if (key instanceof Ci.nsIURI) {
1269
return new URL(key.spec);
1270
}
1271
throw new TypeError("Invalid url or guid: " + key);
1272
},
1273
1274
/**
1275
* Generates a nsINavHistoryResult for the contents of a folder.
1276
* @param aFolderGuid
1277
* The folder to open
1278
* @param [optional] excludeItems
1279
* True to hide all items (individual bookmarks). This is used on
1280
* the left places pane so you just get a folder hierarchy.
1281
* @param [optional] expandQueries
1282
* True to make query items expand as new containers. For managing,
1283
* you want this to be false, for menus and such, you want this to
1284
* be true.
1285
* @returns A nsINavHistoryResult containing the contents of the
1286
* folder. The result.root is guaranteed to be open.
1287
*/
1288
getFolderContents(aFolderGuid, aExcludeItems, aExpandQueries) {
1289
if (!this.isValidGuid(aFolderGuid)) {
1290
throw new Error("aFolderGuid should be a valid GUID.");
1291
}
1292
var query = this.history.getNewQuery();
1293
query.setParents([aFolderGuid]);
1294
var options = this.history.getNewQueryOptions();
1295
options.excludeItems = aExcludeItems;
1296
options.expandQueries = aExpandQueries;
1297
1298
var result = this.history.executeQuery(query, options);
1299
result.root.containerOpen = true;
1300
return result;
1301
},
1302
1303
// Identifier getters for special folders.
1304
// You should use these everywhere PlacesUtils is available to avoid XPCOM
1305
// traversal just to get roots' ids.
1306
get placesRootId() {
1307
delete this.placesRootId;
1308
return (this.placesRootId = this.bookmarks.placesRoot);
1309
},
1310
1311
get bookmarksMenuFolderId() {
1312
delete this.bookmarksMenuFolderId;
1313
return (this.bookmarksMenuFolderId = this.bookmarks.bookmarksMenuFolder);
1314
},
1315
1316
get toolbarFolderId() {
1317
delete this.toolbarFolderId;
1318
return (this.toolbarFolderId = this.bookmarks.toolbarFolder);
1319
},
1320
1321
get tagsFolderId() {
1322
delete this.tagsFolderId;
1323
return (this.tagsFolderId = this.bookmarks.tagsFolder);
1324
},
1325
1326
/**
1327
* Checks if item is a root.
1328
*
1329
* @param {String} guid The guid of the item to look for.
1330
* @returns {Boolean} true if guid is a root, false otherwise.
1331
*/
1332
isRootItem(guid) {
1333
return (
1334
guid == PlacesUtils.bookmarks.menuGuid ||
1335
guid == PlacesUtils.bookmarks.toolbarGuid ||
1336
guid == PlacesUtils.bookmarks.unfiledGuid ||
1337
guid == PlacesUtils.bookmarks.tagsGuid ||
1338
guid == PlacesUtils.bookmarks.rootGuid ||
1339
guid == PlacesUtils.bookmarks.mobileGuid
1340
);
1341
},
1342
1343
/**
1344
* Returns a nsNavHistoryContainerResultNode with forced excludeItems and
1345
* expandQueries.
1346
* @param aNode
1347
* The node to convert
1348
* @param [optional] excludeItems
1349
* True to hide all items (individual bookmarks). This is used on
1350
* the left places pane so you just get a folder hierarchy.
1351
* @param [optional] expandQueries
1352
* True to make query items expand as new containers. For managing,
1353
* you want this to be false, for menus and such, you want this to
1354
* be true.
1355
* @returns A nsINavHistoryContainerResultNode containing the unfiltered
1356
* contents of the container.
1357
* @note The returned container node could be open or closed, we don't
1358
* guarantee its status.
1359
*/
1360
getContainerNodeWithOptions: function PU_getContainerNodeWithOptions(
1361
aNode,
1362
aExcludeItems,
1363
aExpandQueries
1364
) {
1365
if (!this.nodeIsContainer(aNode)) {
1366
throw Cr.NS_ERROR_INVALID_ARG;
1367
}
1368
1369
// excludeItems is inherited by child containers in an excludeItems view.
1370
var excludeItems =
1371
asQuery(aNode).queryOptions.excludeItems ||
1372
asQuery(aNode.parentResult.root).queryOptions.excludeItems;
1373
// expandQueries is inherited by child containers in an expandQueries view.
1374
var expandQueries =
1375
asQuery(aNode).queryOptions.expandQueries &&
1376
asQuery(aNode.parentResult.root).queryOptions.expandQueries;
1377
1378
// If our options are exactly what we expect, directly return the node.
1379
if (excludeItems == aExcludeItems && expandQueries == aExpandQueries) {
1380
return aNode;
1381
}
1382
1383
// Otherwise, get contents manually.
1384
var query = {},
1385
options = {};
1386
this.history.queryStringToQuery(aNode.uri, query, options);
1387
options.value.excludeItems = aExcludeItems;
1388
options.value.expandQueries = aExpandQueries;
1389
return this.history.executeQuery(query.value, options.value).root;
1390
},
1391
1392
/**
1393
* Returns true if a container has uri nodes in its first level.
1394
* Has better performance than (getURLsForContainerNode(node).length > 0).
1395
* @param aNode
1396
* The container node to search through.
1397
* @returns true if the node contains uri nodes, false otherwise.
1398
*/
1399
hasChildURIs: function PU_hasChildURIs(aNode) {
1400
if (!this.nodeIsContainer(aNode)) {
1401
return false;
1402
}
1403
1404
let root = this.getContainerNodeWithOptions(aNode, false, true);
1405
let result = root.parentResult;
1406
let didSuppressNotifications = false;
1407
let wasOpen = root.containerOpen;
1408
if (!wasOpen) {
1409
didSuppressNotifications = result.suppressNotifications;
1410
if (!didSuppressNotifications) {
1411
result.suppressNotifications = true;
1412
}
1413
1414
root.containerOpen = true;
1415
}
1416
1417
let found = false;
1418
for (let i = 0; i < root.childCount && !found; i++) {
1419
let child = root.getChild(i);
1420
if (this.nodeIsURI(child)) {
1421
found = true;
1422
}
1423
}
1424
1425
if (!wasOpen) {
1426
root.containerOpen = false;
1427
if (!didSuppressNotifications) {
1428
result.suppressNotifications = false;
1429
}
1430
}
1431
return found;
1432
},
1433
1434
/**
1435
* Returns an array containing all the uris in the first level of the
1436
* passed in container.
1437
* If you only need to know if the node contains uris, use hasChildURIs.
1438
* @param aNode
1439
* The container node to search through
1440
* @returns array of uris in the first level of the container.
1441
*/
1442
getURLsForContainerNode: function PU_getURLsForContainerNode(aNode) {
1443
let urls = [];
1444
if (!this.nodeIsContainer(aNode)) {
1445
return urls;
1446
}
1447
1448
let root = this.getContainerNodeWithOptions(aNode, false, true);
1449
let result = root.parentResult;
1450
let wasOpen = root.containerOpen;
1451
let didSuppressNotifications = false;
1452
if (!wasOpen) {
1453
didSuppressNotifications = result.suppressNotifications;
1454
if (!didSuppressNotifications) {
1455
result.suppressNotifications = true;
1456
}
1457
1458
root.containerOpen = true;
1459
}
1460
1461
for (let i = 0; i < root.childCount; ++i) {
1462
let child = root.getChild(i);
1463
if (this.nodeIsURI(child)) {
1464
urls.push({
1465
uri: child.uri,
1466
isBookmark: this.nodeIsBookmark(child),
1467
title: child.title,
1468
});
1469
}
1470
}
1471
1472
if (!wasOpen) {
1473
root.containerOpen = false;
1474
if (!didSuppressNotifications) {
1475
result.suppressNotifications = false;
1476
}
1477
}
1478
return urls;
1479
},
1480
1481
/**
1482
* Gets a shared Sqlite.jsm readonly connection to the Places database,
1483
* usable only for SELECT queries.
1484
*
1485
* This is intended to be used mostly internally, components outside of
1486
* Places should, when possible, use API calls and file bugs to get proper
1487
* APIs, where they are missing.
1488
* Keep in mind the Places DB schema is by no means frozen or even stable.
1489
* Your custom queries can - and will - break overtime.
1490
*
1491
* Example:
1492
* let db = await PlacesUtils.promiseDBConnection();
1493
* let rows = await db.executeCached(sql, params);
1494
*/
1495
promiseDBConnection: () => gAsyncDBConnPromised,
1496
1497
/**
1498
* This is pretty much the same as promiseDBConnection, but with a larger
1499
* page cache, useful for consumers doing large table scans, like the urlbar.
1500
* @see promiseDBConnection
1501
*/
1502
promiseLargeCacheDBConnection: () => gAsyncDBLargeCacheConnPromised,
1503
1504
/**
1505
* Returns a Sqlite.jsm wrapper for the main Places connection. Most callers
1506
* should prefer `withConnectionWrapper`, which ensures that all database
1507
* operations finish before the connection is closed.
1508
*/
1509
promiseUnsafeWritableDBConnection: () => gAsyncDBWrapperPromised,
1510
1511
/**
1512
* Performs a read/write operation on the Places database through a Sqlite.jsm
1513
* wrapped connection to the Places database.
1514
*
1515
* This is intended to be used only by Places itself, always use APIs if you
1516
* need to modify the Places database. Use promiseDBConnection if you need to
1517
* SELECT from the database and there's no covering API.
1518
* Keep in mind the Places DB schema is by no means frozen or even stable.
1519
* Your custom queries can - and will - break overtime.
1520
*
1521
* As all operations on the Places database are asynchronous, if shutdown
1522
* is initiated while an operation is pending, this could cause dataloss.
1523
* Using `withConnectionWrapper` ensures that shutdown waits until all
1524
* operations are complete before proceeding.
1525
*
1526
* Example:
1527
* await withConnectionWrapper("Bookmarks: Remove a bookmark", Task.async(function*(db) {
1528
* // Proceed with the db, asynchronously.
1529
* // Shutdown will not interrupt operations that take place here.
1530
* }));
1531
*
1532
* @param {string} name The name of the operation. Used for debugging, logging
1533
* and crash reporting.
1534
* @param {function(db)} task A function that takes as argument a Sqlite.jsm
1535
* connection and returns a Promise. Shutdown is guaranteed to not interrupt
1536
* execution of `task`.
1537
*/
1538
async withConnectionWrapper(name, task) {
1539
if (!name) {
1540
throw new TypeError("Expecting a user-readable name");
1541
}
1542
let db = await gAsyncDBWrapperPromised;
1543
return db.executeBeforeShutdown(name, task);
1544
},
1545
1546
/**
1547
* Gets favicon data for a given page url.
1548
*
1549
* @param aPageUrl url of the page to look favicon for.
1550
* @resolves to an object representing a favicon entry, having the following
1551
* properties: { uri, dataLen, data, mimeType }
1552
* @rejects JavaScript exception if the given url has no associated favicon.
1553
*/
1554
promiseFaviconData(aPageUrl) {
1555
return new Promise((resolve, reject) => {
1556
PlacesUtils.favicons.getFaviconDataForPage(
1557
NetUtil.newURI(aPageUrl),
1558
function(uri, dataLen, data, mimeType) {
1559
if (uri) {
1560
resolve({ uri, dataLen, data, mimeType });
1561
} else {
1562
reject();
1563
}
1564
}
1565
);
1566
});
1567
},
1568
1569
/**
1570
* Returns the passed URL with a #size ref for the specified size and
1571
* devicePixelRatio.
1572
*
1573
* @param window
1574
* The window where the icon will appear.
1575
* @param href
1576
* The string href we should add the ref to.
1577
* @param size
1578
* The target image size
1579
* @return The URL with the fragment at the end, in the same formar as input.
1580
*/
1581
urlWithSizeRef(window, href, size) {
1582
return (
1583
href +
1584
(href.includes("#") ? "&" : "#") +
1585
"size=" +
1586
Math.round(size) * window.devicePixelRatio
1587
);
1588
},
1589
1590
/**
1591
* Get the unique id for an item (a bookmark, a folder or a separator) given
1592
* its item id.
1593
*
1594
* @param aItemId
1595
* an item id
1596
* @return {Promise}
1597
* @resolves to the GUID.
1598
* @rejects if aItemId is invalid.
1599
*/
1600
promiseItemGuid(aItemId) {
1601
return GuidHelper.getItemGuid(aItemId);
1602
},
1603
1604
/**
1605
* Get the item id for an item (a bookmark, a folder or a separator) given
1606
* its unique id.
1607
*
1608
* @param aGuid
1609
* an item GUID
1610
* @return {Promise}
1611
* @resolves to the item id.
1612
* @rejects if there's no item for the given GUID.
1613
*/
1614
promiseItemId(aGuid) {
1615
return GuidHelper.getItemId(aGuid);
1616
},
1617
1618
/**
1619
* Get the item ids for multiple items (a bookmark, a folder or a separator)
1620
* given the unique ids for each item.
1621
*
1622
* @param {Array} aGuids An array of item GUIDs.
1623
* @return {Promise}
1624
* @resolves to a Map of item ids.
1625
* @rejects if not all of the GUIDs could be found.
1626
*/
1627
promiseManyItemIds(aGuids) {
1628
return GuidHelper.getManyItemIds(aGuids);
1629
},
1630
1631
/**
1632
* Invalidate the GUID cache for the given itemId.
1633
*
1634
* @param aItemId
1635
* an item id
1636
*/
1637
invalidateCachedGuidFor(aItemId) {
1638
GuidHelper.invalidateCacheForItemId(aItemId);
1639
},
1640
1641
/**
1642
* Invalidates the entire GUID cache.
1643
*/
1644
invalidateCachedGuids() {
1645
GuidHelper.invalidateCache();
1646
},
1647
1648
/**
1649
* Asynchronously retrieve a JS-object representation of a places bookmarks
1650
* item (a bookmark, a folder, or a separator) along with all of its
1651
* descendants.
1652
*
1653
* @param [optional] aItemGuid
1654
* the (topmost) item to be queried. If it's not passed, the places
1655
* root is queried: that is, you get a representation of the entire
1656
* bookmarks hierarchy.
1657
* @param [optional] aOptions
1658
* Options for customizing the query behavior, in the form of a JS
1659
* object with any of the following properties:
1660
* - excludeItemsCallback: a function for excluding items, along with
1661
* their descendants. Given an item object (that has everything set
1662
* apart its potential children data), it should return true if the
1663
* item should be excluded. Once an item is excluded, the function
1664
* isn't called for any of its descendants. This isn't called for
1665
* the root item.
1666
* WARNING: since the function may be called for each item, using
1667
* this option can slow down the process significantly if the
1668
* callback does anything that's not relatively trivial. It is
1669
* highly recommended to avoid any synchronous I/O or DB queries.
1670
* - includeItemIds: opt-in to include the deprecated id property.
1671
* Use it if you must. It'll be removed once the switch to GUIDs is
1672
* complete.
1673
*
1674
* @return {Promise}
1675
* @resolves to a JS object that represents either a single item or a
1676
* bookmarks tree. Each node in the tree has the following properties set:
1677
* - guid (string): the item's GUID (same as aItemGuid for the top item).
1678
* - [deprecated] id (number): the item's id. This is only if
1679
* aOptions.includeItemIds is set.
1680
* - type (string): the item's type. @see PlacesUtils.TYPE_X_*
1681
* - typeCode (number): the item's type in numeric format.
1682
* @see PlacesUtils.bookmarks.TYPE_*
1683
* - title (string): the item's title. If it has no title, this property
1684
* isn't set.
1685
* - dateAdded (number, microseconds from the epoch): the date-added value of
1686
* the item.
1687
* - lastModified (number, microseconds from the epoch): the last-modified
1688
* value of the item.
1689
* - index: the item's index under it's parent.
1690
*
1691
* The root object (i.e. the one for aItemGuid) also has the following
1692
* properties set:
1693
* - parentGuid (string): the GUID of the root's parent. This isn't set if
1694
* the root item is the places root.
1695
* - itemsCount (number, not enumerable): the number of items, including the
1696
* root item itself, which are represented in the resolved object.
1697
*
1698
* Bookmark items also have the following properties:
1699
* - uri (string): the item's url.
1700
* - tags (string): csv string of the bookmark's tags.
1701
* - charset (string): the last known charset of the bookmark.
1702
* - keyword (string): the bookmark's keyword (unset if none).
1703
* - postData (string): the bookmark's keyword postData (unset if none).
1704
* - iconuri (string): the bookmark's favicon url.
1705
* The last four properties are not set at all if they're irrelevant (e.g.
1706
* |charset| is not set if no charset was previously set for the bookmark
1707
* url).
1708
*
1709
* Folders may also have the following properties:
1710
* - children (array): the folder's children information, each of them
1711
* having the same set of properties as above.
1712
*
1713
* @rejects if the query failed for any reason.
1714
* @note if aItemGuid points to a non-existent item, the returned promise is
1715
* resolved to null.
1716
*/
1717
async promiseBookmarksTree(aItemGuid = "", aOptions = {}) {
1718
let createItemInfoObject = async function(aRow, aIncludeParentGuid) {
1719
let item = {};
1720
let copyProps = (...props) => {
1721
for (let prop of props) {
1722
let val = aRow.getResultByName(prop);
1723
if (val !== null) {
1724
item[prop] = val;
1725
}
1726
}
1727
};
1728
copyProps("guid", "title", "index", "dateAdded", "lastModified");
1729
if (aIncludeParentGuid) {
1730
copyProps("parentGuid");
1731
}
1732
1733
let itemId = aRow.getResultByName("id");
1734
if (aOptions.includeItemIds) {
1735
item.id = itemId;
1736
}
1737
1738
// Cache it for promiseItemId consumers regardless.
1739
GuidHelper.updateCache(itemId, item.guid);
1740
1741
let type = aRow.getResultByName("type");
1742
item.typeCode = type;
1743
if (type == Ci.nsINavBookmarksService.TYPE_BOOKMARK) {
1744
copyProps("charset", "tags", "iconuri");
1745
}
1746
1747
switch (type) {
1748
case PlacesUtils.bookmarks.TYPE_BOOKMARK:
1749
item.type = PlacesUtils.TYPE_X_MOZ_PLACE;
1750
// If this throws due to an invalid url, the item will be skipped.
1751
try {
1752
item.uri = NetUtil.newURI(aRow.getResultByName("url")).spec;
1753
} catch (ex) {
1754
let error = new Error("Invalid bookmark URL");
1755
error.becauseInvalidURL = true;
1756
throw error;
1757
}
1758
// Keywords are cached, so this should be decently fast.
1759
let entry = await PlacesUtils.keywords.fetch({ url: item.uri });
1760
if (entry) {
1761
item.keyword = entry.keyword;
1762
item.postData = entry.postData;
1763
}
1764
break;
1765
case PlacesUtils.bookmarks.TYPE_FOLDER:
1766
item.type = PlacesUtils.TYPE_X_MOZ_PLACE_CONTAINER;
1767
// Mark root folders.
1768
if (item.guid == PlacesUtils.bookmarks.rootGuid) {
1769
item.root = "placesRoot";
1770
} else if (item.guid == PlacesUtils.bookmarks.menuGuid) {
1771
item.root = "bookmarksMenuFolder";
1772
} else if (item.guid == PlacesUtils.bookmarks.unfiledGuid) {
1773
item.root = "unfiledBookmarksFolder";
1774
} else if (item.guid == PlacesUtils.bookmarks.toolbarGuid) {
1775
item.root = "toolbarFolder";
1776
} else if (item.guid == PlacesUtils.bookmarks.mobileGuid) {
1777
item.root = "mobileFolder";
1778
}
1779
break;
1780
case PlacesUtils.bookmarks.TYPE_SEPARATOR:
1781
item.type = PlacesUtils.TYPE_X_MOZ_PLACE_SEPARATOR;
1782
break;
1783
default:
1784
Cu.reportError(`Unexpected bookmark type ${type}`);
1785
break;
1786
}
1787
return item;
1788
};
1789
1790
const QUERY_STR = `/* do not warn (bug no): cannot use an index */
1791
WITH RECURSIVE
1792
descendants(fk, level, type, id, guid, parent, parentGuid, position,
1793
title, dateAdded, lastModified) AS (
1794
SELECT b1.fk, 0, b1.type, b1.id, b1.guid, b1.parent,
1795
(SELECT guid FROM moz_bookmarks WHERE id = b1.parent),
1796
b1.position, b1.title, b1.dateAdded, b1.lastModified
1797
FROM moz_bookmarks b1 WHERE b1.guid=:item_guid
1798
UNION ALL
1799
SELECT b2.fk, level + 1, b2.type, b2.id, b2.guid, b2.parent,
1800
descendants.guid, b2.position, b2.title, b2.dateAdded,
1801
b2.lastModified
1802
FROM moz_bookmarks b2
1803
JOIN descendants ON b2.parent = descendants.id AND b2.id <> :tags_folder)
1804
SELECT d.level, d.id, d.guid, d.parent, d.parentGuid, d.type,
1805
d.position AS [index], IFNULL(d.title, '') AS title, d.dateAdded,
1806
d.lastModified, h.url, (SELECT icon_url FROM moz_icons i
1807
JOIN moz_icons_to_pages ON icon_id = i.id
1808
JOIN moz_pages_w_icons pi ON page_id = pi.id
1809
WHERE pi.page_url_hash = hash(h.url) AND pi.page_url = h.url
1810
ORDER BY width DESC LIMIT 1) AS iconuri,
1811
(SELECT GROUP_CONCAT(t.title, ',')
1812
FROM moz_bookmarks b2
1813
JOIN moz_bookmarks t ON t.id = +b2.parent AND t.parent = :tags_folder
1814
WHERE b2.fk = h.id
1815
) AS tags,
1816
(SELECT a.content FROM moz_annos a
1817
JOIN moz_anno_attributes n ON a.anno_attribute_id = n.id
1818
WHERE place_id = h.id AND n.name = :charset_anno
1819
) AS charset
1820
FROM descendants d
1821
LEFT JOIN moz_bookmarks b3 ON b3.id = d.parent
1822
LEFT JOIN moz_places h ON h.id = d.fk
1823
ORDER BY d.level, d.parent, d.position`;
1824
1825
if (!aItemGuid) {
1826
aItemGuid = this.bookmarks.rootGuid;
1827
}
1828
1829
let hasExcludeItemsCallback = aOptions.hasOwnProperty(
1830
"excludeItemsCallback"
1831
);
1832
let excludedParents = new Set();
1833
let shouldExcludeItem = (aItem, aParentGuid) => {
1834
let exclude =
1835
excludedParents.has(aParentGuid) ||
1836
aOptions.excludeItemsCallback(aItem);
1837
if (exclude) {
1838
if (aItem.type == this.TYPE_X_MOZ_PLACE_CONTAINER) {
1839
excludedParents.add(aItem.guid);
1840
}
1841
}
1842
return exclude;
1843
};
1844
1845
let rootItem = null;
1846
let parentsMap = new Map();
1847
let conn = await this.promiseDBConnection();
1848
let rows = await conn.executeCached(QUERY_STR, {
1849
tags_folder: PlacesUtils.tagsFolderId,
1850
charset_anno: PlacesUtils.CHARSET_ANNO,
1851
item_guid: aItemGuid,
1852
});
1853
let yieldCounter = 0;
1854
for (let row of rows) {
1855
let item;
1856
if (!rootItem) {
1857
try {
1858
// This is the first row.
1859
rootItem = item = await createItemInfoObject(row, true);
1860
Object.defineProperty(rootItem, "itemsCount", {
1861
value: 1,
1862
writable: true,
1863
enumerable: false,
1864
configurable: false,
1865
});
1866
} catch (ex) {
1867
Cu.reportError("Failed to fetch the data for the root item");
1868
throw ex;
1869
}
1870
} else {
1871
try {
1872
// Our query guarantees that we always visit parents ahead of their
1873
// children.
1874
item = await createItemInfoObject(row, false);
1875
let parentGuid = row.getResultByName("parentGuid");
1876
if (hasExcludeItemsCallback && shouldExcludeItem(item, parentGuid)) {
1877
continue;
1878
}
1879
1880
let parentItem = parentsMap.get(parentGuid);
1881
if ("children" in parentItem) {
1882
parentItem.children.push(item);
1883
} else {
1884
parentItem.children = [item];
1885
}
1886
1887
rootItem.itemsCount++;
1888
} catch (ex) {
1889
// This is a bogus child, report and skip it.
1890
Cu.reportError("Failed to fetch the data for an item " + ex);
1891
continue;
1892
}
1893
}
1894
1895
if (item.type == this.TYPE_X_MOZ_PLACE_CONTAINER) {
1896
parentsMap.set(item.guid, item);
1897
}
1898
1899
// With many bookmarks we end up stealing the CPU - even with yielding!
1900
// So we let everyone else have a go every few items (bug 1186714).
1901
if (++yieldCounter % 50 == 0) {
1902
await new Promise(resolve => {
1903
Services.tm.dispatchToMainThread(resolve);
1904
});
1905
}
1906
}
1907
1908
return rootItem;
1909
},
1910
1911
/**
1912
* Returns a generator that iterates over `array` and yields slices of no
1913
* more than `chunkLength` elements at a time.
1914
*
1915
* @param {Array} array An array containing zero or more elements.
1916
* @param {number} chunkLength The maximum number of elements in each chunk.
1917
* @yields {Array} A chunk of the array.
1918
* @throws if `chunkLength` is negative or not an integer.
1919
*/
1920
*chunkArray(array, chunkLength) {
1921
if (chunkLength <= 0 || !Number.isInteger(chunkLength)) {
1922
throw new TypeError("Chunk length must be a positive integer");
1923
}
1924
if (!array.length) {
1925
return;
1926
}
1927
if (array.length <= chunkLength) {
1928
yield array;
1929
return;
1930
}
1931
let startIndex = 0;
1932
while (startIndex < array.length) {
1933
yield array.slice(startIndex, (startIndex += chunkLength));
1934
}
1935
},
1936
};
1937
1938
XPCOMUtils.defineLazyGetter(PlacesUtils, "history", function() {
1939
let hs = Cc["@mozilla.org/browser/nav-history-service;1"].getService(
1940
Ci.nsINavHistoryService
1941
);
1942
return Object.freeze(
1943
new Proxy(hs, {
1944
get(target, name) {
1945
let property, object;
1946
if (name in target) {
1947
property = target[name];
1948
object = target;
1949
} else {
1950
property = History[name];
1951
object = History;
1952
}
1953
if (typeof property == "function") {
1954
return property.bind(object);
1955
}
1956
return property;
1957
},
1958
})
1959
);
1960
});
1961
1962
XPCOMUtils.defineLazyServiceGetter(
1963
PlacesUtils,
1964
"favicons",
1965
"@mozilla.org/browser/favicon-service;1",
1966
"nsIFaviconService"
1967
);
1968
1969
XPCOMUtils.defineLazyServiceGetter(
1970
this,
1971
"bmsvc",
1972
"@mozilla.org/browser/nav-bookmarks-service;1",
1973
"nsINavBookmarksService"
1974
);
1975
XPCOMUtils.defineLazyGetter(PlacesUtils, "bookmarks", () => {
1976
return Object.freeze(
1977
new Proxy(Bookmarks, {
1978
get: (target, name) =>
1979
Bookmarks.hasOwnProperty(name) ? Bookmarks[name] : bmsvc[name],
1980
})
1981
);
1982
});
1983
1984
XPCOMUtils.defineLazyServiceGetter(
1985
PlacesUtils,
1986
"annotations",
1987
"@mozilla.org/browser/annotation-service;1",
1988
"nsIAnnotationService"
1989
);
1990
1991
XPCOMUtils.defineLazyServiceGetter(
1992
PlacesUtils,
1993
"tagging",
1994
"@mozilla.org/browser/tagging-service;1",
1995
"nsITaggingService"
1996
);
1997
1998
XPCOMUtils.defineLazyGetter(this, "bundle", function() {
1999
const PLACES_STRING_BUNDLE_URI = "chrome://places/locale/places.properties";
2000
return Services.strings.createBundle(PLACES_STRING_BUNDLE_URI);
2001
});
2002
2003
// This is just used as a reasonably-random value for copy & paste / drag operations.
2004
XPCOMUtils.defineLazyGetter(PlacesUtils, "instanceId", () => {
2005
return PlacesUtils.history.makeGuid();
2006
});
2007
2008
/**
2009
* Setup internal databases for closing properly during shutdown.
2010
*
2011
* 1. Places initiates shutdown.
2012
* 2. Before places can move to the step where it closes the low-level connection,
2013