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