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