BrowserProvider2.java revision d8c7452a7d8975a2d60414c5a33842b4a743e631
1/*
2 * Copyright (C) 2010 he Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License
15 */
16
17package com.android.browser.provider;
18
19import android.accounts.Account;
20import android.app.SearchManager;
21import android.content.ContentResolver;
22import android.content.ContentUris;
23import android.content.ContentValues;
24import android.content.Context;
25import android.content.Intent;
26import android.content.UriMatcher;
27import android.content.res.Resources;
28import android.content.res.TypedArray;
29import android.database.AbstractCursor;
30import android.database.ContentObserver;
31import android.database.Cursor;
32import android.database.DatabaseUtils;
33import android.database.MatrixCursor;
34import android.database.sqlite.SQLiteDatabase;
35import android.database.sqlite.SQLiteOpenHelper;
36import android.database.sqlite.SQLiteQueryBuilder;
37import android.net.Uri;
38import android.provider.BaseColumns;
39import android.provider.Browser;
40import android.provider.Browser.BookmarkColumns;
41import android.provider.BrowserContract;
42import android.provider.BrowserContract.Accounts;
43import android.provider.BrowserContract.Bookmarks;
44import android.provider.BrowserContract.ChromeSyncColumns;
45import android.provider.BrowserContract.Combined;
46import android.provider.BrowserContract.History;
47import android.provider.BrowserContract.Images;
48import android.provider.BrowserContract.Searches;
49import android.provider.BrowserContract.Settings;
50import android.provider.BrowserContract.SyncState;
51import android.provider.ContactsContract.RawContacts;
52import android.provider.SyncStateContract;
53import android.text.TextUtils;
54
55import com.android.browser.R;
56import com.android.browser.UrlUtils;
57import com.android.browser.widget.BookmarkThumbnailWidgetProvider;
58import com.android.common.content.SyncStateContentProviderHelper;
59import com.google.common.annotations.VisibleForTesting;
60
61import java.io.ByteArrayOutputStream;
62import java.io.File;
63import java.io.IOException;
64import java.io.InputStream;
65import java.util.Arrays;
66import java.util.HashMap;
67
68public class BrowserProvider2 extends SQLiteContentProvider {
69
70    public static interface Snapshots {
71
72        public static final Uri CONTENT_URI = Uri.withAppendedPath(
73                BrowserContract.AUTHORITY_URI, "snapshots");
74        public static final String _ID = "_id";
75        public static final String VIEWSTATE = "view_state";
76        public static final String BACKGROUND = "background";
77        public static final String TITLE = History.TITLE;
78        public static final String URL = History.URL;
79        public static final String FAVICON = History.FAVICON;
80    }
81
82    public static final String LEGACY_AUTHORITY = "browser";
83    static final Uri LEGACY_AUTHORITY_URI = new Uri.Builder()
84            .authority(LEGACY_AUTHORITY).scheme("content").build();
85
86    static final String TABLE_BOOKMARKS = "bookmarks";
87    static final String TABLE_HISTORY = "history";
88    static final String TABLE_IMAGES = "images";
89    static final String TABLE_SEARCHES = "searches";
90    static final String TABLE_SYNC_STATE = "syncstate";
91    static final String TABLE_SETTINGS = "settings";
92    static final String TABLE_SNAPSHOTS = "snapshots";
93
94    static final String TABLE_BOOKMARKS_JOIN_IMAGES = "bookmarks LEFT OUTER JOIN images " +
95            "ON bookmarks.url = images." + Images.URL;
96    static final String TABLE_HISTORY_JOIN_IMAGES = "history LEFT OUTER JOIN images " +
97            "ON history.url = images." + Images.URL;
98
99    static final String VIEW_ACCOUNTS = "v_accounts";
100    static final String VIEW_SNAPSHOTS_COMBINED = "v_snapshots_combined";
101
102    static final String FORMAT_COMBINED_JOIN_SUBQUERY_JOIN_IMAGES =
103            "history LEFT OUTER JOIN (%s) bookmarks " +
104            "ON history.url = bookmarks.url LEFT OUTER JOIN images " +
105            "ON history.url = images.url_key";
106
107    static final String DEFAULT_SORT_HISTORY = History.DATE_LAST_VISITED + " DESC";
108
109    private static final String[] SUGGEST_PROJECTION = new String[] {
110            Bookmarks._ID,
111            Bookmarks.URL,
112            Bookmarks.TITLE};
113
114    private static final String SUGGEST_SELECTION =
115            "url LIKE ? OR url LIKE ? OR url LIKE ? OR url LIKE ?"
116            + " OR title LIKE ?";
117
118    private static final String IMAGE_PRUNE =
119            "url_key NOT IN (SELECT url FROM bookmarks " +
120            "WHERE url IS NOT NULL AND deleted == 0) AND url_key NOT IN " +
121            "(SELECT url FROM history WHERE url IS NOT NULL)";
122
123    static final int BOOKMARKS = 1000;
124    static final int BOOKMARKS_ID = 1001;
125    static final int BOOKMARKS_FOLDER = 1002;
126    static final int BOOKMARKS_FOLDER_ID = 1003;
127    static final int BOOKMARKS_SUGGESTIONS = 1004;
128    static final int BOOKMARKS_DEFAULT_FOLDER_ID = 1005;
129
130    static final int HISTORY = 2000;
131    static final int HISTORY_ID = 2001;
132
133    static final int SEARCHES = 3000;
134    static final int SEARCHES_ID = 3001;
135
136    static final int SYNCSTATE = 4000;
137    static final int SYNCSTATE_ID = 4001;
138
139    static final int IMAGES = 5000;
140
141    static final int COMBINED = 6000;
142    static final int COMBINED_ID = 6001;
143
144    static final int ACCOUNTS = 7000;
145
146    static final int SETTINGS = 8000;
147
148    static final int LEGACY = 9000;
149    static final int LEGACY_ID = 9001;
150
151    static final int SNAPSHOTS = 10000;
152    static final int SNAPSHOTS_ID = 10001;
153
154    public static final long FIXED_ID_ROOT = 1;
155
156    // Default sort order for unsync'd bookmarks
157    static final String DEFAULT_BOOKMARKS_SORT_ORDER =
158            Bookmarks.IS_FOLDER + " DESC, position ASC, _id ASC";
159
160    // Default sort order for sync'd bookmarks
161    static final String DEFAULT_BOOKMARKS_SORT_ORDER_SYNC = "position ASC, _id ASC";
162
163    static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
164
165    static final HashMap<String, String> ACCOUNTS_PROJECTION_MAP = new HashMap<String, String>();
166    static final HashMap<String, String> BOOKMARKS_PROJECTION_MAP = new HashMap<String, String>();
167    static final HashMap<String, String> OTHER_BOOKMARKS_PROJECTION_MAP =
168            new HashMap<String, String>();
169    static final HashMap<String, String> HISTORY_PROJECTION_MAP = new HashMap<String, String>();
170    static final HashMap<String, String> SYNC_STATE_PROJECTION_MAP = new HashMap<String, String>();
171    static final HashMap<String, String> IMAGES_PROJECTION_MAP = new HashMap<String, String>();
172    static final HashMap<String, String> COMBINED_HISTORY_PROJECTION_MAP = new HashMap<String, String>();
173    static final HashMap<String, String> COMBINED_BOOKMARK_PROJECTION_MAP = new HashMap<String, String>();
174    static final HashMap<String, String> SEARCHES_PROJECTION_MAP = new HashMap<String, String>();
175    static final HashMap<String, String> SETTINGS_PROJECTION_MAP = new HashMap<String, String>();
176
177    static {
178        final UriMatcher matcher = URI_MATCHER;
179        final String authority = BrowserContract.AUTHORITY;
180        matcher.addURI(authority, "accounts", ACCOUNTS);
181        matcher.addURI(authority, "bookmarks", BOOKMARKS);
182        matcher.addURI(authority, "bookmarks/#", BOOKMARKS_ID);
183        matcher.addURI(authority, "bookmarks/folder", BOOKMARKS_FOLDER);
184        matcher.addURI(authority, "bookmarks/folder/#", BOOKMARKS_FOLDER_ID);
185        matcher.addURI(authority, "bookmarks/folder/id", BOOKMARKS_DEFAULT_FOLDER_ID);
186        matcher.addURI(authority,
187                SearchManager.SUGGEST_URI_PATH_QUERY,
188                BOOKMARKS_SUGGESTIONS);
189        matcher.addURI(authority,
190                "bookmarks/" + SearchManager.SUGGEST_URI_PATH_QUERY,
191                BOOKMARKS_SUGGESTIONS);
192        matcher.addURI(authority, "history", HISTORY);
193        matcher.addURI(authority, "history/#", HISTORY_ID);
194        matcher.addURI(authority, "searches", SEARCHES);
195        matcher.addURI(authority, "searches/#", SEARCHES_ID);
196        matcher.addURI(authority, "syncstate", SYNCSTATE);
197        matcher.addURI(authority, "syncstate/#", SYNCSTATE_ID);
198        matcher.addURI(authority, "images", IMAGES);
199        matcher.addURI(authority, "combined", COMBINED);
200        matcher.addURI(authority, "combined/#", COMBINED_ID);
201        matcher.addURI(authority, "settings", SETTINGS);
202
203        // Legacy
204        matcher.addURI(LEGACY_AUTHORITY, "searches", SEARCHES);
205        matcher.addURI(LEGACY_AUTHORITY, "searches/#", SEARCHES_ID);
206        matcher.addURI(LEGACY_AUTHORITY, "bookmarks", LEGACY);
207        matcher.addURI(LEGACY_AUTHORITY, "bookmarks/#", LEGACY_ID);
208        matcher.addURI(LEGACY_AUTHORITY,
209                SearchManager.SUGGEST_URI_PATH_QUERY,
210                BOOKMARKS_SUGGESTIONS);
211        matcher.addURI(LEGACY_AUTHORITY,
212                "bookmarks/" + SearchManager.SUGGEST_URI_PATH_QUERY,
213                BOOKMARKS_SUGGESTIONS);
214
215        matcher.addURI(authority, "snapshots", SNAPSHOTS);
216        matcher.addURI(authority, "snapshots/#", SNAPSHOTS_ID);
217
218        // Projection maps
219        HashMap<String, String> map;
220
221        // Accounts
222        map = ACCOUNTS_PROJECTION_MAP;
223        map.put(Accounts.ACCOUNT_TYPE, Accounts.ACCOUNT_TYPE);
224        map.put(Accounts.ACCOUNT_NAME, Accounts.ACCOUNT_NAME);
225        map.put(Accounts.ROOT_ID, Accounts.ROOT_ID);
226
227        // Bookmarks
228        map = BOOKMARKS_PROJECTION_MAP;
229        map.put(Bookmarks._ID, qualifyColumn(TABLE_BOOKMARKS, Bookmarks._ID));
230        map.put(Bookmarks.TITLE, Bookmarks.TITLE);
231        map.put(Bookmarks.URL, Bookmarks.URL);
232        map.put(Bookmarks.FAVICON, Bookmarks.FAVICON);
233        map.put(Bookmarks.THUMBNAIL, Bookmarks.THUMBNAIL);
234        map.put(Bookmarks.TOUCH_ICON, Bookmarks.TOUCH_ICON);
235        map.put(Bookmarks.IS_FOLDER, Bookmarks.IS_FOLDER);
236        map.put(Bookmarks.PARENT, Bookmarks.PARENT);
237        map.put(Bookmarks.POSITION, Bookmarks.POSITION);
238        map.put(Bookmarks.INSERT_AFTER, Bookmarks.INSERT_AFTER);
239        map.put(Bookmarks.IS_DELETED, Bookmarks.IS_DELETED);
240        map.put(Bookmarks.ACCOUNT_NAME, Bookmarks.ACCOUNT_NAME);
241        map.put(Bookmarks.ACCOUNT_TYPE, Bookmarks.ACCOUNT_TYPE);
242        map.put(Bookmarks.SOURCE_ID, Bookmarks.SOURCE_ID);
243        map.put(Bookmarks.VERSION, Bookmarks.VERSION);
244        map.put(Bookmarks.DATE_CREATED, Bookmarks.DATE_CREATED);
245        map.put(Bookmarks.DATE_MODIFIED, Bookmarks.DATE_MODIFIED);
246        map.put(Bookmarks.DIRTY, Bookmarks.DIRTY);
247        map.put(Bookmarks.SYNC1, Bookmarks.SYNC1);
248        map.put(Bookmarks.SYNC2, Bookmarks.SYNC2);
249        map.put(Bookmarks.SYNC3, Bookmarks.SYNC3);
250        map.put(Bookmarks.SYNC4, Bookmarks.SYNC4);
251        map.put(Bookmarks.SYNC5, Bookmarks.SYNC5);
252        map.put(Bookmarks.PARENT_SOURCE_ID, "(SELECT " + Bookmarks.SOURCE_ID +
253                " FROM " + TABLE_BOOKMARKS + " A WHERE " +
254                "A." + Bookmarks._ID + "=" + TABLE_BOOKMARKS + "." + Bookmarks.PARENT +
255                ") AS " + Bookmarks.PARENT_SOURCE_ID);
256        map.put(Bookmarks.INSERT_AFTER_SOURCE_ID, "(SELECT " + Bookmarks.SOURCE_ID +
257                " FROM " + TABLE_BOOKMARKS + " A WHERE " +
258                "A." + Bookmarks._ID + "=" + TABLE_BOOKMARKS + "." + Bookmarks.INSERT_AFTER +
259                ") AS " + Bookmarks.INSERT_AFTER_SOURCE_ID);
260
261        // Other bookmarks
262        OTHER_BOOKMARKS_PROJECTION_MAP.putAll(BOOKMARKS_PROJECTION_MAP);
263        OTHER_BOOKMARKS_PROJECTION_MAP.put(Bookmarks.POSITION,
264                Long.toString(Long.MAX_VALUE) + " AS " + Bookmarks.POSITION);
265
266        // History
267        map = HISTORY_PROJECTION_MAP;
268        map.put(History._ID, qualifyColumn(TABLE_HISTORY, History._ID));
269        map.put(History.TITLE, History.TITLE);
270        map.put(History.URL, History.URL);
271        map.put(History.FAVICON, History.FAVICON);
272        map.put(History.THUMBNAIL, History.THUMBNAIL);
273        map.put(History.TOUCH_ICON, History.TOUCH_ICON);
274        map.put(History.DATE_CREATED, History.DATE_CREATED);
275        map.put(History.DATE_LAST_VISITED, History.DATE_LAST_VISITED);
276        map.put(History.VISITS, History.VISITS);
277        map.put(History.USER_ENTERED, History.USER_ENTERED);
278
279        // Sync state
280        map = SYNC_STATE_PROJECTION_MAP;
281        map.put(SyncState._ID, SyncState._ID);
282        map.put(SyncState.ACCOUNT_NAME, SyncState.ACCOUNT_NAME);
283        map.put(SyncState.ACCOUNT_TYPE, SyncState.ACCOUNT_TYPE);
284        map.put(SyncState.DATA, SyncState.DATA);
285
286        // Images
287        map = IMAGES_PROJECTION_MAP;
288        map.put(Images.URL, Images.URL);
289        map.put(Images.FAVICON, Images.FAVICON);
290        map.put(Images.THUMBNAIL, Images.THUMBNAIL);
291        map.put(Images.TOUCH_ICON, Images.TOUCH_ICON);
292
293        // Combined history half
294        map = COMBINED_HISTORY_PROJECTION_MAP;
295        map.put(Combined._ID, bookmarkOrHistoryColumn(Combined._ID));
296        map.put(Combined.TITLE, bookmarkOrHistoryColumn(Combined.TITLE));
297        map.put(Combined.URL, qualifyColumn(TABLE_HISTORY, Combined.URL));
298        map.put(Combined.DATE_CREATED, qualifyColumn(TABLE_HISTORY, Combined.DATE_CREATED));
299        map.put(Combined.DATE_LAST_VISITED, Combined.DATE_LAST_VISITED);
300        map.put(Combined.IS_BOOKMARK, "CASE WHEN " +
301                TABLE_BOOKMARKS + "." + Bookmarks._ID +
302                " IS NOT NULL THEN 1 ELSE 0 END AS " + Combined.IS_BOOKMARK);
303        map.put(Combined.VISITS, Combined.VISITS);
304        map.put(Combined.FAVICON, Combined.FAVICON);
305        map.put(Combined.THUMBNAIL, Combined.THUMBNAIL);
306        map.put(Combined.TOUCH_ICON, Combined.TOUCH_ICON);
307        map.put(Combined.USER_ENTERED, "NULL AS " + Combined.USER_ENTERED);
308
309        // Combined bookmark half
310        map = COMBINED_BOOKMARK_PROJECTION_MAP;
311        map.put(Combined._ID, Combined._ID);
312        map.put(Combined.TITLE, Combined.TITLE);
313        map.put(Combined.URL, Combined.URL);
314        map.put(Combined.DATE_CREATED, Combined.DATE_CREATED);
315        map.put(Combined.DATE_LAST_VISITED, "NULL AS " + Combined.DATE_LAST_VISITED);
316        map.put(Combined.IS_BOOKMARK, "1 AS " + Combined.IS_BOOKMARK);
317        map.put(Combined.VISITS, "0 AS " + Combined.VISITS);
318        map.put(Combined.FAVICON, Combined.FAVICON);
319        map.put(Combined.THUMBNAIL, Combined.THUMBNAIL);
320        map.put(Combined.TOUCH_ICON, Combined.TOUCH_ICON);
321        map.put(Combined.USER_ENTERED, "NULL AS " + Combined.USER_ENTERED);
322
323        // Searches
324        map = SEARCHES_PROJECTION_MAP;
325        map.put(Searches._ID, Searches._ID);
326        map.put(Searches.SEARCH, Searches.SEARCH);
327        map.put(Searches.DATE, Searches.DATE);
328
329        // Settings
330        map = SETTINGS_PROJECTION_MAP;
331        map.put(Settings.KEY, Settings.KEY);
332        map.put(Settings.VALUE, Settings.VALUE);
333    }
334
335    static final String bookmarkOrHistoryColumn(String column) {
336        return "CASE WHEN bookmarks." + column + " IS NOT NULL THEN " +
337                "bookmarks." + column + " ELSE history." + column + " END AS " + column;
338    }
339
340    static final String qualifyColumn(String table, String column) {
341        return table + "." + column + " AS " + column;
342    }
343
344    DatabaseHelper mOpenHelper;
345    SyncStateContentProviderHelper mSyncHelper = new SyncStateContentProviderHelper();
346    // This is so provider tests can intercept widget updating
347    ContentObserver mWidgetObserver = null;
348
349    final class DatabaseHelper extends SQLiteOpenHelper {
350        static final String DATABASE_NAME = "browser2.db";
351        static final int DATABASE_VERSION = 29;
352        public DatabaseHelper(Context context) {
353            super(context, DATABASE_NAME, null, DATABASE_VERSION);
354        }
355
356        @Override
357        public void onCreate(SQLiteDatabase db) {
358            db.execSQL("CREATE TABLE " + TABLE_BOOKMARKS + "(" +
359                    Bookmarks._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
360                    Bookmarks.TITLE + " TEXT," +
361                    Bookmarks.URL + " TEXT," +
362                    Bookmarks.IS_FOLDER + " INTEGER NOT NULL DEFAULT 0," +
363                    Bookmarks.PARENT + " INTEGER," +
364                    Bookmarks.POSITION + " INTEGER NOT NULL," +
365                    Bookmarks.INSERT_AFTER + " INTEGER," +
366                    Bookmarks.IS_DELETED + " INTEGER NOT NULL DEFAULT 0," +
367                    Bookmarks.ACCOUNT_NAME + " TEXT," +
368                    Bookmarks.ACCOUNT_TYPE + " TEXT," +
369                    Bookmarks.SOURCE_ID + " TEXT," +
370                    Bookmarks.VERSION + " INTEGER NOT NULL DEFAULT 1," +
371                    Bookmarks.DATE_CREATED + " INTEGER," +
372                    Bookmarks.DATE_MODIFIED + " INTEGER," +
373                    Bookmarks.DIRTY + " INTEGER NOT NULL DEFAULT 0," +
374                    Bookmarks.SYNC1 + " TEXT," +
375                    Bookmarks.SYNC2 + " TEXT," +
376                    Bookmarks.SYNC3 + " TEXT," +
377                    Bookmarks.SYNC4 + " TEXT," +
378                    Bookmarks.SYNC5 + " TEXT" +
379                    ");");
380
381            // TODO indices
382
383            db.execSQL("CREATE TABLE " + TABLE_HISTORY + "(" +
384                    History._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
385                    History.TITLE + " TEXT," +
386                    History.URL + " TEXT NOT NULL," +
387                    History.DATE_CREATED + " INTEGER," +
388                    History.DATE_LAST_VISITED + " INTEGER," +
389                    History.VISITS + " INTEGER NOT NULL DEFAULT 0," +
390                    History.USER_ENTERED + " INTEGER" +
391                    ");");
392
393            db.execSQL("CREATE TABLE " + TABLE_IMAGES + " (" +
394                    Images.URL + " TEXT UNIQUE NOT NULL," +
395                    Images.FAVICON + " BLOB," +
396                    Images.THUMBNAIL + " BLOB," +
397                    Images.TOUCH_ICON + " BLOB" +
398                    ");");
399            db.execSQL("CREATE INDEX imagesUrlIndex ON " + TABLE_IMAGES +
400                    "(" + Images.URL + ")");
401
402            db.execSQL("CREATE TABLE " + TABLE_SEARCHES + " (" +
403                    Searches._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
404                    Searches.SEARCH + " TEXT," +
405                    Searches.DATE + " LONG" +
406                    ");");
407
408            db.execSQL("CREATE TABLE " + TABLE_SETTINGS + " (" +
409                    Settings.KEY + " TEXT PRIMARY KEY," +
410                    Settings.VALUE + " TEXT NOT NULL" +
411                    ");");
412
413            createAccountsView(db);
414
415            mSyncHelper.createDatabase(db);
416
417            if (!importFromBrowserProvider(db)) {
418                createDefaultBookmarks(db);
419            }
420
421            enableSync(db);
422
423            createSnapshots(db);
424        }
425
426        void enableSync(SQLiteDatabase db) {
427            ContentValues values = new ContentValues();
428            values.put(Settings.KEY, Settings.KEY_SYNC_ENABLED);
429            values.put(Settings.VALUE, 1);
430            insertSettingsInTransaction(db, values);
431        }
432
433        boolean importFromBrowserProvider(SQLiteDatabase db) {
434            Context context = getContext();
435            File oldDbFile = context.getDatabasePath(BrowserProvider.sDatabaseName);
436            if (oldDbFile.exists()) {
437                BrowserProvider.DatabaseHelper helper =
438                        new BrowserProvider.DatabaseHelper(context);
439                SQLiteDatabase oldDb = helper.getWritableDatabase();
440                Cursor c = null;
441                try {
442                    String table = BrowserProvider.TABLE_NAMES[BrowserProvider.URI_MATCH_BOOKMARKS];
443                    // Import bookmarks
444                    c = oldDb.query(table,
445                            new String[] {
446                            BookmarkColumns.URL, // 0
447                            BookmarkColumns.TITLE, // 1
448                            BookmarkColumns.FAVICON, // 2
449                            BookmarkColumns.TOUCH_ICON, // 3
450                            }, BookmarkColumns.BOOKMARK + "!=0", null,
451                            null, null, null);
452                    if (c != null) {
453                        while (c.moveToNext()) {
454                            ContentValues values = new ContentValues();
455                            values.put(Bookmarks.URL, c.getString(0));
456                            values.put(Bookmarks.TITLE, c.getString(1));
457                            values.put(Bookmarks.POSITION, 0);
458                            values.put(Bookmarks.PARENT, FIXED_ID_ROOT);
459                            ContentValues imageValues = new ContentValues();
460                            imageValues.put(Images.URL, c.getString(0));
461                            imageValues.put(Images.FAVICON, c.getBlob(2));
462                            imageValues.put(Images.TOUCH_ICON, c.getBlob(3));
463                            db.insertOrThrow(TABLE_IMAGES, Images.THUMBNAIL, imageValues);
464                            db.insertOrThrow(TABLE_BOOKMARKS, Bookmarks.DIRTY, values);
465                        }
466                        c.close();
467                    }
468                    // Import history
469                    c = oldDb.query(table,
470                            new String[] {
471                            BookmarkColumns.URL, // 0
472                            BookmarkColumns.TITLE, // 1
473                            BookmarkColumns.VISITS, // 2
474                            BookmarkColumns.DATE, // 3
475                            BookmarkColumns.CREATED, // 4
476                            }, null, null, null, null, null);
477                    if (c != null) {
478                        while (c.moveToNext()) {
479                            ContentValues values = new ContentValues();
480                            values.put(History.URL, c.getString(0));
481                            values.put(History.TITLE, c.getString(1));
482                            values.put(History.VISITS, c.getInt(2));
483                            values.put(History.DATE_LAST_VISITED, c.getLong(3));
484                            values.put(History.DATE_CREATED, c.getLong(4));
485                            db.insertOrThrow(TABLE_HISTORY, History.FAVICON, values);
486                        }
487                        c.close();
488                    }
489                    // Wipe the old DB, in case the delete fails.
490                    oldDb.delete(table, null, null);
491                } finally {
492                    if (c != null) c.close();
493                    oldDb.close();
494                    helper.close();
495                }
496                if (!oldDbFile.delete()) {
497                    oldDbFile.deleteOnExit();
498                }
499                return true;
500            }
501            return false;
502        }
503
504        void createAccountsView(SQLiteDatabase db) {
505            db.execSQL("CREATE VIEW IF NOT EXISTS v_accounts AS "
506                    + "SELECT NULL AS " + Accounts.ACCOUNT_NAME
507                    + ", NULL AS " + Accounts.ACCOUNT_TYPE
508                    + ", " + FIXED_ID_ROOT + " AS " + Accounts.ROOT_ID
509                    + " UNION ALL SELECT " + Accounts.ACCOUNT_NAME
510                    + ", " + Accounts.ACCOUNT_TYPE + ", "
511                    + Bookmarks._ID + " AS " + Accounts.ROOT_ID
512                    + " FROM " + TABLE_BOOKMARKS + " WHERE "
513                    + ChromeSyncColumns.SERVER_UNIQUE + " = \""
514                    + ChromeSyncColumns.FOLDER_NAME_BOOKMARKS_BAR + "\" AND "
515                    + Bookmarks.IS_DELETED + " = 0");
516        }
517
518        @Override
519        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
520            if (oldVersion < 29) {
521                createSnapshots(db);
522            }
523            if (oldVersion < 28) {
524                enableSync(db);
525            }
526            if (oldVersion < 27) {
527                createAccountsView(db);
528            }
529            if (oldVersion < 26) {
530                db.execSQL("DROP VIEW IF EXISTS combined");
531            }
532            if (oldVersion < 25) {
533                db.execSQL("DROP TABLE IF EXISTS " + TABLE_BOOKMARKS);
534                db.execSQL("DROP TABLE IF EXISTS " + TABLE_HISTORY);
535                db.execSQL("DROP TABLE IF EXISTS " + TABLE_SEARCHES);
536                db.execSQL("DROP TABLE IF EXISTS " + TABLE_IMAGES);
537                db.execSQL("DROP TABLE IF EXISTS " + TABLE_SETTINGS);
538                mSyncHelper.onAccountsChanged(db, new Account[] {}); // remove all sync info
539                onCreate(db);
540            }
541        }
542
543        void createSnapshots(SQLiteDatabase db) {
544            db.execSQL("DROP TABLE IF EXISTS " + TABLE_SNAPSHOTS);
545            db.execSQL("CREATE TABLE " + TABLE_SNAPSHOTS + " (" +
546                    Snapshots._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
547                    Snapshots.URL + " TEXT NOT NULL," +
548                    Snapshots.TITLE + " TEXT," +
549                    Snapshots.BACKGROUND + " INTEGER," +
550                    Snapshots.VIEWSTATE + " BLOB NOT NULL" +
551                    ");");
552            db.execSQL("CREATE VIEW IF NOT EXISTS " + VIEW_SNAPSHOTS_COMBINED +
553                    " AS SELECT * FROM " + TABLE_SNAPSHOTS +
554                    " LEFT OUTER JOIN " + TABLE_IMAGES +
555                    " ON " + TABLE_SNAPSHOTS + "." + Snapshots.URL +
556                    " = images.url_key");
557        }
558
559        @Override
560        public void onOpen(SQLiteDatabase db) {
561            db.enableWriteAheadLogging();
562            mSyncHelper.onDatabaseOpened(db);
563        }
564
565        private void createDefaultBookmarks(SQLiteDatabase db) {
566            ContentValues values = new ContentValues();
567            // TODO figure out how to deal with localization for the defaults
568
569            // Bookmarks folder
570            values.put(Bookmarks._ID, FIXED_ID_ROOT);
571            values.put(ChromeSyncColumns.SERVER_UNIQUE, ChromeSyncColumns.FOLDER_NAME_BOOKMARKS);
572            values.put(Bookmarks.TITLE, "Bookmarks");
573            values.putNull(Bookmarks.PARENT);
574            values.put(Bookmarks.POSITION, 0);
575            values.put(Bookmarks.IS_FOLDER, true);
576            values.put(Bookmarks.DIRTY, true);
577            db.insertOrThrow(TABLE_BOOKMARKS, null, values);
578
579            addDefaultBookmarks(db, FIXED_ID_ROOT);
580        }
581
582        private void addDefaultBookmarks(SQLiteDatabase db, long parentId) {
583            Resources res = getContext().getResources();
584            final CharSequence[] bookmarks = res.getTextArray(
585                    R.array.bookmarks);
586            int size = bookmarks.length;
587            TypedArray preloads = res.obtainTypedArray(R.array.bookmark_preloads);
588            try {
589                String parent = Long.toString(parentId);
590                String now = Long.toString(System.currentTimeMillis());
591                for (int i = 0; i < size; i = i + 2) {
592                    CharSequence bookmarkDestination = replaceSystemPropertyInString(getContext(),
593                            bookmarks[i + 1]);
594                    db.execSQL("INSERT INTO bookmarks (" +
595                            Bookmarks.TITLE + ", " +
596                            Bookmarks.URL + ", " +
597                            Bookmarks.IS_FOLDER + "," +
598                            Bookmarks.PARENT + "," +
599                            Bookmarks.POSITION + "," +
600                            Bookmarks.DATE_CREATED +
601                        ") VALUES (" +
602                            "'" + bookmarks[i] + "', " +
603                            "'" + bookmarkDestination + "', " +
604                            "0," +
605                            parent + "," +
606                            Integer.toString(i) + "," +
607                            now +
608                            ");");
609
610                    int faviconId = preloads.getResourceId(i, 0);
611                    int thumbId = preloads.getResourceId(i + 1, 0);
612                    byte[] thumb = null, favicon = null;
613                    try {
614                        thumb = readRaw(res, thumbId);
615                    } catch (IOException e) {
616                    }
617                    try {
618                        favicon = readRaw(res, faviconId);
619                    } catch (IOException e) {
620                    }
621                    if (thumb != null || favicon != null) {
622                        ContentValues imageValues = new ContentValues();
623                        imageValues.put(Images.URL, bookmarkDestination.toString());
624                        if (favicon != null) {
625                            imageValues.put(Images.FAVICON, favicon);
626                        }
627                        if (thumb != null) {
628                            imageValues.put(Images.THUMBNAIL, thumb);
629                        }
630                        db.insert(TABLE_IMAGES, Images.FAVICON, imageValues);
631                    }
632                }
633            } catch (ArrayIndexOutOfBoundsException e) {
634            }
635        }
636
637        private byte[] readRaw(Resources res, int id) throws IOException {
638            if (id == 0) {
639                return null;
640            }
641            InputStream is = res.openRawResource(id);
642            try {
643                ByteArrayOutputStream bos = new ByteArrayOutputStream();
644                byte[] buf = new byte[4096];
645                int read;
646                while ((read = is.read(buf)) > 0) {
647                    bos.write(buf, 0, read);
648                }
649                bos.flush();
650                return bos.toByteArray();
651            } finally {
652                is.close();
653            }
654        }
655
656        // XXX: This is a major hack to remove our dependency on gsf constants and
657        // its content provider. http://b/issue?id=2425179
658        private String getClientId(ContentResolver cr) {
659            String ret = "android-google";
660            Cursor c = null;
661            try {
662                c = cr.query(Uri.parse("content://com.google.settings/partner"),
663                        new String[] { "value" }, "name='client_id'", null, null);
664                if (c != null && c.moveToNext()) {
665                    ret = c.getString(0);
666                }
667            } catch (RuntimeException ex) {
668                // fall through to return the default
669            } finally {
670                if (c != null) {
671                    c.close();
672                }
673            }
674            return ret;
675        }
676
677        private CharSequence replaceSystemPropertyInString(Context context, CharSequence srcString) {
678            StringBuffer sb = new StringBuffer();
679            int lastCharLoc = 0;
680
681            final String client_id = getClientId(context.getContentResolver());
682
683            for (int i = 0; i < srcString.length(); ++i) {
684                char c = srcString.charAt(i);
685                if (c == '{') {
686                    sb.append(srcString.subSequence(lastCharLoc, i));
687                    lastCharLoc = i;
688              inner:
689                    for (int j = i; j < srcString.length(); ++j) {
690                        char k = srcString.charAt(j);
691                        if (k == '}') {
692                            String propertyKeyValue = srcString.subSequence(i + 1, j).toString();
693                            if (propertyKeyValue.equals("CLIENT_ID")) {
694                                sb.append(client_id);
695                            } else {
696                                sb.append("unknown");
697                            }
698                            lastCharLoc = j + 1;
699                            i = j;
700                            break inner;
701                        }
702                    }
703                }
704            }
705            if (srcString.length() - lastCharLoc > 0) {
706                // Put on the tail, if there is one
707                sb.append(srcString.subSequence(lastCharLoc, srcString.length()));
708            }
709            return sb;
710        }
711    }
712
713    @Override
714    public SQLiteOpenHelper getDatabaseHelper(Context context) {
715        synchronized (this) {
716            if (mOpenHelper == null) {
717                mOpenHelper = new DatabaseHelper(context);
718            }
719            return mOpenHelper;
720        }
721    }
722
723    @Override
724    public boolean isCallerSyncAdapter(Uri uri) {
725        return uri.getBooleanQueryParameter(BrowserContract.CALLER_IS_SYNCADAPTER, false);
726    }
727
728    @VisibleForTesting
729    public void setWidgetObserver(ContentObserver obs) {
730        mWidgetObserver = obs;
731    }
732
733    void refreshWidgets() {
734        if (mWidgetObserver == null) {
735            BookmarkThumbnailWidgetProvider.refreshWidgets(getContext());
736        } else {
737            mWidgetObserver.dispatchChange(false);
738        }
739    }
740
741    @Override
742    public String getType(Uri uri) {
743        final int match = URI_MATCHER.match(uri);
744        switch (match) {
745            case LEGACY:
746            case BOOKMARKS:
747                return Bookmarks.CONTENT_TYPE;
748            case LEGACY_ID:
749            case BOOKMARKS_ID:
750                return Bookmarks.CONTENT_ITEM_TYPE;
751            case HISTORY:
752                return History.CONTENT_TYPE;
753            case HISTORY_ID:
754                return History.CONTENT_ITEM_TYPE;
755            case SEARCHES:
756                return Searches.CONTENT_TYPE;
757            case SEARCHES_ID:
758                return Searches.CONTENT_ITEM_TYPE;
759        }
760        return null;
761    }
762
763    boolean isNullAccount(String account) {
764        if (account == null) return true;
765        account = account.trim();
766        return account.length() == 0 || account.equals("null");
767    }
768
769    Object[] getSelectionWithAccounts(Uri uri, String selection, String[] selectionArgs) {
770        // Look for account info
771        String accountType = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_TYPE);
772        String accountName = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_NAME);
773        boolean hasAccounts = false;
774        if (accountType != null && accountName != null) {
775            if (!isNullAccount(accountType) && !isNullAccount(accountName)) {
776                selection = DatabaseUtils.concatenateWhere(selection,
777                        Bookmarks.ACCOUNT_TYPE + "=? AND " + Bookmarks.ACCOUNT_NAME + "=? ");
778                selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
779                        new String[] { accountType, accountName });
780                hasAccounts = true;
781            } else {
782                selection = DatabaseUtils.concatenateWhere(selection,
783                        Bookmarks.ACCOUNT_NAME + " IS NULL AND " +
784                        Bookmarks.ACCOUNT_TYPE + " IS NULL");
785            }
786        }
787        return new Object[] { selection, selectionArgs, hasAccounts };
788    }
789
790    @Override
791    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
792            String sortOrder) {
793        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
794        final int match = URI_MATCHER.match(uri);
795        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
796        String limit = uri.getQueryParameter(BrowserContract.PARAM_LIMIT);
797        switch (match) {
798            case ACCOUNTS: {
799                qb.setTables(VIEW_ACCOUNTS);
800                qb.setProjectionMap(ACCOUNTS_PROJECTION_MAP);
801                break;
802            }
803
804            case BOOKMARKS_FOLDER_ID:
805            case BOOKMARKS_ID:
806            case BOOKMARKS: {
807                // Only show deleted bookmarks if requested to do so
808                if (!uri.getBooleanQueryParameter(Bookmarks.QUERY_PARAMETER_SHOW_DELETED, false)) {
809                    selection = DatabaseUtils.concatenateWhere(
810                            Bookmarks.IS_DELETED + "=0", selection);
811                }
812
813                if (match == BOOKMARKS_ID) {
814                    // Tack on the ID of the specific bookmark requested
815                    selection = DatabaseUtils.concatenateWhere(selection,
816                            TABLE_BOOKMARKS + "." + Bookmarks._ID + "=?");
817                    selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
818                            new String[] { Long.toString(ContentUris.parseId(uri)) });
819                } else if (match == BOOKMARKS_FOLDER_ID) {
820                    // Tack on the ID of the specific folder requested
821                    selection = DatabaseUtils.concatenateWhere(selection,
822                            TABLE_BOOKMARKS + "." + Bookmarks.PARENT + "=?");
823                    selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
824                            new String[] { Long.toString(ContentUris.parseId(uri)) });
825                }
826
827                Object[] withAccount = getSelectionWithAccounts(uri, selection, selectionArgs);
828                selection = (String) withAccount[0];
829                selectionArgs = (String[]) withAccount[1];
830                boolean hasAccounts = (Boolean) withAccount[2];
831
832                // Set a default sort order if one isn't specified
833                if (TextUtils.isEmpty(sortOrder)) {
834                    if (hasAccounts) {
835                        sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER_SYNC;
836                    } else {
837                        sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER;
838                    }
839                }
840
841                qb.setProjectionMap(BOOKMARKS_PROJECTION_MAP);
842                qb.setTables(TABLE_BOOKMARKS_JOIN_IMAGES);
843                break;
844            }
845
846            case BOOKMARKS_FOLDER: {
847                // Look for an account
848                boolean useAccount = false;
849                String accountType = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_TYPE);
850                String accountName = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_NAME);
851                if (!isNullAccount(accountType) && !isNullAccount(accountName)) {
852                    useAccount = true;
853                }
854
855                qb.setTables(TABLE_BOOKMARKS_JOIN_IMAGES);
856                String[] args;
857                String query;
858                // Set a default sort order if one isn't specified
859                if (TextUtils.isEmpty(sortOrder)) {
860                    if (useAccount) {
861                        sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER_SYNC;
862                    } else {
863                        sortOrder = DEFAULT_BOOKMARKS_SORT_ORDER;
864                    }
865                }
866                if (!useAccount) {
867                    qb.setProjectionMap(BOOKMARKS_PROJECTION_MAP);
868                    String where = Bookmarks.PARENT + "=? AND " + Bookmarks.IS_DELETED + "=0";
869                    where = DatabaseUtils.concatenateWhere(where, selection);
870                    args = new String[] { Long.toString(FIXED_ID_ROOT) };
871                    if (selectionArgs != null) {
872                        args = DatabaseUtils.appendSelectionArgs(args, selectionArgs);
873                    }
874                    query = qb.buildQuery(projection, where, null, null, sortOrder, null);
875                } else {
876                    qb.setProjectionMap(BOOKMARKS_PROJECTION_MAP);
877                    String where = Bookmarks.ACCOUNT_TYPE + "=? AND " +
878                            Bookmarks.ACCOUNT_NAME + "=? " +
879                            "AND parent = " +
880                            "(SELECT _id FROM " + TABLE_BOOKMARKS + " WHERE " +
881                            ChromeSyncColumns.SERVER_UNIQUE + "=" +
882                            "'" + ChromeSyncColumns.FOLDER_NAME_BOOKMARKS_BAR + "' " +
883                            "AND account_type = ? AND account_name = ?) " +
884                            "AND " + Bookmarks.IS_DELETED + "=0";
885                    where = DatabaseUtils.concatenateWhere(where, selection);
886                    String bookmarksBarQuery = qb.buildQuery(projection,
887                            where, null, null, null, null);
888                    args = new String[] {accountType, accountName,
889                            accountType, accountName};
890                    if (selectionArgs != null) {
891                        args = DatabaseUtils.appendSelectionArgs(args, selectionArgs);
892                    }
893
894                    where = Bookmarks.ACCOUNT_TYPE + "=? AND " + Bookmarks.ACCOUNT_NAME + "=?" +
895                            " AND " + ChromeSyncColumns.SERVER_UNIQUE + "=?";
896                    where = DatabaseUtils.concatenateWhere(where, selection);
897                    qb.setProjectionMap(OTHER_BOOKMARKS_PROJECTION_MAP);
898                    String otherBookmarksQuery = qb.buildQuery(projection,
899                            where, null, null, null, null);
900
901                    query = qb.buildUnionQuery(
902                            new String[] { bookmarksBarQuery, otherBookmarksQuery },
903                            sortOrder, limit);
904
905                    args = DatabaseUtils.appendSelectionArgs(args, new String[] {
906                            accountType, accountName, ChromeSyncColumns.FOLDER_NAME_OTHER_BOOKMARKS,
907                            });
908                    if (selectionArgs != null) {
909                        args = DatabaseUtils.appendSelectionArgs(args, selectionArgs);
910                    }
911                }
912
913                Cursor cursor = db.rawQuery(query, args);
914                if (cursor != null) {
915                    cursor.setNotificationUri(getContext().getContentResolver(),
916                            BrowserContract.AUTHORITY_URI);
917                }
918                return cursor;
919            }
920
921            case BOOKMARKS_DEFAULT_FOLDER_ID: {
922                String accountName = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_NAME);
923                String accountType = uri.getQueryParameter(Bookmarks.PARAM_ACCOUNT_TYPE);
924                long id = queryDefaultFolderId(accountName, accountType);
925                MatrixCursor c = new MatrixCursor(new String[] {Bookmarks._ID});
926                c.newRow().add(id);
927                return c;
928            }
929
930            case BOOKMARKS_SUGGESTIONS: {
931                return doSuggestQuery(selection, selectionArgs, limit);
932            }
933
934            case HISTORY_ID: {
935                selection = DatabaseUtils.concatenateWhere(selection, TABLE_HISTORY + "._id=?");
936                selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
937                        new String[] { Long.toString(ContentUris.parseId(uri)) });
938                // fall through
939            }
940            case HISTORY: {
941                filterSearchClient(selectionArgs);
942                if (sortOrder == null) {
943                    sortOrder = DEFAULT_SORT_HISTORY;
944                }
945                qb.setProjectionMap(HISTORY_PROJECTION_MAP);
946                qb.setTables(TABLE_HISTORY_JOIN_IMAGES);
947                break;
948            }
949
950            case SEARCHES_ID: {
951                selection = DatabaseUtils.concatenateWhere(selection, TABLE_SEARCHES + "._id=?");
952                selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
953                        new String[] { Long.toString(ContentUris.parseId(uri)) });
954                // fall through
955            }
956            case SEARCHES: {
957                qb.setTables(TABLE_SEARCHES);
958                qb.setProjectionMap(SEARCHES_PROJECTION_MAP);
959                break;
960            }
961
962            case SYNCSTATE: {
963                return mSyncHelper.query(db, projection, selection, selectionArgs, sortOrder);
964            }
965
966            case SYNCSTATE_ID: {
967                selection = appendAccountToSelection(uri, selection);
968                String selectionWithId =
969                        (SyncStateContract.Columns._ID + "=" + ContentUris.parseId(uri) + " ")
970                        + (selection == null ? "" : " AND (" + selection + ")");
971                return mSyncHelper.query(db, projection, selectionWithId, selectionArgs, sortOrder);
972            }
973
974            case IMAGES: {
975                qb.setTables(TABLE_IMAGES);
976                qb.setProjectionMap(IMAGES_PROJECTION_MAP);
977                break;
978            }
979
980            case LEGACY_ID:
981            case COMBINED_ID: {
982                selection = DatabaseUtils.concatenateWhere(
983                        selection, Combined._ID + " = CAST(? AS INTEGER)");
984                selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
985                        new String[] { Long.toString(ContentUris.parseId(uri)) });
986                // fall through
987            }
988            case LEGACY:
989            case COMBINED: {
990                if ((match == LEGACY || match == LEGACY_ID)
991                        && projection == null) {
992                    projection = Browser.HISTORY_PROJECTION;
993                }
994                String[] args = createCombinedQuery(uri, projection, qb);
995                if (selectionArgs == null) {
996                    selectionArgs = args;
997                } else {
998                    selectionArgs = DatabaseUtils.appendSelectionArgs(args, selectionArgs);
999                }
1000                break;
1001            }
1002
1003            case SETTINGS: {
1004                qb.setTables(TABLE_SETTINGS);
1005                qb.setProjectionMap(SETTINGS_PROJECTION_MAP);
1006                break;
1007            }
1008
1009            case SNAPSHOTS_ID: {
1010                selection = DatabaseUtils.concatenateWhere(selection, "_id=?");
1011                selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
1012                        new String[] { Long.toString(ContentUris.parseId(uri)) });
1013                // fall through
1014            }
1015            case SNAPSHOTS: {
1016                qb.setTables(VIEW_SNAPSHOTS_COMBINED);
1017                break;
1018            }
1019
1020            default: {
1021                throw new UnsupportedOperationException("Unknown URL " + uri.toString());
1022            }
1023        }
1024
1025        Cursor cursor = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder,
1026                limit);
1027        cursor.setNotificationUri(getContext().getContentResolver(), BrowserContract.AUTHORITY_URI);
1028        return cursor;
1029    }
1030
1031    private Cursor doSuggestQuery(String selection, String[] selectionArgs, String limit) {
1032        if (selectionArgs[0] == null) {
1033            return null;
1034        } else {
1035            String like = selectionArgs[0] + "%";
1036            if (selectionArgs[0].startsWith("http")
1037                    || selectionArgs[0].startsWith("file")) {
1038                selectionArgs[0] = like;
1039            } else {
1040                selectionArgs = new String[5];
1041                selectionArgs[0] = "http://" + like;
1042                selectionArgs[1] = "http://www." + like;
1043                selectionArgs[2] = "https://" + like;
1044                selectionArgs[3] = "https://www." + like;
1045                // To match against titles.
1046                selectionArgs[4] = like;
1047                selection = SUGGEST_SELECTION;
1048            }
1049        }
1050        selection = DatabaseUtils.concatenateWhere(selection,
1051                Bookmarks.IS_DELETED + "=0 AND " + Bookmarks.IS_FOLDER + "=0");
1052
1053        Cursor c = mOpenHelper.getReadableDatabase().query(TABLE_BOOKMARKS,
1054                SUGGEST_PROJECTION, selection, selectionArgs, null, null,
1055                DEFAULT_BOOKMARKS_SORT_ORDER, null);
1056
1057        return new SuggestionsCursor(c);
1058    }
1059
1060    private String[] createCombinedQuery(
1061            Uri uri, String[] projection, SQLiteQueryBuilder qb) {
1062        String[] args = null;
1063        StringBuilder whereBuilder = new StringBuilder(128);
1064        whereBuilder.append(Bookmarks.IS_DELETED);
1065        whereBuilder.append(" = 0");
1066        // Look for account info
1067        Object[] withAccount = getSelectionWithAccounts(uri, null, null);
1068        String selection = (String) withAccount[0];
1069        String[] selectionArgs = (String[]) withAccount[1];
1070        if (selection != null) {
1071            whereBuilder.append(" AND " + selection);
1072            if (selectionArgs != null) {
1073                // We use the selection twice, hence we need to duplicate the args
1074                args = new String[selectionArgs.length * 2];
1075                System.arraycopy(selectionArgs, 0, args, 0, selectionArgs.length);
1076                System.arraycopy(selectionArgs, 0, args, selectionArgs.length,
1077                        selectionArgs.length);
1078            }
1079        }
1080        String where = whereBuilder.toString();
1081        // Build the bookmark subquery for history union subquery
1082        qb.setTables(TABLE_BOOKMARKS);
1083        String subQuery = qb.buildQuery(null, where, null, null, null, null);
1084        // Build the history union subquery
1085        qb.setTables(String.format(FORMAT_COMBINED_JOIN_SUBQUERY_JOIN_IMAGES, subQuery));
1086        qb.setProjectionMap(COMBINED_HISTORY_PROJECTION_MAP);
1087        String historySubQuery = qb.buildQuery(null,
1088                null, null, null, null, null);
1089        // Build the bookmark union subquery
1090        qb.setTables(TABLE_BOOKMARKS_JOIN_IMAGES);
1091        qb.setProjectionMap(COMBINED_BOOKMARK_PROJECTION_MAP);
1092        where += String.format(" AND %s NOT IN (SELECT %s FROM %s)",
1093                Combined.URL, History.URL, TABLE_HISTORY);
1094        String bookmarksSubQuery = qb.buildQuery(null, where,
1095                null, null, null, null);
1096        // Put it all together
1097        String query = qb.buildUnionQuery(
1098                new String[] {historySubQuery, bookmarksSubQuery},
1099                null, null);
1100        qb.setTables("(" + query + ")");
1101        qb.setProjectionMap(null);
1102        return args;
1103    }
1104
1105    int deleteBookmarks(String selection, String[] selectionArgs,
1106            boolean callerIsSyncAdapter) {
1107        //TODO cascade deletes down from folders
1108        final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1109        if (callerIsSyncAdapter) {
1110            return db.delete(TABLE_BOOKMARKS, selection, selectionArgs);
1111        }
1112        ContentValues values = new ContentValues();
1113        values.put(Bookmarks.DATE_MODIFIED, System.currentTimeMillis());
1114        values.put(Bookmarks.IS_DELETED, 1);
1115        return updateBookmarksInTransaction(values, selection, selectionArgs,
1116                callerIsSyncAdapter);
1117    }
1118
1119    @Override
1120    public int deleteInTransaction(Uri uri, String selection, String[] selectionArgs,
1121            boolean callerIsSyncAdapter) {
1122        final int match = URI_MATCHER.match(uri);
1123        final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1124        int deleted = 0;
1125        switch (match) {
1126            case BOOKMARKS_ID: {
1127                selection = DatabaseUtils.concatenateWhere(selection,
1128                        TABLE_BOOKMARKS + "._id=?");
1129                selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
1130                        new String[] { Long.toString(ContentUris.parseId(uri)) });
1131                // fall through
1132            }
1133            case BOOKMARKS: {
1134                // Look for account info
1135                Object[] withAccount = getSelectionWithAccounts(uri, selection, selectionArgs);
1136                selection = (String) withAccount[0];
1137                selectionArgs = (String[]) withAccount[1];
1138                deleted = deleteBookmarks(selection, selectionArgs, callerIsSyncAdapter);
1139                pruneImages();
1140                if (deleted > 0) {
1141                    refreshWidgets();
1142                }
1143                break;
1144            }
1145
1146            case HISTORY_ID: {
1147                selection = DatabaseUtils.concatenateWhere(selection, TABLE_HISTORY + "._id=?");
1148                selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
1149                        new String[] { Long.toString(ContentUris.parseId(uri)) });
1150                // fall through
1151            }
1152            case HISTORY: {
1153                filterSearchClient(selectionArgs);
1154                deleted = db.delete(TABLE_HISTORY, selection, selectionArgs);
1155                pruneImages();
1156                break;
1157            }
1158
1159            case SEARCHES_ID: {
1160                selection = DatabaseUtils.concatenateWhere(selection, TABLE_SEARCHES + "._id=?");
1161                selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
1162                        new String[] { Long.toString(ContentUris.parseId(uri)) });
1163                // fall through
1164            }
1165            case SEARCHES: {
1166                deleted = db.delete(TABLE_SEARCHES, selection, selectionArgs);
1167                break;
1168            }
1169
1170            case SYNCSTATE: {
1171                deleted = mSyncHelper.delete(db, selection, selectionArgs);
1172                break;
1173            }
1174            case SYNCSTATE_ID: {
1175                String selectionWithId =
1176                        (SyncStateContract.Columns._ID + "=" + ContentUris.parseId(uri) + " ")
1177                        + (selection == null ? "" : " AND (" + selection + ")");
1178                deleted = mSyncHelper.delete(db, selectionWithId, selectionArgs);
1179                break;
1180            }
1181            case LEGACY_ID: {
1182                selection = DatabaseUtils.concatenateWhere(
1183                        selection, Combined._ID + " = CAST(? AS INTEGER)");
1184                selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
1185                        new String[] { Long.toString(ContentUris.parseId(uri)) });
1186                // fall through
1187            }
1188            case LEGACY: {
1189                String[] projection = new String[] { Combined._ID,
1190                        Combined.IS_BOOKMARK, Combined.URL };
1191                SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
1192                String[] args = createCombinedQuery(uri, projection, qb);
1193                if (selectionArgs == null) {
1194                    selectionArgs = args;
1195                } else {
1196                    selectionArgs = DatabaseUtils.appendSelectionArgs(
1197                            args, selectionArgs);
1198                }
1199                Cursor c = qb.query(db, projection, selection, selectionArgs,
1200                        null, null, null);
1201                while (c.moveToNext()) {
1202                    long id = c.getLong(0);
1203                    boolean isBookmark = c.getInt(1) != 0;
1204                    String url = c.getString(2);
1205                    if (isBookmark) {
1206                        deleted += deleteBookmarks(Bookmarks._ID + "=?",
1207                                new String[] { Long.toString(id) },
1208                                callerIsSyncAdapter);
1209                        db.delete(TABLE_HISTORY, History.URL + "=?",
1210                                new String[] { url });
1211                    } else {
1212                        deleted += db.delete(TABLE_HISTORY,
1213                                Bookmarks._ID + "=?",
1214                                new String[] { Long.toString(id) });
1215                    }
1216                }
1217                break;
1218            }
1219            case SNAPSHOTS_ID: {
1220                selection = DatabaseUtils.concatenateWhere(selection, TABLE_SNAPSHOTS + "._id=?");
1221                selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
1222                        new String[] { Long.toString(ContentUris.parseId(uri)) });
1223                // fall through
1224            }
1225            case SNAPSHOTS: {
1226                deleted = db.delete(TABLE_SNAPSHOTS, selection, selectionArgs);
1227                break;
1228            }
1229            default: {
1230                throw new UnsupportedOperationException("Unknown delete URI " + uri);
1231            }
1232        }
1233        if (deleted > 0) {
1234            postNotifyUri(uri);
1235            postNotifyUri(LEGACY_AUTHORITY_URI);
1236        }
1237        return deleted;
1238    }
1239
1240    long queryDefaultFolderId(String accountName, String accountType) {
1241        if (!isNullAccount(accountName) && !isNullAccount(accountType)) {
1242            final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
1243            Cursor c = db.query(TABLE_BOOKMARKS, new String[] { Bookmarks._ID },
1244                    ChromeSyncColumns.SERVER_UNIQUE + " = ?" +
1245                    " AND account_type = ? AND account_name = ?",
1246                    new String[] { ChromeSyncColumns.FOLDER_NAME_BOOKMARKS_BAR,
1247                    accountType, accountName }, null, null, null);
1248            if (c.moveToFirst()) {
1249                return c.getLong(0);
1250            }
1251        }
1252        return FIXED_ID_ROOT;
1253    }
1254
1255    @Override
1256    public Uri insertInTransaction(Uri uri, ContentValues values, boolean callerIsSyncAdapter) {
1257        int match = URI_MATCHER.match(uri);
1258        final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1259        long id = -1;
1260        if (match == LEGACY) {
1261            // Intercept and route to the correct table
1262            Integer bookmark = values.getAsInteger(BookmarkColumns.BOOKMARK);
1263            values.remove(BookmarkColumns.BOOKMARK);
1264            if (bookmark == null || bookmark == 0) {
1265                match = HISTORY;
1266            } else {
1267                match = BOOKMARKS;
1268                values.remove(BookmarkColumns.DATE);
1269                values.remove(BookmarkColumns.VISITS);
1270                values.remove(BookmarkColumns.USER_ENTERED);
1271                values.put(Bookmarks.IS_FOLDER, 0);
1272            }
1273        }
1274        switch (match) {
1275            case BOOKMARKS: {
1276                // Mark rows dirty if they're not coming from a sync adapter
1277                if (!callerIsSyncAdapter) {
1278                    long now = System.currentTimeMillis();
1279                    values.put(Bookmarks.DATE_CREATED, now);
1280                    values.put(Bookmarks.DATE_MODIFIED, now);
1281                    values.put(Bookmarks.DIRTY, 1);
1282
1283                    String accountType = values
1284                            .getAsString(Bookmarks.ACCOUNT_TYPE);
1285                    String accountName = values
1286                            .getAsString(Bookmarks.ACCOUNT_NAME);
1287                    boolean hasParent = values.containsKey(Bookmarks.PARENT);
1288                    if (hasParent) {
1289                        // Let's make sure it's valid
1290                        long parentId = values.getAsLong(Bookmarks.PARENT);
1291                        hasParent = isValidParent(
1292                                accountType, accountName, parentId);
1293                    }
1294
1295                    // If no parent is set default to the "Bookmarks Bar" folder
1296                    if (!hasParent) {
1297                        values.put(Bookmarks.PARENT,
1298                                queryDefaultFolderId(accountName, accountType));
1299                    }
1300                }
1301
1302                // If no position is requested put the bookmark at the beginning of the list
1303                if (!values.containsKey(Bookmarks.POSITION)) {
1304                    values.put(Bookmarks.POSITION, Long.toString(Long.MIN_VALUE));
1305                }
1306
1307                // Extract out the image values so they can be inserted into the images table
1308                String url = values.getAsString(Bookmarks.URL);
1309                ContentValues imageValues = extractImageValues(values, url);
1310                Boolean isFolder = values.getAsBoolean(Bookmarks.IS_FOLDER);
1311                if ((isFolder == null || !isFolder)
1312                        && imageValues != null && !TextUtils.isEmpty(url)) {
1313                    int count = db.update(TABLE_IMAGES, imageValues, Images.URL + "=?",
1314                            new String[] { url });
1315                    if (count == 0) {
1316                        db.insertOrThrow(TABLE_IMAGES, Images.FAVICON, imageValues);
1317                    }
1318                }
1319
1320                id = db.insertOrThrow(TABLE_BOOKMARKS, Bookmarks.DIRTY, values);
1321                refreshWidgets();
1322                break;
1323            }
1324
1325            case HISTORY: {
1326                // If no created time is specified set it to now
1327                if (!values.containsKey(History.DATE_CREATED)) {
1328                    values.put(History.DATE_CREATED, System.currentTimeMillis());
1329                }
1330                String url = values.getAsString(History.URL);
1331                url = filterSearchClient(url);
1332                values.put(History.URL, url);
1333
1334                // Extract out the image values so they can be inserted into the images table
1335                ContentValues imageValues = extractImageValues(values,
1336                        values.getAsString(History.URL));
1337                if (imageValues != null) {
1338                    db.insertOrThrow(TABLE_IMAGES, Images.FAVICON, imageValues);
1339                }
1340
1341                id = db.insertOrThrow(TABLE_HISTORY, History.VISITS, values);
1342                break;
1343            }
1344
1345            case SEARCHES: {
1346                id = insertSearchesInTransaction(db, values);
1347                break;
1348            }
1349
1350            case SYNCSTATE: {
1351                id = mSyncHelper.insert(db, values);
1352                break;
1353            }
1354
1355            case SETTINGS: {
1356                id = 0;
1357                insertSettingsInTransaction(db, values);
1358                break;
1359            }
1360
1361            case SNAPSHOTS: {
1362                id = db.insertOrThrow(TABLE_SNAPSHOTS, Snapshots.TITLE, values);
1363                break;
1364            }
1365
1366            default: {
1367                throw new UnsupportedOperationException("Unknown insert URI " + uri);
1368            }
1369        }
1370
1371        if (id >= 0) {
1372            postNotifyUri(uri);
1373            postNotifyUri(LEGACY_AUTHORITY_URI);
1374            return ContentUris.withAppendedId(uri, id);
1375        } else {
1376            return null;
1377        }
1378    }
1379
1380    private boolean isValidParent(String accountType, String accountName,
1381            long parentId) {
1382        if (parentId <= 0) {
1383            return false;
1384        }
1385        Uri uri = ContentUris.withAppendedId(Bookmarks.CONTENT_URI, parentId);
1386        Cursor c = query(uri,
1387                new String[] { Bookmarks.ACCOUNT_NAME, Bookmarks.ACCOUNT_TYPE },
1388                null, null, null);
1389        try {
1390            if (c.moveToFirst()) {
1391                String parentName = c.getString(0);
1392                String parentType = c.getString(1);
1393                if (TextUtils.equals(accountName, parentName)
1394                        && TextUtils.equals(accountType, parentType)) {
1395                    return true;
1396                }
1397            }
1398            return false;
1399        } finally {
1400            c.close();
1401        }
1402    }
1403
1404    private void filterSearchClient(String[] selectionArgs) {
1405        if (selectionArgs != null) {
1406            for (int i = 0; i < selectionArgs.length; i++) {
1407                selectionArgs[i] = filterSearchClient(selectionArgs[i]);
1408            }
1409        }
1410    }
1411
1412    // Filters out the client= param for search urls
1413    private String filterSearchClient(String url) {
1414        // remove "client" before updating it to the history so that it wont
1415        // show up in the auto-complete list.
1416        int index = url.indexOf("client=");
1417        if (index > 0 && url.contains(".google.")) {
1418            int end = url.indexOf('&', index);
1419            if (end > 0) {
1420                url = url.substring(0, index)
1421                        .concat(url.substring(end + 1));
1422            } else {
1423                // the url.charAt(index-1) should be either '?' or '&'
1424                url = url.substring(0, index-1);
1425            }
1426        }
1427        return url;
1428    }
1429
1430    /**
1431     * Searches are unique, so perform an UPSERT manually since SQLite doesn't support them.
1432     */
1433    private long insertSearchesInTransaction(SQLiteDatabase db, ContentValues values) {
1434        String search = values.getAsString(Searches.SEARCH);
1435        if (TextUtils.isEmpty(search)) {
1436            throw new IllegalArgumentException("Must include the SEARCH field");
1437        }
1438        Cursor cursor = null;
1439        try {
1440            cursor = db.query(TABLE_SEARCHES, new String[] { Searches._ID },
1441                    Searches.SEARCH + "=?", new String[] { search }, null, null, null);
1442            if (cursor.moveToNext()) {
1443                long id = cursor.getLong(0);
1444                db.update(TABLE_SEARCHES, values, Searches._ID + "=?",
1445                        new String[] { Long.toString(id) });
1446                return id;
1447            } else {
1448                return db.insertOrThrow(TABLE_SEARCHES, Searches.SEARCH, values);
1449            }
1450        } finally {
1451            if (cursor != null) cursor.close();
1452        }
1453    }
1454
1455    /**
1456     * Settings are unique, so perform an UPSERT manually since SQLite doesn't support them.
1457     */
1458    private long insertSettingsInTransaction(SQLiteDatabase db, ContentValues values) {
1459        String key = values.getAsString(Settings.KEY);
1460        if (TextUtils.isEmpty(key)) {
1461            throw new IllegalArgumentException("Must include the KEY field");
1462        }
1463        String[] keyArray = new String[] { key };
1464        Cursor cursor = null;
1465        try {
1466            cursor = db.query(TABLE_SETTINGS, new String[] { Settings.KEY },
1467                    Settings.KEY + "=?", keyArray, null, null, null);
1468            if (cursor.moveToNext()) {
1469                long id = cursor.getLong(0);
1470                db.update(TABLE_SETTINGS, values, Settings.KEY + "=?", keyArray);
1471                return id;
1472            } else {
1473                return db.insertOrThrow(TABLE_SETTINGS, Settings.VALUE, values);
1474            }
1475        } finally {
1476            if (cursor != null) cursor.close();
1477        }
1478    }
1479
1480    @Override
1481    public int updateInTransaction(Uri uri, ContentValues values, String selection,
1482            String[] selectionArgs, boolean callerIsSyncAdapter) {
1483        int match = URI_MATCHER.match(uri);
1484        final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1485        if (match == LEGACY || match == LEGACY_ID) {
1486            // Intercept and route to the correct table
1487            Integer bookmark = values.getAsInteger(BookmarkColumns.BOOKMARK);
1488            values.remove(BookmarkColumns.BOOKMARK);
1489            if (bookmark == null || bookmark == 0) {
1490                if (match == LEGACY) {
1491                    match = HISTORY;
1492                } else {
1493                    match = HISTORY_ID;
1494                }
1495            } else {
1496                if (match == LEGACY) {
1497                    match = BOOKMARKS;
1498                } else {
1499                    match = BOOKMARKS_ID;
1500                }
1501                values.remove(BookmarkColumns.DATE);
1502                values.remove(BookmarkColumns.VISITS);
1503                values.remove(BookmarkColumns.USER_ENTERED);
1504            }
1505        }
1506        int modified = 0;
1507        switch (match) {
1508            case BOOKMARKS_ID: {
1509                selection = DatabaseUtils.concatenateWhere(selection,
1510                        TABLE_BOOKMARKS + "._id=?");
1511                selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
1512                        new String[] { Long.toString(ContentUris.parseId(uri)) });
1513                // fall through
1514            }
1515            case BOOKMARKS: {
1516                Object[] withAccount = getSelectionWithAccounts(uri, selection, selectionArgs);
1517                selection = (String) withAccount[0];
1518                selectionArgs = (String[]) withAccount[1];
1519                modified = updateBookmarksInTransaction(values, selection, selectionArgs,
1520                        callerIsSyncAdapter);
1521                if (modified > 0) {
1522                    refreshWidgets();
1523                }
1524                break;
1525            }
1526
1527            case HISTORY_ID: {
1528                selection = DatabaseUtils.concatenateWhere(selection, TABLE_HISTORY + "._id=?");
1529                selectionArgs = DatabaseUtils.appendSelectionArgs(selectionArgs,
1530                        new String[] { Long.toString(ContentUris.parseId(uri)) });
1531                // fall through
1532            }
1533            case HISTORY: {
1534                modified = updateHistoryInTransaction(values, selection, selectionArgs);
1535                break;
1536            }
1537
1538            case SYNCSTATE: {
1539                modified = mSyncHelper.update(mDb, values,
1540                        appendAccountToSelection(uri, selection), selectionArgs);
1541                break;
1542            }
1543
1544            case SYNCSTATE_ID: {
1545                selection = appendAccountToSelection(uri, selection);
1546                String selectionWithId =
1547                        (SyncStateContract.Columns._ID + "=" + ContentUris.parseId(uri) + " ")
1548                        + (selection == null ? "" : " AND (" + selection + ")");
1549                modified = mSyncHelper.update(mDb, values,
1550                        selectionWithId, selectionArgs);
1551                break;
1552            }
1553
1554            case IMAGES: {
1555                String url = values.getAsString(Images.URL);
1556                if (TextUtils.isEmpty(url)) {
1557                    throw new IllegalArgumentException("Images.URL is required");
1558                }
1559                if (!shouldUpdateImages(db, url, values)) {
1560                    return 0;
1561                }
1562                int count = db.update(TABLE_IMAGES, values, Images.URL + "=?",
1563                        new String[] { url });
1564                if (count == 0) {
1565                    db.insertOrThrow(TABLE_IMAGES, Images.FAVICON, values);
1566                    count = 1;
1567                }
1568                if (getUrlCount(db, TABLE_BOOKMARKS, url) > 0) {
1569                    postNotifyUri(Bookmarks.CONTENT_URI);
1570                    refreshWidgets();
1571                }
1572                if (getUrlCount(db, TABLE_HISTORY, url) > 0) {
1573                    postNotifyUri(History.CONTENT_URI);
1574                }
1575                postNotifyUri(LEGACY_AUTHORITY_URI);
1576                pruneImages();
1577                return count;
1578            }
1579
1580            case SEARCHES: {
1581                modified = db.update(TABLE_SEARCHES, values, selection, selectionArgs);
1582                break;
1583            }
1584
1585            default: {
1586                throw new UnsupportedOperationException("Unknown update URI " + uri);
1587            }
1588        }
1589        pruneImages();
1590        if (modified > 0) {
1591            postNotifyUri(uri);
1592            postNotifyUri(LEGACY_AUTHORITY_URI);
1593        }
1594        return modified;
1595    }
1596
1597    // We want to avoid sending out more URI notifications than we have to
1598    // Thus, we check to see if the images we are about to store are already there
1599    // This is used because things like a site's favion or touch icon is rarely
1600    // changed, but the browser tries to update it every time the page loads.
1601    // Without this, we will always send out 3 URI notifications per page load.
1602    // With this, that drops to 0 or 1, depending on if the thumbnail changed.
1603    private boolean shouldUpdateImages(
1604            SQLiteDatabase db, String url, ContentValues values) {
1605        final String[] projection = new String[] {
1606                Images.FAVICON,
1607                Images.THUMBNAIL,
1608                Images.TOUCH_ICON,
1609        };
1610        Cursor cursor = db.query(TABLE_IMAGES, projection, Images.URL + "=?",
1611                new String[] { url }, null, null, null);
1612        byte[] nfavicon = values.getAsByteArray(Images.FAVICON);
1613        byte[] nthumb = values.getAsByteArray(Images.THUMBNAIL);
1614        byte[] ntouch = values.getAsByteArray(Images.TOUCH_ICON);
1615        byte[] cfavicon = null;
1616        byte[] cthumb = null;
1617        byte[] ctouch = null;
1618        try {
1619            if (cursor.getCount() <= 0) {
1620                return nfavicon != null || nthumb != null || ntouch != null;
1621            }
1622            while (cursor.moveToNext()) {
1623                if (nfavicon != null) {
1624                    cfavicon = cursor.getBlob(0);
1625                    if (!Arrays.equals(nfavicon, cfavicon)) {
1626                        return true;
1627                    }
1628                }
1629                if (nthumb != null) {
1630                    cthumb = cursor.getBlob(1);
1631                    if (!Arrays.equals(nthumb, cthumb)) {
1632                        return true;
1633                    }
1634                }
1635                if (ntouch != null) {
1636                    ctouch = cursor.getBlob(2);
1637                    if (!Arrays.equals(ntouch, ctouch)) {
1638                        return true;
1639                    }
1640                }
1641            }
1642        } finally {
1643            cursor.close();
1644        }
1645        return false;
1646    }
1647
1648    int getUrlCount(SQLiteDatabase db, String table, String url) {
1649        Cursor c = db.query(table, new String[] { "COUNT(*)" },
1650                "url = ?", new String[] { url }, null, null, null);
1651        try {
1652            int count = 0;
1653            if (c.moveToFirst()) {
1654                count = c.getInt(0);
1655            }
1656            return count;
1657        } finally {
1658            c.close();
1659        }
1660    }
1661
1662    /**
1663     * Does a query to find the matching bookmarks and updates each one with the provided values.
1664     */
1665    int updateBookmarksInTransaction(ContentValues values, String selection,
1666            String[] selectionArgs, boolean callerIsSyncAdapter) {
1667        int count = 0;
1668        final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1669        final String[] bookmarksProjection = new String[] {
1670                Bookmarks._ID, // 0
1671                Bookmarks.VERSION, // 1
1672                Bookmarks.URL, // 2
1673                Bookmarks.TITLE, // 3
1674                Bookmarks.IS_FOLDER, // 4
1675                Bookmarks.ACCOUNT_NAME, // 5
1676                Bookmarks.ACCOUNT_TYPE, // 6
1677        };
1678        Cursor cursor = db.query(TABLE_BOOKMARKS, bookmarksProjection,
1679                selection, selectionArgs, null, null, null);
1680        boolean updatingParent = values.containsKey(Bookmarks.PARENT);
1681        String parentAccountName = null;
1682        String parentAccountType = null;
1683        if (updatingParent) {
1684            long parent = values.getAsLong(Bookmarks.PARENT);
1685            Cursor c = db.query(TABLE_BOOKMARKS, new String[] {
1686                    Bookmarks.ACCOUNT_NAME, Bookmarks.ACCOUNT_TYPE},
1687                    "_id = ?", new String[] { Long.toString(parent) },
1688                    null, null, null);
1689            if (c.moveToFirst()) {
1690                parentAccountName = c.getString(0);
1691                parentAccountType = c.getString(1);
1692                c.close();
1693            }
1694        } else if (values.containsKey(Bookmarks.ACCOUNT_NAME)
1695                || values.containsKey(Bookmarks.ACCOUNT_TYPE)) {
1696            // TODO: Implement if needed (no one needs this yet)
1697        }
1698        try {
1699            String[] args = new String[1];
1700            // Mark the bookmark dirty if the caller isn't a sync adapter
1701            if (!callerIsSyncAdapter) {
1702                values.put(Bookmarks.DATE_MODIFIED, System.currentTimeMillis());
1703                values.put(Bookmarks.DIRTY, 1);
1704            }
1705
1706            boolean updatingUrl = values.containsKey(Bookmarks.URL);
1707            String url = null;
1708            if (updatingUrl) {
1709                url = values.getAsString(Bookmarks.URL);
1710            }
1711            ContentValues imageValues = extractImageValues(values, url);
1712
1713            while (cursor.moveToNext()) {
1714                long id = cursor.getLong(0);
1715                args[0] = Long.toString(id);
1716                String accountName = cursor.getString(5);
1717                String accountType = cursor.getString(6);
1718                // If we are updating the parent and either the account name or
1719                // type do not match that of the new parent
1720                if (updatingParent
1721                        && (!TextUtils.equals(accountName, parentAccountName)
1722                        || !TextUtils.equals(accountType, parentAccountType))) {
1723                    // Parent is a different account
1724                    // First, insert a new bookmark/folder with the new account
1725                    // Then, if this is a folder, reparent all it's children
1726                    // Finally, delete the old bookmark/folder
1727                    ContentValues newValues = valuesFromCursor(cursor);
1728                    newValues.putAll(values);
1729                    newValues.remove(Bookmarks._ID);
1730                    newValues.remove(Bookmarks.VERSION);
1731                    newValues.put(Bookmarks.ACCOUNT_NAME, parentAccountName);
1732                    newValues.put(Bookmarks.ACCOUNT_TYPE, parentAccountType);
1733                    Uri insertUri = insertInTransaction(Bookmarks.CONTENT_URI,
1734                            newValues, callerIsSyncAdapter);
1735                    long newId = ContentUris.parseId(insertUri);
1736                    if (cursor.getInt(4) != 0) {
1737                        // This is a folder, reparent
1738                        ContentValues updateChildren = new ContentValues(1);
1739                        updateChildren.put(Bookmarks.PARENT, newId);
1740                        count += updateBookmarksInTransaction(updateChildren,
1741                                Bookmarks.PARENT + "=?", new String[] {
1742                                Long.toString(id)}, callerIsSyncAdapter);
1743                    }
1744                    // Now, delete the old one
1745                    Uri uri = ContentUris.withAppendedId(Bookmarks.CONTENT_URI, id);
1746                    deleteInTransaction(uri, null, null, callerIsSyncAdapter);
1747                    count += 1;
1748                } else {
1749                    if (!callerIsSyncAdapter) {
1750                        // increase the local version for non-sync changes
1751                        values.put(Bookmarks.VERSION, cursor.getLong(1) + 1);
1752                    }
1753                    count += db.update(TABLE_BOOKMARKS, values, "_id=?", args);
1754                }
1755
1756                // Update the images over in their table
1757                if (imageValues != null) {
1758                    if (!updatingUrl) {
1759                        url = cursor.getString(2);
1760                        imageValues.put(Images.URL, url);
1761                    }
1762
1763                    if (!TextUtils.isEmpty(url)) {
1764                        args[0] = url;
1765                        if (db.update(TABLE_IMAGES, imageValues, Images.URL + "=?", args) == 0) {
1766                            db.insert(TABLE_IMAGES, Images.FAVICON, imageValues);
1767                        }
1768                    }
1769                }
1770            }
1771        } finally {
1772            if (cursor != null) cursor.close();
1773        }
1774        return count;
1775    }
1776
1777    ContentValues valuesFromCursor(Cursor c) {
1778        int count = c.getColumnCount();
1779        ContentValues values = new ContentValues(count);
1780        String[] colNames = c.getColumnNames();
1781        for (int i = 0; i < count; i++) {
1782            switch (c.getType(i)) {
1783            case Cursor.FIELD_TYPE_BLOB:
1784                values.put(colNames[i], c.getBlob(i));
1785                break;
1786            case Cursor.FIELD_TYPE_FLOAT:
1787                values.put(colNames[i], c.getFloat(i));
1788                break;
1789            case Cursor.FIELD_TYPE_INTEGER:
1790                values.put(colNames[i], c.getLong(i));
1791                break;
1792            case Cursor.FIELD_TYPE_STRING:
1793                values.put(colNames[i], c.getString(i));
1794                break;
1795            }
1796        }
1797        return values;
1798    }
1799
1800    /**
1801     * Does a query to find the matching bookmarks and updates each one with the provided values.
1802     */
1803    int updateHistoryInTransaction(ContentValues values, String selection, String[] selectionArgs) {
1804        int count = 0;
1805        final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1806        filterSearchClient(selectionArgs);
1807        Cursor cursor = query(History.CONTENT_URI,
1808                new String[] { History._ID, History.URL },
1809                selection, selectionArgs, null);
1810        try {
1811            String[] args = new String[1];
1812
1813            boolean updatingUrl = values.containsKey(History.URL);
1814            String url = null;
1815            if (updatingUrl) {
1816                url = filterSearchClient(values.getAsString(History.URL));
1817                values.put(History.URL, url);
1818            }
1819            ContentValues imageValues = extractImageValues(values, url);
1820
1821            while (cursor.moveToNext()) {
1822                args[0] = cursor.getString(0);
1823                count += db.update(TABLE_HISTORY, values, "_id=?", args);
1824
1825                // Update the images over in their table
1826                if (imageValues != null) {
1827                    if (!updatingUrl) {
1828                        url = cursor.getString(1);
1829                        imageValues.put(Images.URL, url);
1830                    }
1831                    args[0] = url;
1832                    if (db.update(TABLE_IMAGES, imageValues, Images.URL + "=?", args) == 0) {
1833                        db.insert(TABLE_IMAGES, Images.FAVICON, imageValues);
1834                    }
1835                }
1836            }
1837        } finally {
1838            if (cursor != null) cursor.close();
1839        }
1840        return count;
1841    }
1842
1843    String appendAccountToSelection(Uri uri, String selection) {
1844        final String accountName = uri.getQueryParameter(RawContacts.ACCOUNT_NAME);
1845        final String accountType = uri.getQueryParameter(RawContacts.ACCOUNT_TYPE);
1846
1847        final boolean partialUri = TextUtils.isEmpty(accountName) ^ TextUtils.isEmpty(accountType);
1848        if (partialUri) {
1849            // Throw when either account is incomplete
1850            throw new IllegalArgumentException(
1851                    "Must specify both or neither of ACCOUNT_NAME and ACCOUNT_TYPE for " + uri);
1852        }
1853
1854        // Accounts are valid by only checking one parameter, since we've
1855        // already ruled out partial accounts.
1856        final boolean validAccount = !TextUtils.isEmpty(accountName);
1857        if (validAccount) {
1858            StringBuilder selectionSb = new StringBuilder(RawContacts.ACCOUNT_NAME + "="
1859                    + DatabaseUtils.sqlEscapeString(accountName) + " AND "
1860                    + RawContacts.ACCOUNT_TYPE + "="
1861                    + DatabaseUtils.sqlEscapeString(accountType));
1862            if (!TextUtils.isEmpty(selection)) {
1863                selectionSb.append(" AND (");
1864                selectionSb.append(selection);
1865                selectionSb.append(')');
1866            }
1867            return selectionSb.toString();
1868        } else {
1869            return selection;
1870        }
1871    }
1872
1873    ContentValues extractImageValues(ContentValues values, String url) {
1874        ContentValues imageValues = null;
1875        // favicon
1876        if (values.containsKey(Bookmarks.FAVICON)) {
1877            imageValues = new ContentValues();
1878            imageValues.put(Images.FAVICON, values.getAsByteArray(Bookmarks.FAVICON));
1879            values.remove(Bookmarks.FAVICON);
1880        }
1881
1882        // thumbnail
1883        if (values.containsKey(Bookmarks.THUMBNAIL)) {
1884            if (imageValues == null) {
1885                imageValues = new ContentValues();
1886            }
1887            imageValues.put(Images.THUMBNAIL, values.getAsByteArray(Bookmarks.THUMBNAIL));
1888            values.remove(Bookmarks.THUMBNAIL);
1889        }
1890
1891        // touch icon
1892        if (values.containsKey(Bookmarks.TOUCH_ICON)) {
1893            if (imageValues == null) {
1894                imageValues = new ContentValues();
1895            }
1896            imageValues.put(Images.TOUCH_ICON, values.getAsByteArray(Bookmarks.TOUCH_ICON));
1897            values.remove(Bookmarks.TOUCH_ICON);
1898        }
1899
1900        if (imageValues != null) {
1901            imageValues.put(Images.URL,  url);
1902        }
1903        return imageValues;
1904    }
1905
1906    void pruneImages() {
1907        final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
1908        db.delete(TABLE_IMAGES, IMAGE_PRUNE, null);
1909    }
1910
1911    static class SuggestionsCursor extends AbstractCursor {
1912        private static final int ID_INDEX = 0;
1913        private static final int URL_INDEX = 1;
1914        private static final int TITLE_INDEX = 2;
1915        // shared suggestion array index, make sure to match COLUMNS
1916        private static final int SUGGEST_COLUMN_INTENT_ACTION_ID = 1;
1917        private static final int SUGGEST_COLUMN_INTENT_DATA_ID = 2;
1918        private static final int SUGGEST_COLUMN_TEXT_1_ID = 3;
1919        private static final int SUGGEST_COLUMN_TEXT_2_TEXT_ID = 4;
1920        private static final int SUGGEST_COLUMN_TEXT_2_URL_ID = 5;
1921        private static final int SUGGEST_COLUMN_ICON_1_ID = 6;
1922
1923        // shared suggestion columns
1924        private static final String[] COLUMNS = new String[] {
1925                BaseColumns._ID,
1926                SearchManager.SUGGEST_COLUMN_INTENT_ACTION,
1927                SearchManager.SUGGEST_COLUMN_INTENT_DATA,
1928                SearchManager.SUGGEST_COLUMN_TEXT_1,
1929                SearchManager.SUGGEST_COLUMN_TEXT_2,
1930                SearchManager.SUGGEST_COLUMN_TEXT_2_URL,
1931                SearchManager.SUGGEST_COLUMN_ICON_1};
1932
1933        private Cursor mSource;
1934
1935        public SuggestionsCursor(Cursor cursor) {
1936            mSource = cursor;
1937        }
1938
1939        @Override
1940        public String[] getColumnNames() {
1941            return COLUMNS;
1942        }
1943
1944        @Override
1945        public String getString(int columnIndex) {
1946            switch (columnIndex) {
1947            case ID_INDEX:
1948                return mSource.getString(columnIndex);
1949            case SUGGEST_COLUMN_INTENT_ACTION_ID:
1950                return Intent.ACTION_VIEW;
1951            case SUGGEST_COLUMN_INTENT_DATA_ID:
1952            case SUGGEST_COLUMN_TEXT_2_TEXT_ID:
1953            case SUGGEST_COLUMN_TEXT_2_URL_ID:
1954                return UrlUtils.stripUrl(mSource.getString(URL_INDEX));
1955            case SUGGEST_COLUMN_TEXT_1_ID:
1956                return mSource.getString(TITLE_INDEX);
1957            case SUGGEST_COLUMN_ICON_1_ID:
1958                return Integer.toString(R.drawable.ic_bookmark_off_holo_dark);
1959            }
1960            return null;
1961        }
1962
1963        @Override
1964        public int getCount() {
1965            return mSource.getCount();
1966        }
1967
1968        @Override
1969        public double getDouble(int column) {
1970            throw new UnsupportedOperationException();
1971        }
1972
1973        @Override
1974        public float getFloat(int column) {
1975            throw new UnsupportedOperationException();
1976        }
1977
1978        @Override
1979        public int getInt(int column) {
1980            throw new UnsupportedOperationException();
1981        }
1982
1983        @Override
1984        public long getLong(int column) {
1985            switch (column) {
1986            case ID_INDEX:
1987                return mSource.getLong(ID_INDEX);
1988            }
1989            throw new UnsupportedOperationException();
1990        }
1991
1992        @Override
1993        public short getShort(int column) {
1994            throw new UnsupportedOperationException();
1995        }
1996
1997        @Override
1998        public boolean isNull(int column) {
1999            return mSource.isNull(column);
2000        }
2001
2002        @Override
2003        public boolean onMove(int oldPosition, int newPosition) {
2004            return mSource.moveToPosition(newPosition);
2005        }
2006    }
2007}
2008