1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/bookmarks/browser/bookmark_utils.h"
9 #include "base/basictypes.h"
10 #include "base/bind.h"
11 #include "base/containers/hash_tables.h"
12 #include "base/files/file_path.h"
13 #include "base/i18n/case_conversion.h"
14 #include "base/i18n/string_search.h"
15 #include "base/metrics/user_metrics_action.h"
16 #include "base/prefs/pref_service.h"
17 #include "base/strings/string_util.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "base/time/time.h"
21 #include "components/bookmarks/browser/bookmark_client.h"
22 #include "components/bookmarks/browser/bookmark_model.h"
23 #include "components/bookmarks/browser/scoped_group_bookmark_actions.h"
24 #include "components/bookmarks/common/bookmark_pref_names.h"
25 #include "components/pref_registry/pref_registry_syncable.h"
26 #include "components/query_parser/query_parser.h"
27 #include "net/base/net_util.h"
28 #include "ui/base/clipboard/clipboard.h"
29 #include "ui/base/models/tree_node_iterator.h"
38 // The maximum length of URL or title returned by the Cleanup functions.
39 const size_t kCleanedUpUrlMaxLength
= 1024u;
40 const size_t kCleanedUpTitleMaxLength
= 1024u;
42 void CloneBookmarkNodeImpl(BookmarkModel
* model
,
43 const BookmarkNodeData::Element
& element
,
44 const BookmarkNode
* parent
,
46 bool reset_node_times
) {
47 // Make sure to not copy non clonable keys.
48 BookmarkNode::MetaInfoMap meta_info_map
= element
.meta_info_map
;
49 for (const std::string
& key
: model
->non_cloned_keys())
50 meta_info_map
.erase(key
);
53 Time date_added
= reset_node_times
? Time::Now() : element
.date_added
;
54 DCHECK(!date_added
.is_null());
56 model
->AddURLWithCreationTimeAndMetaInfo(parent
,
63 const BookmarkNode
* cloned_node
= model
->AddFolderWithMetaInfo(
64 parent
, index_to_add_at
, element
.title
, &meta_info_map
);
65 if (!reset_node_times
) {
66 DCHECK(!element
.date_folder_modified
.is_null());
67 model
->SetDateFolderModified(cloned_node
, element
.date_folder_modified
);
69 for (int i
= 0; i
< static_cast<int>(element
.children
.size()); ++i
)
70 CloneBookmarkNodeImpl(model
, element
.children
[i
], cloned_node
, i
,
75 // Comparison function that compares based on date modified of the two nodes.
76 bool MoreRecentlyModified(const BookmarkNode
* n1
, const BookmarkNode
* n2
) {
77 return n1
->date_folder_modified() > n2
->date_folder_modified();
80 // Returns true if |text| contains each string in |words|. This is used when
81 // searching for bookmarks.
82 bool DoesBookmarkTextContainWords(const base::string16
& text
,
83 const std::vector
<base::string16
>& words
) {
84 for (size_t i
= 0; i
< words
.size(); ++i
) {
85 if (!base::i18n::StringSearchIgnoringCaseAndAccents(
86 words
[i
], text
, NULL
, NULL
)) {
93 // Returns true if |node|s title or url contains the strings in |words|.
94 // |languages| argument is user's accept-language setting to decode IDN.
95 bool DoesBookmarkContainWords(const BookmarkNode
* node
,
96 const std::vector
<base::string16
>& words
,
97 const std::string
& languages
) {
99 DoesBookmarkTextContainWords(node
->GetTitle(), words
) ||
100 DoesBookmarkTextContainWords(
101 base::UTF8ToUTF16(node
->url().spec()), words
) ||
102 DoesBookmarkTextContainWords(net::FormatUrl(
103 node
->url(), languages
, net::kFormatUrlOmitNothing
,
104 net::UnescapeRule::NORMAL
, NULL
, NULL
, NULL
), words
);
107 // This is used with a tree iterator to skip subtrees which are not visible.
108 bool PruneInvisibleFolders(const BookmarkNode
* node
) {
109 return !node
->IsVisible();
112 // This traces parents up to root, determines if node is contained in a
114 bool HasSelectedAncestor(BookmarkModel
* model
,
115 const std::vector
<const BookmarkNode
*>& selected_nodes
,
116 const BookmarkNode
* node
) {
117 if (!node
|| model
->is_permanent_node(node
))
120 for (size_t i
= 0; i
< selected_nodes
.size(); ++i
)
121 if (node
->id() == selected_nodes
[i
]->id())
124 return HasSelectedAncestor(model
, selected_nodes
, node
->parent());
127 const BookmarkNode
* GetNodeByID(const BookmarkNode
* node
, int64 id
) {
128 if (node
->id() == id
)
131 for (int i
= 0, child_count
= node
->child_count(); i
< child_count
; ++i
) {
132 const BookmarkNode
* result
= GetNodeByID(node
->GetChild(i
), id
);
139 // Attempts to shorten a URL safely (i.e., by preventing the end of the URL
140 // from being in the middle of an escape sequence) to no more than
141 // kCleanedUpUrlMaxLength characters, returning the result.
142 std::string
TruncateUrl(const std::string
& url
) {
143 if (url
.length() <= kCleanedUpUrlMaxLength
)
146 // If we're in the middle of an escape sequence, truncate just before it.
147 if (url
[kCleanedUpUrlMaxLength
- 1] == '%')
148 return url
.substr(0, kCleanedUpUrlMaxLength
- 1);
149 if (url
[kCleanedUpUrlMaxLength
- 2] == '%')
150 return url
.substr(0, kCleanedUpUrlMaxLength
- 2);
152 return url
.substr(0, kCleanedUpUrlMaxLength
);
155 // Returns the URL from the clipboard. If there is no URL an empty URL is
157 GURL
GetUrlFromClipboard() {
158 base::string16 url_text
;
160 ui::Clipboard::GetForCurrentThread()->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE
,
163 return GURL(url_text
);
168 QueryFields::QueryFields() {}
169 QueryFields::~QueryFields() {}
171 void CloneBookmarkNode(BookmarkModel
* model
,
172 const std::vector
<BookmarkNodeData::Element
>& elements
,
173 const BookmarkNode
* parent
,
175 bool reset_node_times
) {
176 if (!parent
->is_folder() || !model
) {
180 for (size_t i
= 0; i
< elements
.size(); ++i
) {
181 CloneBookmarkNodeImpl(model
, elements
[i
], parent
,
182 index_to_add_at
+ static_cast<int>(i
),
187 void CopyToClipboard(BookmarkModel
* model
,
188 const std::vector
<const BookmarkNode
*>& nodes
,
193 // Create array of selected nodes with descendants filtered out.
194 std::vector
<const BookmarkNode
*> filtered_nodes
;
195 for (size_t i
= 0; i
< nodes
.size(); ++i
)
196 if (!HasSelectedAncestor(model
, nodes
, nodes
[i
]->parent()))
197 filtered_nodes
.push_back(nodes
[i
]);
199 BookmarkNodeData(filtered_nodes
).
200 WriteToClipboard(ui::CLIPBOARD_TYPE_COPY_PASTE
);
203 ScopedGroupBookmarkActions
group_cut(model
);
204 for (size_t i
= 0; i
< filtered_nodes
.size(); ++i
) {
205 int index
= filtered_nodes
[i
]->parent()->GetIndexOf(filtered_nodes
[i
]);
207 model
->Remove(filtered_nodes
[i
]->parent(), index
);
212 // Updates |title| such that |url| and |title| pair are unique among the
213 // children of |parent|.
214 void MakeTitleUnique(const BookmarkModel
* model
,
215 const BookmarkNode
* parent
,
217 base::string16
* title
) {
218 base::hash_set
<base::string16
> titles
;
219 for (int i
= 0; i
< parent
->child_count(); i
++) {
220 const BookmarkNode
* node
= parent
->GetChild(i
);
221 if (node
->is_url() && (url
== node
->url()) &&
222 StartsWith(node
->GetTitle(), *title
, false)) {
223 titles
.insert(node
->GetTitle());
227 if (titles
.find(*title
) == titles
.end())
230 for (size_t i
= 0; i
< titles
.size(); i
++) {
231 const base::string16
new_title(*title
+
232 base::ASCIIToUTF16(base::StringPrintf(
233 " (%lu)", (unsigned long)(i
+ 1))));
234 if (titles
.find(new_title
) == titles
.end()) {
242 void PasteFromClipboard(BookmarkModel
* model
,
243 const BookmarkNode
* parent
,
248 BookmarkNodeData bookmark_data
;
249 if (!bookmark_data
.ReadFromClipboard(ui::CLIPBOARD_TYPE_COPY_PASTE
)) {
250 GURL url
= GetUrlFromClipboard();
253 BookmarkNode
node(url
);
254 node
.SetTitle(base::ASCIIToUTF16(url
.spec()));
255 bookmark_data
= BookmarkNodeData(&node
);
258 index
= parent
->child_count();
259 ScopedGroupBookmarkActions
group_paste(model
);
261 if (bookmark_data
.size() == 1 &&
262 model
->IsBookmarked(bookmark_data
.elements
[0].url
)) {
263 MakeTitleUnique(model
,
265 bookmark_data
.elements
[0].url
,
266 &bookmark_data
.elements
[0].title
);
269 CloneBookmarkNode(model
, bookmark_data
.elements
, parent
, index
, true);
272 bool CanPasteFromClipboard(BookmarkModel
* model
, const BookmarkNode
* node
) {
273 if (!node
|| !model
->client()->CanBeEditedByUser(node
))
275 return (BookmarkNodeData::ClipboardContainsBookmarks() ||
276 GetUrlFromClipboard().is_valid());
279 std::vector
<const BookmarkNode
*> GetMostRecentlyModifiedUserFolders(
280 BookmarkModel
* model
,
282 std::vector
<const BookmarkNode
*> nodes
;
283 ui::TreeNodeIterator
<const BookmarkNode
> iterator(
284 model
->root_node(), base::Bind(&PruneInvisibleFolders
));
286 while (iterator
.has_next()) {
287 const BookmarkNode
* parent
= iterator
.Next();
288 if (!model
->client()->CanBeEditedByUser(parent
))
290 if (parent
->is_folder() && parent
->date_folder_modified() > Time()) {
291 if (max_count
== 0) {
292 nodes
.push_back(parent
);
294 std::vector
<const BookmarkNode
*>::iterator i
=
295 std::upper_bound(nodes
.begin(), nodes
.end(), parent
,
296 &MoreRecentlyModified
);
297 if (nodes
.size() < max_count
|| i
!= nodes
.end()) {
298 nodes
.insert(i
, parent
);
299 while (nodes
.size() > max_count
)
303 } // else case, the root node, which we don't care about or imported nodes
304 // (which have a time of 0).
307 if (nodes
.size() < max_count
) {
308 // Add the permanent nodes if there is space. The permanent nodes are the
309 // only children of the root_node.
310 const BookmarkNode
* root_node
= model
->root_node();
312 for (int i
= 0; i
< root_node
->child_count(); ++i
) {
313 const BookmarkNode
* node
= root_node
->GetChild(i
);
314 if (node
->IsVisible() && model
->client()->CanBeEditedByUser(node
) &&
315 std::find(nodes
.begin(), nodes
.end(), node
) == nodes
.end()) {
316 nodes
.push_back(node
);
318 if (nodes
.size() == max_count
)
326 void GetMostRecentlyAddedEntries(BookmarkModel
* model
,
328 std::vector
<const BookmarkNode
*>* nodes
) {
329 ui::TreeNodeIterator
<const BookmarkNode
> iterator(model
->root_node());
330 while (iterator
.has_next()) {
331 const BookmarkNode
* node
= iterator
.Next();
332 if (node
->is_url()) {
333 std::vector
<const BookmarkNode
*>::iterator insert_position
=
334 std::upper_bound(nodes
->begin(), nodes
->end(), node
,
336 if (nodes
->size() < count
|| insert_position
!= nodes
->end()) {
337 nodes
->insert(insert_position
, node
);
338 while (nodes
->size() > count
)
345 bool MoreRecentlyAdded(const BookmarkNode
* n1
, const BookmarkNode
* n2
) {
346 return n1
->date_added() > n2
->date_added();
349 void GetBookmarksMatchingProperties(BookmarkModel
* model
,
350 const QueryFields
& query
,
352 const std::string
& languages
,
353 std::vector
<const BookmarkNode
*>* nodes
) {
354 std::vector
<base::string16
> query_words
;
355 query_parser::QueryParser parser
;
356 if (query
.word_phrase_query
) {
357 parser
.ParseQueryWords(base::i18n::ToLower(*query
.word_phrase_query
),
358 query_parser::MatchingAlgorithm::DEFAULT
,
360 if (query_words
.empty())
364 ui::TreeNodeIterator
<const BookmarkNode
> iterator(model
->root_node());
365 while (iterator
.has_next()) {
366 const BookmarkNode
* node
= iterator
.Next();
367 if ((!query_words
.empty() &&
368 !DoesBookmarkContainWords(node
, query_words
, languages
)) ||
369 model
->is_permanent_node(node
)) {
373 // Check against bare url spec and IDN-decoded url.
374 if (!node
->is_url() ||
375 !(base::UTF8ToUTF16(node
->url().spec()) == *query
.url
||
377 node
->url(), languages
, net::kFormatUrlOmitNothing
,
378 net::UnescapeRule::NORMAL
, NULL
, NULL
, NULL
) == *query
.url
)) {
382 if (query
.title
&& node
->GetTitle() != *query
.title
)
385 nodes
->push_back(node
);
386 if (nodes
->size() == max_count
)
391 void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable
* registry
) {
392 registry
->RegisterBooleanPref(
393 prefs::kShowBookmarkBar
,
395 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF
);
396 registry
->RegisterBooleanPref(
397 prefs::kEditBookmarksEnabled
,
399 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF
);
400 registry
->RegisterBooleanPref(
401 prefs::kShowAppsShortcutInBookmarkBar
,
403 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF
);
404 registry
->RegisterBooleanPref(
405 prefs::kShowManagedBookmarksInBookmarkBar
,
407 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF
);
410 const BookmarkNode
* GetParentForNewNodes(
411 const BookmarkNode
* parent
,
412 const std::vector
<const BookmarkNode
*>& selection
,
414 const BookmarkNode
* real_parent
= parent
;
416 if (selection
.size() == 1 && selection
[0]->is_folder())
417 real_parent
= selection
[0];
420 if (selection
.size() == 1 && selection
[0]->is_url()) {
421 *index
= real_parent
->GetIndexOf(selection
[0]) + 1;
423 // Node doesn't exist in parent, add to end.
425 *index
= real_parent
->child_count();
428 *index
= real_parent
->child_count();
435 void DeleteBookmarkFolders(BookmarkModel
* model
,
436 const std::vector
<int64
>& ids
) {
437 // Remove the folders that were removed. This has to be done after all the
438 // other changes have been committed.
439 for (std::vector
<int64
>::const_iterator iter
= ids
.begin();
442 const BookmarkNode
* node
= GetBookmarkNodeByID(model
, *iter
);
445 const BookmarkNode
* parent
= node
->parent();
446 model
->Remove(parent
, parent
->GetIndexOf(node
));
450 void AddIfNotBookmarked(BookmarkModel
* model
,
452 const base::string16
& title
) {
453 if (IsBookmarkedByUser(model
, url
))
454 return; // Nothing to do, a user bookmark with that url already exists.
455 model
->client()->RecordAction(base::UserMetricsAction("BookmarkAdded"));
456 const BookmarkNode
* parent
= model
->GetParentForNewNodes();
457 model
->AddURL(parent
, parent
->child_count(), title
, url
);
460 void RemoveAllBookmarks(BookmarkModel
* model
, const GURL
& url
) {
461 std::vector
<const BookmarkNode
*> bookmarks
;
462 model
->GetNodesByURL(url
, &bookmarks
);
464 // Remove all the user bookmarks.
465 for (size_t i
= 0; i
< bookmarks
.size(); ++i
) {
466 const BookmarkNode
* node
= bookmarks
[i
];
467 int index
= node
->parent()->GetIndexOf(node
);
468 if (index
> -1 && model
->client()->CanBeEditedByUser(node
))
469 model
->Remove(node
->parent(), index
);
473 base::string16
CleanUpUrlForMatching(
475 const std::string
& languages
,
476 base::OffsetAdjuster::Adjustments
* adjustments
) {
477 base::OffsetAdjuster::Adjustments tmp_adjustments
;
478 return base::i18n::ToLower(net::FormatUrlWithAdjustments(
479 GURL(TruncateUrl(gurl
.spec())), languages
,
480 net::kFormatUrlOmitUsernamePassword
,
481 net::UnescapeRule::SPACES
| net::UnescapeRule::URL_SPECIAL_CHARS
,
482 NULL
, NULL
, adjustments
? adjustments
: &tmp_adjustments
));
485 base::string16
CleanUpTitleForMatching(const base::string16
& title
) {
486 return base::i18n::ToLower(title
.substr(0u, kCleanedUpTitleMaxLength
));
489 bool CanAllBeEditedByUser(BookmarkClient
* client
,
490 const std::vector
<const BookmarkNode
*>& nodes
) {
491 for (size_t i
= 0; i
< nodes
.size(); ++i
) {
492 if (!client
->CanBeEditedByUser(nodes
[i
]))
498 bool IsBookmarkedByUser(BookmarkModel
* model
, const GURL
& url
) {
499 std::vector
<const BookmarkNode
*> nodes
;
500 model
->GetNodesByURL(url
, &nodes
);
501 for (size_t i
= 0; i
< nodes
.size(); ++i
) {
502 if (model
->client()->CanBeEditedByUser(nodes
[i
]))
508 const BookmarkNode
* GetBookmarkNodeByID(const BookmarkModel
* model
, int64 id
) {
509 // TODO(sky): TreeNode needs a method that visits all nodes using a predicate.
510 return GetNodeByID(model
->root_node(), id
);
513 bool IsDescendantOf(const bookmarks::BookmarkNode
* node
,
514 const bookmarks::BookmarkNode
* root
) {
515 return node
&& node
->HasAncestor(root
);
518 bool HasDescendantsOf(const std::vector
<const bookmarks::BookmarkNode
*>& list
,
519 const bookmarks::BookmarkNode
* root
) {
520 for (const BookmarkNode
* node
: list
) {
521 if (IsDescendantOf(node
, root
))
527 } // namespace bookmarks