Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / chrome / utility / importer / firefox_importer.cc
1 // Copyright 2013 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.
4
5 #include "chrome/utility/importer/firefox_importer.h"
6
7 #include <set>
8
9 #include "base/files/file_enumerator.h"
10 #include "base/files/file_util.h"
11 #include "base/json/json_file_value_serializer.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/stl_util.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "chrome/common/importer/firefox_importer_utils.h"
18 #include "chrome/common/importer/imported_bookmark_entry.h"
19 #include "chrome/common/importer/imported_favicon_usage.h"
20 #include "chrome/common/importer/importer_autofill_form_data_entry.h"
21 #include "chrome/common/importer/importer_bridge.h"
22 #include "chrome/common/importer/importer_url_row.h"
23 #include "chrome/grit/generated_resources.h"
24 #include "chrome/utility/importer/bookmark_html_reader.h"
25 #include "chrome/utility/importer/favicon_reencode.h"
26 #include "chrome/utility/importer/nss_decryptor.h"
27 #include "components/autofill/core/common/password_form.h"
28 #include "sql/connection.h"
29 #include "sql/statement.h"
30 #include "url/gurl.h"
31
32 namespace {
33
34 // Original definition is in http://mxr.mozilla.org/firefox/source/toolkit/
35 //  components/places/public/nsINavBookmarksService.idl
36 enum BookmarkItemType {
37   TYPE_BOOKMARK = 1,
38   TYPE_FOLDER = 2,
39   TYPE_SEPARATOR = 3,
40   TYPE_DYNAMIC_CONTAINER = 4
41 };
42
43 // Loads the default bookmarks in the Firefox installed at |app_path|,
44 // and stores their locations in |urls|.
45 void LoadDefaultBookmarks(const base::FilePath& app_path,
46                           std::set<GURL>* urls) {
47   base::FilePath file = app_path.AppendASCII("defaults")
48       .AppendASCII("profile")
49       .AppendASCII("bookmarks.html");
50   urls->clear();
51
52   std::vector<ImportedBookmarkEntry> bookmarks;
53   bookmark_html_reader::ImportBookmarksFile(base::Callback<bool(void)>(),
54                                             base::Callback<bool(const GURL&)>(),
55                                             file,
56                                             &bookmarks,
57                                             NULL);
58   for (size_t i = 0; i < bookmarks.size(); ++i)
59     urls->insert(bookmarks[i].url);
60 }
61
62 // Returns true if |url| has a valid scheme that we allow to import. We
63 // filter out the URL with a unsupported scheme.
64 bool CanImportURL(const GURL& url) {
65   // The URL is not valid.
66   if (!url.is_valid())
67     return false;
68
69   // Filter out the URLs with unsupported schemes.
70   const char* const kInvalidSchemes[] = {"wyciwyg", "place", "about", "chrome"};
71   for (size_t i = 0; i < arraysize(kInvalidSchemes); ++i) {
72     if (url.SchemeIs(kInvalidSchemes[i]))
73       return false;
74   }
75
76   return true;
77 }
78
79 }  // namespace
80
81 struct FirefoxImporter::BookmarkItem {
82   int parent;
83   int id;
84   GURL url;
85   base::string16 title;
86   BookmarkItemType type;
87   std::string keyword;
88   base::Time date_added;
89   int64 favicon;
90   bool empty_folder;
91 };
92
93 FirefoxImporter::FirefoxImporter() {
94 }
95
96 FirefoxImporter::~FirefoxImporter() {
97 }
98
99 void FirefoxImporter::StartImport(
100     const importer::SourceProfile& source_profile,
101     uint16 items,
102     ImporterBridge* bridge) {
103   bridge_ = bridge;
104   source_path_ = source_profile.source_path;
105   app_path_ = source_profile.app_path;
106
107 #if defined(OS_POSIX)
108   locale_ = source_profile.locale;
109 #endif
110
111   // The order here is important!
112   bridge_->NotifyStarted();
113   if ((items & importer::HOME_PAGE) && !cancelled()) {
114     bridge_->NotifyItemStarted(importer::HOME_PAGE);
115     ImportHomepage();  // Doesn't have a UI item.
116     bridge_->NotifyItemEnded(importer::HOME_PAGE);
117   }
118
119   // Note history should be imported before bookmarks because bookmark import
120   // will also import favicons and we store favicon for a URL only if the URL
121   // exist in history or bookmarks.
122   if ((items & importer::HISTORY) && !cancelled()) {
123     bridge_->NotifyItemStarted(importer::HISTORY);
124     ImportHistory();
125     bridge_->NotifyItemEnded(importer::HISTORY);
126   }
127
128   if ((items & importer::FAVORITES) && !cancelled()) {
129     bridge_->NotifyItemStarted(importer::FAVORITES);
130     ImportBookmarks();
131     bridge_->NotifyItemEnded(importer::FAVORITES);
132   }
133   if ((items & importer::SEARCH_ENGINES) && !cancelled()) {
134     bridge_->NotifyItemStarted(importer::SEARCH_ENGINES);
135     ImportSearchEngines();
136     bridge_->NotifyItemEnded(importer::SEARCH_ENGINES);
137   }
138   if ((items & importer::PASSWORDS) && !cancelled()) {
139     bridge_->NotifyItemStarted(importer::PASSWORDS);
140     ImportPasswords();
141     bridge_->NotifyItemEnded(importer::PASSWORDS);
142   }
143   if ((items & importer::AUTOFILL_FORM_DATA) && !cancelled()) {
144     bridge_->NotifyItemStarted(importer::AUTOFILL_FORM_DATA);
145     ImportAutofillFormData();
146     bridge_->NotifyItemEnded(importer::AUTOFILL_FORM_DATA);
147   }
148   bridge_->NotifyEnded();
149 }
150
151 void FirefoxImporter::ImportHistory() {
152   base::FilePath file = source_path_.AppendASCII("places.sqlite");
153   if (!base::PathExists(file))
154     return;
155
156   sql::Connection db;
157   if (!db.Open(file))
158     return;
159
160   // |visit_type| represent the transition type of URLs (typed, click,
161   // redirect, bookmark, etc.) We eliminate some URLs like sub-frames and
162   // redirects, since we don't want them to appear in history.
163   // Firefox transition types are defined in:
164   //   toolkit/components/places/public/nsINavHistoryService.idl
165   const char query[] =
166       "SELECT h.url, h.title, h.visit_count, "
167       "h.hidden, h.typed, v.visit_date "
168       "FROM moz_places h JOIN moz_historyvisits v "
169       "ON h.id = v.place_id "
170       "WHERE v.visit_type <= 3";
171
172   sql::Statement s(db.GetUniqueStatement(query));
173
174   std::vector<ImporterURLRow> rows;
175   while (s.Step() && !cancelled()) {
176     GURL url(s.ColumnString(0));
177
178     // Filter out unwanted URLs.
179     if (!CanImportURL(url))
180       continue;
181
182     ImporterURLRow row(url);
183     row.title = s.ColumnString16(1);
184     row.visit_count = s.ColumnInt(2);
185     row.hidden = s.ColumnInt(3) == 1;
186     row.typed_count = s.ColumnInt(4);
187     row.last_visit = base::Time::FromTimeT(s.ColumnInt64(5)/1000000);
188
189     rows.push_back(row);
190   }
191
192   if (!rows.empty() && !cancelled())
193     bridge_->SetHistoryItems(rows, importer::VISIT_SOURCE_FIREFOX_IMPORTED);
194 }
195
196 void FirefoxImporter::ImportBookmarks() {
197   base::FilePath file = source_path_.AppendASCII("places.sqlite");
198   if (!base::PathExists(file))
199     return;
200
201   sql::Connection db;
202   if (!db.Open(file))
203     return;
204
205   // Get the bookmark folders that we are interested in.
206   int toolbar_folder_id = -1;
207   int menu_folder_id = -1;
208   int unsorted_folder_id = -1;
209   LoadRootNodeID(&db, &toolbar_folder_id, &menu_folder_id, &unsorted_folder_id);
210
211   // Load livemark IDs.
212   std::set<int> livemark_id;
213   LoadLivemarkIDs(&db, &livemark_id);
214
215   // Load the default bookmarks.
216   std::set<GURL> default_urls;
217   LoadDefaultBookmarks(app_path_, &default_urls);
218
219   BookmarkList list;
220   GetTopBookmarkFolder(&db, toolbar_folder_id, &list);
221   GetTopBookmarkFolder(&db, menu_folder_id, &list);
222   GetTopBookmarkFolder(&db, unsorted_folder_id, &list);
223   size_t count = list.size();
224   for (size_t i = 0; i < count; ++i)
225     GetWholeBookmarkFolder(&db, &list, i, NULL);
226
227   std::vector<ImportedBookmarkEntry> bookmarks;
228   std::vector<importer::URLKeywordInfo> url_keywords;
229   FaviconMap favicon_map;
230
231   // TODO(jcampan): http://b/issue?id=1196285 we do not support POST based
232   //                keywords yet.  We won't include them in the list.
233   std::set<int> post_keyword_ids;
234   const char query[] =
235       "SELECT b.id FROM moz_bookmarks b "
236       "INNER JOIN moz_items_annos ia ON ia.item_id = b.id "
237       "INNER JOIN moz_anno_attributes aa ON ia.anno_attribute_id = aa.id "
238       "WHERE aa.name = 'bookmarkProperties/POSTData'";
239   sql::Statement s(db.GetUniqueStatement(query));
240
241   if (!s.is_valid())
242     return;
243
244   while (s.Step() && !cancelled())
245     post_keyword_ids.insert(s.ColumnInt(0));
246
247   for (size_t i = 0; i < list.size(); ++i) {
248     BookmarkItem* item = list[i];
249
250     if (item->type == TYPE_FOLDER) {
251       // Folders are added implicitly on adding children, so we only explicitly
252       // add empty folders.
253       if (!item->empty_folder)
254         continue;
255     } else if (item->type == TYPE_BOOKMARK) {
256       // Import only valid bookmarks
257       if (!CanImportURL(item->url))
258         continue;
259     } else {
260       continue;
261     }
262
263     // Skip the default bookmarks and unwanted URLs.
264     if (default_urls.find(item->url) != default_urls.end() ||
265         post_keyword_ids.find(item->id) != post_keyword_ids.end())
266       continue;
267
268     // Find the bookmark path by tracing their links to parent folders.
269     std::vector<base::string16> path;
270     BookmarkItem* child = item;
271     bool found_path = false;
272     bool is_in_toolbar = false;
273     while (child->parent >= 0) {
274       BookmarkItem* parent = list[child->parent];
275       if (livemark_id.find(parent->id) != livemark_id.end()) {
276         // Don't import live bookmarks.
277         break;
278       }
279
280       if (parent->id != menu_folder_id) {
281         // To avoid excessive nesting, omit the name for the bookmarks menu
282         // folder.
283         path.insert(path.begin(), parent->title);
284       }
285
286       if (parent->id == toolbar_folder_id)
287         is_in_toolbar = true;
288
289       if (parent->id == toolbar_folder_id ||
290           parent->id == menu_folder_id ||
291           parent->id == unsorted_folder_id) {
292         // We've reached a root node, hooray!
293         found_path = true;
294         break;
295       }
296
297       child = parent;
298     }
299
300     if (!found_path)
301       continue;
302
303     ImportedBookmarkEntry entry;
304     entry.creation_time = item->date_added;
305     entry.title = item->title;
306     entry.url = item->url;
307     entry.path = path;
308     entry.in_toolbar = is_in_toolbar;
309     entry.is_folder = item->type == TYPE_FOLDER;
310
311     bookmarks.push_back(entry);
312
313     if (item->type == TYPE_BOOKMARK) {
314       if (item->favicon)
315         favicon_map[item->favicon].insert(item->url);
316
317       // This bookmark has a keyword, we should import it.
318       if (!item->keyword.empty() && item->url.is_valid()) {
319         importer::URLKeywordInfo url_keyword_info;
320         url_keyword_info.url = item->url;
321         url_keyword_info.keyword.assign(base::UTF8ToUTF16(item->keyword));
322         url_keyword_info.display_name = item->title;
323         url_keywords.push_back(url_keyword_info);
324       }
325     }
326   }
327
328   STLDeleteElements(&list);
329
330   // Write into profile.
331   if (!bookmarks.empty() && !cancelled()) {
332     const base::string16& first_folder_name =
333         bridge_->GetLocalizedString(IDS_BOOKMARK_GROUP_FROM_FIREFOX);
334     bridge_->AddBookmarks(bookmarks, first_folder_name);
335   }
336   if (!url_keywords.empty() && !cancelled()) {
337     bridge_->SetKeywords(url_keywords, false);
338   }
339   if (!favicon_map.empty() && !cancelled()) {
340     std::vector<ImportedFaviconUsage> favicons;
341     LoadFavicons(&db, favicon_map, &favicons);
342     bridge_->SetFavicons(favicons);
343   }
344 }
345
346 void FirefoxImporter::ImportPasswords() {
347   // Initializes NSS3.
348   NSSDecryptor decryptor;
349   if (!decryptor.Init(source_path_, source_path_) &&
350       !decryptor.Init(app_path_, source_path_)) {
351     return;
352   }
353
354   std::vector<autofill::PasswordForm> forms;
355   base::FilePath source_path = source_path_;
356   base::FilePath file = source_path.AppendASCII("signons.sqlite");
357   if (base::PathExists(file)) {
358     // Since Firefox 3.1, passwords are in signons.sqlite db.
359     decryptor.ReadAndParseSignons(file, &forms);
360   } else {
361     // Firefox 3.0 uses signons3.txt to store the passwords.
362     file = source_path.AppendASCII("signons3.txt");
363     if (!base::PathExists(file))
364       file = source_path.AppendASCII("signons2.txt");
365
366     std::string content;
367     base::ReadFileToString(file, &content);
368     decryptor.ParseSignons(content, &forms);
369   }
370
371   if (!cancelled()) {
372     for (size_t i = 0; i < forms.size(); ++i) {
373       if (!forms[i].username_value.empty() ||
374           !forms[i].password_value.empty() ||
375           forms[i].blacklisted_by_user) {
376         bridge_->SetPasswordForm(forms[i]);
377       }
378     }
379   }
380 }
381
382 void FirefoxImporter::ImportSearchEngines() {
383   std::vector<std::string> search_engine_data;
384   GetSearchEnginesXMLData(&search_engine_data);
385
386   bridge_->SetFirefoxSearchEnginesXMLData(search_engine_data);
387 }
388
389 void FirefoxImporter::ImportHomepage() {
390   GURL home_page = GetHomepage(source_path_);
391   if (home_page.is_valid() && !IsDefaultHomepage(home_page, app_path_)) {
392     bridge_->AddHomePage(home_page);
393   }
394 }
395
396 void FirefoxImporter::ImportAutofillFormData() {
397   base::FilePath file = source_path_.AppendASCII("formhistory.sqlite");
398   if (!base::PathExists(file))
399     return;
400
401   sql::Connection db;
402   if (!db.Open(file))
403     return;
404
405   const char query[] =
406       "SELECT fieldname, value, timesUsed, firstUsed, lastUsed FROM "
407       "moz_formhistory";
408
409   sql::Statement s(db.GetUniqueStatement(query));
410
411   std::vector<ImporterAutofillFormDataEntry> form_entries;
412   while (s.Step() && !cancelled()) {
413     ImporterAutofillFormDataEntry form_entry;
414     form_entry.name = s.ColumnString16(0);
415     form_entry.value = s.ColumnString16(1);
416     form_entry.times_used = s.ColumnInt(2);
417     form_entry.first_used = base::Time::FromTimeT(s.ColumnInt64(3) / 1000000);
418     form_entry.last_used = base::Time::FromTimeT(s.ColumnInt64(4) / 1000000);
419
420     // Don't import search bar history.
421     if (base::UTF16ToUTF8(form_entry.name) == "searchbar-history")
422       continue;
423
424     form_entries.push_back(form_entry);
425   }
426
427   if (!form_entries.empty() && !cancelled())
428     bridge_->SetAutofillFormData(form_entries);
429 }
430
431 void FirefoxImporter::GetSearchEnginesXMLData(
432     std::vector<std::string>* search_engine_data) {
433   base::FilePath file = source_path_.AppendASCII("search.sqlite");
434   if (!base::PathExists(file)) {
435     // Since Firefox 3.5, search engines are no longer stored in search.sqlite.
436     // Instead, search.json is used for storing search engines.
437     GetSearchEnginesXMLDataFromJSON(search_engine_data);
438     return;
439   }
440
441   sql::Connection db;
442   if (!db.Open(file))
443     return;
444
445   const char query[] =
446       "SELECT engineid FROM engine_data "
447       "WHERE engineid NOT IN "
448       "(SELECT engineid FROM engine_data "
449       "WHERE name='hidden') "
450       "ORDER BY value ASC";
451
452   sql::Statement s(db.GetUniqueStatement(query));
453   if (!s.is_valid())
454     return;
455
456   const base::FilePath searchplugins_path(FILE_PATH_LITERAL("searchplugins"));
457   // Search engine definitions are XMLs stored in two directories. Default
458   // engines are in the app directory (app_path_) and custom engines are
459   // in the profile directory (source_path_).
460
461   // Since Firefox 21, app_path_ engines are in 'browser' subdirectory:
462   base::FilePath app_path =
463       app_path_.AppendASCII("browser").Append(searchplugins_path);
464   if (!base::PathExists(app_path)) {
465     // This might be an older Firefox, try old location without the 'browser'
466     // path component:
467     app_path = app_path_.Append(searchplugins_path);
468   }
469
470   base::FilePath profile_path = source_path_.Append(searchplugins_path);
471
472   // Firefox doesn't store a search engine in its sqlite database unless the
473   // user has added a engine. So we get search engines from sqlite db as well
474   // as from the file system.
475   if (s.Step()) {
476     const std::string kAppPrefix("[app]/");
477     const std::string kProfilePrefix("[profile]/");
478     do {
479       base::FilePath file;
480       std::string engine(s.ColumnString(0));
481
482       // The string contains [app]/<name>.xml or [profile]/<name>.xml where
483       // the [app] and [profile] need to be replaced with the actual app or
484       // profile path.
485       size_t index = engine.find(kAppPrefix);
486       if (index != std::string::npos) {
487         // Remove '[app]/'.
488         file = app_path.AppendASCII(engine.substr(index + kAppPrefix.length()));
489       } else if ((index = engine.find(kProfilePrefix)) != std::string::npos) {
490         // Remove '[profile]/'.
491           file = profile_path.AppendASCII(
492               engine.substr(index + kProfilePrefix.length()));
493       } else {
494         // Looks like absolute path to the file.
495         file = base::FilePath::FromUTF8Unsafe(engine);
496       }
497       std::string file_data;
498       base::ReadFileToString(file, &file_data);
499       search_engine_data->push_back(file_data);
500     } while (s.Step() && !cancelled());
501   }
502
503 #if defined(OS_POSIX)
504   // Ubuntu-flavored Firefox supports locale-specific search engines via
505   // locale-named subdirectories. They fall back to en-US.
506   // See http://crbug.com/53899
507   // TODO(jshin): we need to make sure our locale code matches that of
508   // Firefox.
509   DCHECK(!locale_.empty());
510   base::FilePath locale_app_path = app_path.AppendASCII(locale_);
511   base::FilePath default_locale_app_path = app_path.AppendASCII("en-US");
512   if (base::DirectoryExists(locale_app_path))
513     app_path = locale_app_path;
514   else if (base::DirectoryExists(default_locale_app_path))
515     app_path = default_locale_app_path;
516 #endif
517
518   // Get search engine definition from file system.
519   base::FileEnumerator engines(app_path, false, base::FileEnumerator::FILES);
520   for (base::FilePath engine_path = engines.Next();
521        !engine_path.value().empty(); engine_path = engines.Next()) {
522     std::string file_data;
523     base::ReadFileToString(file, &file_data);
524     search_engine_data->push_back(file_data);
525   }
526 }
527
528 void FirefoxImporter::GetSearchEnginesXMLDataFromJSON(
529     std::vector<std::string>* search_engine_data) {
530   // search-metadata.json contains keywords for search engines. This
531   // file exists only if the user has set keywords for search engines.
532   base::FilePath search_metadata_json_file =
533       source_path_.AppendASCII("search-metadata.json");
534   JSONFileValueSerializer metadata_serializer(search_metadata_json_file);
535   scoped_ptr<base::Value> metadata_root(
536       metadata_serializer.Deserialize(NULL, NULL));
537   const base::DictionaryValue* search_metadata_root = NULL;
538   if (metadata_root)
539     metadata_root->GetAsDictionary(&search_metadata_root);
540
541   // search.json contains information about search engines to import.
542   base::FilePath search_json_file = source_path_.AppendASCII("search.json");
543   if (!base::PathExists(search_json_file))
544     return;
545
546   JSONFileValueSerializer serializer(search_json_file);
547   scoped_ptr<base::Value> root(serializer.Deserialize(NULL, NULL));
548   const base::DictionaryValue* search_root = NULL;
549   if (!root || !root->GetAsDictionary(&search_root))
550     return;
551
552   const std::string kDirectories("directories");
553   const base::DictionaryValue* search_directories = NULL;
554   if (!search_root->GetDictionary(kDirectories, &search_directories))
555     return;
556
557   // Dictionary |search_directories| contains a list of search engines
558   // (default and installed). The list can be found from key <engines>
559   // of the dictionary. Key <engines> is a grandchild of key <directories>.
560   // However, key <engines> parent's key is dynamic which depends on
561   // operating systems. For example,
562   //   Ubuntu (for default search engine):
563   //     /usr/lib/firefox/distribution/searchplugins/locale/en-US
564   //   Ubuntu (for installed search engines):
565   //     /home/<username>/.mozilla/firefox/lcd50n4n.default/searchplugins
566   //   Windows (for default search engine):
567   //     C:\\Program Files (x86)\\Mozilla Firefox\\browser\\searchplugins
568   // Therefore, it needs to be retrieved by searching.
569
570   for (base::DictionaryValue::Iterator it(*search_directories); !it.IsAtEnd();
571        it.Advance()) {
572     // The key of |it| may contains dot (.) which cannot be used as <key>
573     // for retrieving <engines>. Hence, it is needed to get |it| as dictionary.
574     // The resulted dictionary can be used for retrieving <engines>.
575     const std::string kEngines("engines");
576     const base::DictionaryValue* search_directory = NULL;
577     if (!it.value().GetAsDictionary(&search_directory))
578       continue;
579
580     const base::ListValue* search_engines = NULL;
581     if (!search_directory->GetList(kEngines, &search_engines))
582       continue;
583
584     const std::string kFilePath("filePath");
585     const std::string kHidden("_hidden");
586     for (size_t i = 0; i < search_engines->GetSize(); ++i) {
587       const base::DictionaryValue* engine_info = NULL;
588       if (!search_engines->GetDictionary(i, &engine_info))
589         continue;
590
591       bool is_hidden = false;
592       std::string file_path;
593       if (!engine_info->GetBoolean(kHidden, &is_hidden) ||
594           !engine_info->GetString(kFilePath, &file_path))
595         continue;
596
597       if (!is_hidden) {
598         const std::string kAppPrefix("[app]/");
599         const std::string kProfilePrefix("[profile]/");
600         base::FilePath xml_file = base::FilePath::FromUTF8Unsafe(file_path);
601
602         // If |file_path| contains [app] or [profile] then they need to be
603         // replaced with the actual app or profile path.
604         size_t index = file_path.find(kAppPrefix);
605         if (index != std::string::npos) {
606           // Replace '[app]/' with actual app path.
607           xml_file = app_path_.AppendASCII("searchplugins").AppendASCII(
608               file_path.substr(index + kAppPrefix.length()));
609         } else if ((index = file_path.find(kProfilePrefix)) !=
610                    std::string::npos) {
611           // Replace '[profile]/' with actual profile path.
612           xml_file = source_path_.AppendASCII("searchplugins").AppendASCII(
613               file_path.substr(index + kProfilePrefix.length()));
614         }
615
616         std::string file_data;
617         base::ReadFileToString(xml_file, &file_data);
618
619         // If a keyword is mentioned for this search engine, then add
620         // it to the XML string as an <Alias> element and use this updated
621         // string.
622         const base::DictionaryValue* search_xml_path = NULL;
623         if (search_metadata_root && search_metadata_root->HasKey(file_path) &&
624             search_metadata_root->GetDictionaryWithoutPathExpansion(
625                 file_path, &search_xml_path)) {
626           std::string alias;
627           search_xml_path->GetString("alias", &alias);
628
629           // Add <Alias> element as the last child element.
630           size_t end_of_parent = file_data.find("</SearchPlugin>");
631           if (end_of_parent != std::string::npos && !alias.empty())
632             file_data.insert(end_of_parent, "<Alias>" + alias + "</Alias> \n");
633         }
634         search_engine_data->push_back(file_data);
635       }
636     }
637   }
638 }
639
640 void FirefoxImporter::LoadRootNodeID(sql::Connection* db,
641                                       int* toolbar_folder_id,
642                                       int* menu_folder_id,
643                                       int* unsorted_folder_id) {
644   static const char kToolbarFolderName[] = "toolbar";
645   static const char kMenuFolderName[] = "menu";
646   static const char kUnsortedFolderName[] = "unfiled";
647
648   const char query[] = "SELECT root_name, folder_id FROM moz_bookmarks_roots";
649   sql::Statement s(db->GetUniqueStatement(query));
650
651   while (s.Step()) {
652     std::string folder = s.ColumnString(0);
653     int id = s.ColumnInt(1);
654     if (folder == kToolbarFolderName)
655       *toolbar_folder_id = id;
656     else if (folder == kMenuFolderName)
657       *menu_folder_id = id;
658     else if (folder == kUnsortedFolderName)
659       *unsorted_folder_id = id;
660   }
661 }
662
663 void FirefoxImporter::LoadLivemarkIDs(sql::Connection* db,
664                                        std::set<int>* livemark) {
665   static const char kFeedAnnotation[] = "livemark/feedURI";
666   livemark->clear();
667
668   const char query[] =
669       "SELECT b.item_id "
670       "FROM moz_anno_attributes a "
671       "JOIN moz_items_annos b ON a.id = b.anno_attribute_id "
672       "WHERE a.name = ? ";
673   sql::Statement s(db->GetUniqueStatement(query));
674   s.BindString(0, kFeedAnnotation);
675
676   while (s.Step() && !cancelled())
677     livemark->insert(s.ColumnInt(0));
678 }
679
680 void FirefoxImporter::GetTopBookmarkFolder(sql::Connection* db,
681                                             int folder_id,
682                                             BookmarkList* list) {
683   const char query[] =
684       "SELECT b.title "
685       "FROM moz_bookmarks b "
686       "WHERE b.type = 2 AND b.id = ? "
687       "ORDER BY b.position";
688   sql::Statement s(db->GetUniqueStatement(query));
689   s.BindInt(0, folder_id);
690
691   if (s.Step()) {
692     BookmarkItem* item = new BookmarkItem;
693     item->parent = -1;  // The top level folder has no parent.
694     item->id = folder_id;
695     item->title = s.ColumnString16(0);
696     item->type = TYPE_FOLDER;
697     item->favicon = 0;
698     item->empty_folder = true;
699     list->push_back(item);
700   }
701 }
702
703 void FirefoxImporter::GetWholeBookmarkFolder(sql::Connection* db,
704                                               BookmarkList* list,
705                                               size_t position,
706                                               bool* empty_folder) {
707   if (position >= list->size()) {
708     NOTREACHED();
709     return;
710   }
711
712   const char query[] =
713       "SELECT b.id, h.url, COALESCE(b.title, h.title), "
714       "b.type, k.keyword, b.dateAdded, h.favicon_id "
715       "FROM moz_bookmarks b "
716       "LEFT JOIN moz_places h ON b.fk = h.id "
717       "LEFT JOIN moz_keywords k ON k.id = b.keyword_id "
718       "WHERE b.type IN (1,2) AND b.parent = ? "
719       "ORDER BY b.position";
720   sql::Statement s(db->GetUniqueStatement(query));
721   s.BindInt(0, (*list)[position]->id);
722
723   BookmarkList temp_list;
724   while (s.Step()) {
725     BookmarkItem* item = new BookmarkItem;
726     item->parent = static_cast<int>(position);
727     item->id = s.ColumnInt(0);
728     item->url = GURL(s.ColumnString(1));
729     item->title = s.ColumnString16(2);
730     item->type = static_cast<BookmarkItemType>(s.ColumnInt(3));
731     item->keyword = s.ColumnString(4);
732     item->date_added = base::Time::FromTimeT(s.ColumnInt64(5)/1000000);
733     item->favicon = s.ColumnInt64(6);
734     item->empty_folder = true;
735
736     temp_list.push_back(item);
737     if (empty_folder != NULL)
738       *empty_folder = false;
739   }
740
741   // Appends all items to the list.
742   for (BookmarkList::iterator i = temp_list.begin();
743        i != temp_list.end(); ++i) {
744     list->push_back(*i);
745     // Recursive add bookmarks in sub-folders.
746     if ((*i)->type == TYPE_FOLDER)
747       GetWholeBookmarkFolder(db, list, list->size() - 1, &(*i)->empty_folder);
748   }
749 }
750
751 void FirefoxImporter::LoadFavicons(
752     sql::Connection* db,
753     const FaviconMap& favicon_map,
754     std::vector<ImportedFaviconUsage>* favicons) {
755   const char query[] = "SELECT url, data FROM moz_favicons WHERE id=?";
756   sql::Statement s(db->GetUniqueStatement(query));
757
758   if (!s.is_valid())
759     return;
760
761   for (FaviconMap::const_iterator i = favicon_map.begin();
762        i != favicon_map.end(); ++i) {
763     s.BindInt64(0, i->first);
764     if (s.Step()) {
765       ImportedFaviconUsage usage;
766
767       usage.favicon_url = GURL(s.ColumnString(0));
768       if (!usage.favicon_url.is_valid())
769         continue;  // Don't bother importing favicons with invalid URLs.
770
771       std::vector<unsigned char> data;
772       s.ColumnBlobAsVector(1, &data);
773       if (data.empty())
774         continue;  // Data definitely invalid.
775
776       if (!importer::ReencodeFavicon(&data[0], data.size(), &usage.png_data))
777         continue;  // Unable to decode.
778
779       usage.urls = i->second;
780       favicons->push_back(usage);
781     }
782     s.Reset(true);
783   }
784 }