EmailProvider.java revision 75987dbe0ca7609bf4f11f2d7edfe4bcd70a4fe5
1/*
2 * Copyright (C) 2009 The 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.email.provider;
18
19import android.accounts.AccountManager;
20import android.content.ContentProvider;
21import android.content.ContentProviderOperation;
22import android.content.ContentProviderResult;
23import android.content.ContentResolver;
24import android.content.ContentUris;
25import android.content.ContentValues;
26import android.content.Intent;
27import android.content.Context;
28import android.content.OperationApplicationException;
29import android.content.UriMatcher;
30import android.database.ContentObserver;
31import android.database.Cursor;
32import android.database.MatrixCursor;
33import android.database.SQLException;
34import android.database.sqlite.SQLiteDatabase;
35import android.database.sqlite.SQLiteException;
36import android.database.sqlite.SQLiteOpenHelper;
37import android.net.Uri;
38import android.provider.ContactsContract;
39import android.text.TextUtils;
40import android.util.Log;
41
42import com.android.email.Email;
43import com.android.email.Preferences;
44import com.android.email.provider.ContentCache.CacheToken;
45import com.android.email.service.AttachmentDownloadService;
46import com.android.emailcommon.AccountManagerTypes;
47import com.android.emailcommon.CalendarProviderStub;
48import com.android.emailcommon.Logging;
49import com.android.emailcommon.provider.Account;
50import com.android.emailcommon.provider.EmailContent;
51import com.android.emailcommon.provider.EmailContent.AccountColumns;
52import com.android.emailcommon.provider.EmailContent.Attachment;
53import com.android.emailcommon.provider.EmailContent.AttachmentColumns;
54import com.android.emailcommon.provider.EmailContent.Body;
55import com.android.emailcommon.provider.EmailContent.BodyColumns;
56import com.android.emailcommon.provider.EmailContent.HostAuthColumns;
57import com.android.emailcommon.provider.EmailContent.MailboxColumns;
58import com.android.emailcommon.provider.EmailContent.Message;
59import com.android.emailcommon.provider.EmailContent.MessageColumns;
60import com.android.emailcommon.provider.EmailContent.PolicyColumns;
61import com.android.emailcommon.provider.EmailContent.QuickResponseColumns;
62import com.android.emailcommon.provider.EmailContent.SyncColumns;
63import com.android.emailcommon.provider.HostAuth;
64import com.android.emailcommon.provider.Mailbox;
65import com.android.emailcommon.provider.Policy;
66import com.android.emailcommon.provider.QuickResponse;
67import com.android.emailcommon.service.LegacyPolicySet;
68import com.google.common.annotations.VisibleForTesting;
69
70import java.io.File;
71import java.util.ArrayList;
72import java.util.Arrays;
73import java.util.Collection;
74import java.util.HashMap;
75import java.util.List;
76import java.util.Map;
77
78public class EmailProvider extends ContentProvider {
79
80    private static final String TAG = "EmailProvider";
81
82    protected static final String DATABASE_NAME = "EmailProvider.db";
83    protected static final String BODY_DATABASE_NAME = "EmailProviderBody.db";
84    protected static final String BACKUP_DATABASE_NAME = "EmailProviderBackup.db";
85
86    public static final String ACTION_ATTACHMENT_UPDATED = "com.android.email.ATTACHMENT_UPDATED";
87    public static final String ATTACHMENT_UPDATED_EXTRA_FLAGS =
88        "com.android.email.ATTACHMENT_UPDATED_FLAGS";
89
90    /**
91     * Notifies that changes happened. Certain UI components, e.g., widgets, can register for this
92     * {@link android.content.Intent} and update accordingly. However, this can be very broad and
93     * is NOT the preferred way of getting notification.
94     */
95    public static final String ACTION_NOTIFY_MESSAGE_LIST_DATASET_CHANGED =
96            "com.android.email.MESSAGE_LIST_DATASET_CHANGED";
97
98    public static final String EMAIL_MESSAGE_MIME_TYPE =
99        "vnd.android.cursor.item/email-message";
100    public static final String EMAIL_ATTACHMENT_MIME_TYPE =
101        "vnd.android.cursor.item/email-attachment";
102
103    public static final Uri INTEGRITY_CHECK_URI =
104        Uri.parse("content://" + EmailContent.AUTHORITY + "/integrityCheck");
105    public static final Uri ACCOUNT_BACKUP_URI =
106        Uri.parse("content://" + EmailContent.AUTHORITY + "/accountBackup");
107
108    /** Appended to the notification URI for delete operations */
109    public static final String NOTIFICATION_OP_DELETE = "delete";
110    /** Appended to the notification URI for insert operations */
111    public static final String NOTIFICATION_OP_INSERT = "insert";
112    /** Appended to the notification URI for update operations */
113    public static final String NOTIFICATION_OP_UPDATE = "update";
114
115    // Definitions for our queries looking for orphaned messages
116    private static final String[] ORPHANS_PROJECTION
117        = new String[] {MessageColumns.ID, MessageColumns.MAILBOX_KEY};
118    private static final int ORPHANS_ID = 0;
119    private static final int ORPHANS_MAILBOX_KEY = 1;
120
121    private static final String WHERE_ID = EmailContent.RECORD_ID + "=?";
122
123    // This is not a hard limit on accounts, per se, but beyond this, we can't guarantee that all
124    // critical mailboxes, host auth's, accounts, and policies are cached
125    private static final int MAX_CACHED_ACCOUNTS = 16;
126    // Inbox, Drafts, Sent, Outbox, Trash, and Search (these boxes are cached when possible)
127    private static final int NUM_ALWAYS_CACHED_MAILBOXES = 6;
128
129    // We'll cache the following four tables; sizes are best estimates of effective values
130    private final ContentCache mCacheAccount =
131        new ContentCache("Account", Account.CONTENT_PROJECTION, MAX_CACHED_ACCOUNTS);
132    private final ContentCache mCacheHostAuth =
133        new ContentCache("HostAuth", HostAuth.CONTENT_PROJECTION, MAX_CACHED_ACCOUNTS * 2);
134    /*package*/ final ContentCache mCacheMailbox =
135        new ContentCache("Mailbox", Mailbox.CONTENT_PROJECTION,
136                MAX_CACHED_ACCOUNTS * (NUM_ALWAYS_CACHED_MAILBOXES + 2));
137    private final ContentCache mCacheMessage =
138        new ContentCache("Message", Message.CONTENT_PROJECTION, 8);
139    private final ContentCache mCachePolicy =
140        new ContentCache("Policy", Policy.CONTENT_PROJECTION, MAX_CACHED_ACCOUNTS);
141
142    // Any changes to the database format *must* include update-in-place code.
143    // Original version: 3
144    // Version 4: Database wipe required; changing AccountManager interface w/Exchange
145    // Version 5: Database wipe required; changing AccountManager interface w/Exchange
146    // Version 6: Adding Message.mServerTimeStamp column
147    // Version 7: Replace the mailbox_delete trigger with a version that removes orphaned messages
148    //            from the Message_Deletes and Message_Updates tables
149    // Version 8: Add security flags column to accounts table
150    // Version 9: Add security sync key and signature to accounts table
151    // Version 10: Add meeting info to message table
152    // Version 11: Add content and flags to attachment table
153    // Version 12: Add content_bytes to attachment table. content is deprecated.
154    // Version 13: Add messageCount to Mailbox table.
155    // Version 14: Add snippet to Message table
156    // Version 15: Fix upgrade problem in version 14.
157    // Version 16: Add accountKey to Attachment table
158    // Version 17: Add parentKey to Mailbox table
159    // Version 18: Copy Mailbox.displayName to Mailbox.serverId for all IMAP & POP3 mailboxes.
160    //             Column Mailbox.serverId is used for the server-side pathname of a mailbox.
161    // Version 19: Add Policy table; add policyKey to Account table and trigger to delete an
162    //             Account's policy when the Account is deleted
163    // Version 20: Add new policies to Policy table
164    // Version 21: Add lastSeenMessageKey column to Mailbox table
165    // Version 22: Upgrade path for IMAP/POP accounts to integrate with AccountManager
166    // Version 23: Add column to mailbox table for time of last access
167    // Version 24: Add column to hostauth table for client cert alias
168    // Version 25: Added QuickResponse table
169    // Version 26: Update IMAP accounts to add FLAG_SUPPORTS_SEARCH flag
170    // Version 27: Add protocolSearchInfo to Message table
171    // Version 28: Add notifiedMessageId and notifiedMessageCount to Account
172    // Version 29: Add protocolPoliciesEnforced and protocolPoliciesUnsupported to Policy
173
174    public static final int DATABASE_VERSION = 29;
175
176    // Any changes to the database format *must* include update-in-place code.
177    // Original version: 2
178    // Version 3: Add "sourceKey" column
179    // Version 4: Database wipe required; changing AccountManager interface w/Exchange
180    // Version 5: Database wipe required; changing AccountManager interface w/Exchange
181    // Version 6: Adding Body.mIntroText column
182    public static final int BODY_DATABASE_VERSION = 6;
183
184    private static final int ACCOUNT_BASE = 0;
185    private static final int ACCOUNT = ACCOUNT_BASE;
186    private static final int ACCOUNT_ID = ACCOUNT_BASE + 1;
187    private static final int ACCOUNT_ID_ADD_TO_FIELD = ACCOUNT_BASE + 2;
188    private static final int ACCOUNT_RESET_NEW_COUNT = ACCOUNT_BASE + 3;
189    private static final int ACCOUNT_RESET_NEW_COUNT_ID = ACCOUNT_BASE + 4;
190    private static final int ACCOUNT_DEFAULT_ID = ACCOUNT_BASE + 5;
191
192    private static final int MAILBOX_BASE = 0x1000;
193    private static final int MAILBOX = MAILBOX_BASE;
194    private static final int MAILBOX_ID = MAILBOX_BASE + 1;
195    private static final int MAILBOX_ID_FROM_ACCOUNT_AND_TYPE = MAILBOX_BASE + 2;
196    private static final int MAILBOX_ID_ADD_TO_FIELD = MAILBOX_BASE + 2;
197
198    private static final int MESSAGE_BASE = 0x2000;
199    private static final int MESSAGE = MESSAGE_BASE;
200    private static final int MESSAGE_ID = MESSAGE_BASE + 1;
201    private static final int SYNCED_MESSAGE_ID = MESSAGE_BASE + 2;
202
203    private static final int ATTACHMENT_BASE = 0x3000;
204    private static final int ATTACHMENT = ATTACHMENT_BASE;
205    private static final int ATTACHMENT_ID = ATTACHMENT_BASE + 1;
206    private static final int ATTACHMENTS_MESSAGE_ID = ATTACHMENT_BASE + 2;
207
208    private static final int HOSTAUTH_BASE = 0x4000;
209    private static final int HOSTAUTH = HOSTAUTH_BASE;
210    private static final int HOSTAUTH_ID = HOSTAUTH_BASE + 1;
211
212    private static final int UPDATED_MESSAGE_BASE = 0x5000;
213    private static final int UPDATED_MESSAGE = UPDATED_MESSAGE_BASE;
214    private static final int UPDATED_MESSAGE_ID = UPDATED_MESSAGE_BASE + 1;
215
216    private static final int DELETED_MESSAGE_BASE = 0x6000;
217    private static final int DELETED_MESSAGE = DELETED_MESSAGE_BASE;
218    private static final int DELETED_MESSAGE_ID = DELETED_MESSAGE_BASE + 1;
219
220    private static final int POLICY_BASE = 0x7000;
221    private static final int POLICY = POLICY_BASE;
222    private static final int POLICY_ID = POLICY_BASE + 1;
223
224    private static final int QUICK_RESPONSE_BASE = 0x8000;
225    private static final int QUICK_RESPONSE = QUICK_RESPONSE_BASE;
226    private static final int QUICK_RESPONSE_ID = QUICK_RESPONSE_BASE + 1;
227    private static final int QUICK_RESPONSE_ACCOUNT_ID = QUICK_RESPONSE_BASE + 2;
228
229    // MUST ALWAYS EQUAL THE LAST OF THE PREVIOUS BASE CONSTANTS
230    private static final int LAST_EMAIL_PROVIDER_DB_BASE = QUICK_RESPONSE_BASE;
231
232    // DO NOT CHANGE BODY_BASE!!
233    private static final int BODY_BASE = LAST_EMAIL_PROVIDER_DB_BASE + 0x1000;
234    private static final int BODY = BODY_BASE;
235    private static final int BODY_ID = BODY_BASE + 1;
236
237    private static final int BASE_SHIFT = 12;  // 12 bits to the base type: 0, 0x1000, 0x2000, etc.
238
239    // TABLE_NAMES MUST remain in the order of the BASE constants above (e.g. ACCOUNT_BASE = 0x0000,
240    // MESSAGE_BASE = 0x1000, etc.)
241    private static final String[] TABLE_NAMES = {
242        Account.TABLE_NAME,
243        Mailbox.TABLE_NAME,
244        Message.TABLE_NAME,
245        Attachment.TABLE_NAME,
246        HostAuth.TABLE_NAME,
247        Message.UPDATED_TABLE_NAME,
248        Message.DELETED_TABLE_NAME,
249        Policy.TABLE_NAME,
250        QuickResponse.TABLE_NAME,
251        Body.TABLE_NAME
252    };
253
254    // CONTENT_CACHES MUST remain in the order of the BASE constants above
255    private final ContentCache[] mContentCaches = {
256        mCacheAccount,
257        mCacheMailbox,
258        mCacheMessage,
259        null, // Attachment
260        mCacheHostAuth,
261        null, // Updated message
262        null, // Deleted message
263        mCachePolicy,
264        null, // Quick response
265        null  // Body
266    };
267
268    // CACHE_PROJECTIONS MUST remain in the order of the BASE constants above
269    private static final String[][] CACHE_PROJECTIONS = {
270        Account.CONTENT_PROJECTION,
271        Mailbox.CONTENT_PROJECTION,
272        Message.CONTENT_PROJECTION,
273        null, // Attachment
274        HostAuth.CONTENT_PROJECTION,
275        null, // Updated message
276        null, // Deleted message
277        Policy.CONTENT_PROJECTION,
278        null,  // Quick response
279        null  // Body
280    };
281
282    private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
283
284    private static final String MAILBOX_PRE_CACHE_SELECTION = MailboxColumns.TYPE + " IN (" +
285        Mailbox.TYPE_INBOX + "," + Mailbox.TYPE_DRAFTS + "," + Mailbox.TYPE_TRASH + "," +
286        Mailbox.TYPE_SENT + "," + Mailbox.TYPE_SEARCH + "," + Mailbox.TYPE_OUTBOX + ")";
287
288    /**
289     * Let's only generate these SQL strings once, as they are used frequently
290     * Note that this isn't relevant for table creation strings, since they are used only once
291     */
292    private static final String UPDATED_MESSAGE_INSERT = "insert or ignore into " +
293        Message.UPDATED_TABLE_NAME + " select * from " + Message.TABLE_NAME + " where " +
294        EmailContent.RECORD_ID + '=';
295
296    private static final String UPDATED_MESSAGE_DELETE = "delete from " +
297        Message.UPDATED_TABLE_NAME + " where " + EmailContent.RECORD_ID + '=';
298
299    private static final String DELETED_MESSAGE_INSERT = "insert or replace into " +
300        Message.DELETED_TABLE_NAME + " select * from " + Message.TABLE_NAME + " where " +
301        EmailContent.RECORD_ID + '=';
302
303    private static final String DELETE_ORPHAN_BODIES = "delete from " + Body.TABLE_NAME +
304        " where " + BodyColumns.MESSAGE_KEY + " in " + "(select " + BodyColumns.MESSAGE_KEY +
305        " from " + Body.TABLE_NAME + " except select " + EmailContent.RECORD_ID + " from " +
306        Message.TABLE_NAME + ')';
307
308    private static final String DELETE_BODY = "delete from " + Body.TABLE_NAME +
309        " where " + BodyColumns.MESSAGE_KEY + '=';
310
311    private static final String ID_EQUALS = EmailContent.RECORD_ID + "=?";
312
313    private static final String TRIGGER_MAILBOX_DELETE =
314        "create trigger mailbox_delete before delete on " + Mailbox.TABLE_NAME +
315        " begin" +
316        " delete from " + Message.TABLE_NAME +
317        "  where " + MessageColumns.MAILBOX_KEY + "=old." + EmailContent.RECORD_ID +
318        "; delete from " + Message.UPDATED_TABLE_NAME +
319        "  where " + MessageColumns.MAILBOX_KEY + "=old." + EmailContent.RECORD_ID +
320        "; delete from " + Message.DELETED_TABLE_NAME +
321        "  where " + MessageColumns.MAILBOX_KEY + "=old." + EmailContent.RECORD_ID +
322        "; end";
323
324    private static final String TRIGGER_ACCOUNT_DELETE =
325        "create trigger account_delete before delete on " + Account.TABLE_NAME +
326        " begin delete from " + Mailbox.TABLE_NAME +
327        " where " + MailboxColumns.ACCOUNT_KEY + "=old." + EmailContent.RECORD_ID +
328        "; delete from " + HostAuth.TABLE_NAME +
329        " where " + EmailContent.RECORD_ID + "=old." + AccountColumns.HOST_AUTH_KEY_RECV +
330        "; delete from " + HostAuth.TABLE_NAME +
331        " where " + EmailContent.RECORD_ID + "=old." + AccountColumns.HOST_AUTH_KEY_SEND +
332        "; delete from " + Policy.TABLE_NAME +
333        " where " + EmailContent.RECORD_ID + "=old." + AccountColumns.POLICY_KEY +
334        "; end";
335
336    private static final ContentValues CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT;
337
338    public static final String MESSAGE_URI_PARAMETER_MAILBOX_ID = "mailboxId";
339
340    static {
341        // Email URI matching table
342        UriMatcher matcher = sURIMatcher;
343
344        // All accounts
345        matcher.addURI(EmailContent.AUTHORITY, "account", ACCOUNT);
346        // A specific account
347        // insert into this URI causes a mailbox to be added to the account
348        matcher.addURI(EmailContent.AUTHORITY, "account/#", ACCOUNT_ID);
349        matcher.addURI(EmailContent.AUTHORITY, "account/default", ACCOUNT_DEFAULT_ID);
350
351        // Special URI to reset the new message count.  Only update works, and content values
352        // will be ignored.
353        matcher.addURI(EmailContent.AUTHORITY, "resetNewMessageCount",
354                ACCOUNT_RESET_NEW_COUNT);
355        matcher.addURI(EmailContent.AUTHORITY, "resetNewMessageCount/#",
356                ACCOUNT_RESET_NEW_COUNT_ID);
357
358        // All mailboxes
359        matcher.addURI(EmailContent.AUTHORITY, "mailbox", MAILBOX);
360        // A specific mailbox
361        // insert into this URI causes a message to be added to the mailbox
362        // ** NOTE For now, the accountKey must be set manually in the values!
363        matcher.addURI(EmailContent.AUTHORITY, "mailbox/#", MAILBOX_ID);
364        matcher.addURI(EmailContent.AUTHORITY, "mailboxIdFromAccountAndType/#/#",
365                MAILBOX_ID_FROM_ACCOUNT_AND_TYPE);
366        // All messages
367        matcher.addURI(EmailContent.AUTHORITY, "message", MESSAGE);
368        // A specific message
369        // insert into this URI causes an attachment to be added to the message
370        matcher.addURI(EmailContent.AUTHORITY, "message/#", MESSAGE_ID);
371
372        // A specific attachment
373        matcher.addURI(EmailContent.AUTHORITY, "attachment", ATTACHMENT);
374        // A specific attachment (the header information)
375        matcher.addURI(EmailContent.AUTHORITY, "attachment/#", ATTACHMENT_ID);
376        // The attachments of a specific message (query only) (insert & delete TBD)
377        matcher.addURI(EmailContent.AUTHORITY, "attachment/message/#",
378                ATTACHMENTS_MESSAGE_ID);
379
380        // All mail bodies
381        matcher.addURI(EmailContent.AUTHORITY, "body", BODY);
382        // A specific mail body
383        matcher.addURI(EmailContent.AUTHORITY, "body/#", BODY_ID);
384
385        // All hostauth records
386        matcher.addURI(EmailContent.AUTHORITY, "hostauth", HOSTAUTH);
387        // A specific hostauth
388        matcher.addURI(EmailContent.AUTHORITY, "hostauth/#", HOSTAUTH_ID);
389
390        // Atomically a constant value to a particular field of a mailbox/account
391        matcher.addURI(EmailContent.AUTHORITY, "mailboxIdAddToField/#",
392                MAILBOX_ID_ADD_TO_FIELD);
393        matcher.addURI(EmailContent.AUTHORITY, "accountIdAddToField/#",
394                ACCOUNT_ID_ADD_TO_FIELD);
395
396        /**
397         * THIS URI HAS SPECIAL SEMANTICS
398         * ITS USE IS INTENDED FOR THE UI APPLICATION TO MARK CHANGES THAT NEED TO BE SYNCED BACK
399         * TO A SERVER VIA A SYNC ADAPTER
400         */
401        matcher.addURI(EmailContent.AUTHORITY, "syncedMessage/#", SYNCED_MESSAGE_ID);
402
403        /**
404         * THE URIs BELOW THIS POINT ARE INTENDED TO BE USED BY SYNC ADAPTERS ONLY
405         * THEY REFER TO DATA CREATED AND MAINTAINED BY CALLS TO THE SYNCED_MESSAGE_ID URI
406         * BY THE UI APPLICATION
407         */
408        // All deleted messages
409        matcher.addURI(EmailContent.AUTHORITY, "deletedMessage", DELETED_MESSAGE);
410        // A specific deleted message
411        matcher.addURI(EmailContent.AUTHORITY, "deletedMessage/#", DELETED_MESSAGE_ID);
412
413        // All updated messages
414        matcher.addURI(EmailContent.AUTHORITY, "updatedMessage", UPDATED_MESSAGE);
415        // A specific updated message
416        matcher.addURI(EmailContent.AUTHORITY, "updatedMessage/#", UPDATED_MESSAGE_ID);
417
418        CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT = new ContentValues();
419        CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT.put(Account.NEW_MESSAGE_COUNT, 0);
420
421        matcher.addURI(EmailContent.AUTHORITY, "policy", POLICY);
422        matcher.addURI(EmailContent.AUTHORITY, "policy/#", POLICY_ID);
423
424        // All quick responses
425        matcher.addURI(EmailContent.AUTHORITY, "quickresponse", QUICK_RESPONSE);
426        // A specific quick response
427        matcher.addURI(EmailContent.AUTHORITY, "quickresponse/#", QUICK_RESPONSE_ID);
428        // All quick responses associated with a particular account id
429        matcher.addURI(EmailContent.AUTHORITY, "quickresponse/account/#",
430                QUICK_RESPONSE_ACCOUNT_ID);
431    }
432
433    /**
434     * Wrap the UriMatcher call so we can throw a runtime exception if an unknown Uri is passed in
435     * @param uri the Uri to match
436     * @return the match value
437     */
438    private static int findMatch(Uri uri, String methodName) {
439        int match = sURIMatcher.match(uri);
440        if (match < 0) {
441            throw new IllegalArgumentException("Unknown uri: " + uri);
442        } else if (Logging.LOGD) {
443            Log.v(TAG, methodName + ": uri=" + uri + ", match is " + match);
444        }
445        return match;
446    }
447
448    /*
449     * Internal helper method for index creation.
450     * Example:
451     * "create index message_" + MessageColumns.FLAG_READ
452     * + " on " + Message.TABLE_NAME + " (" + MessageColumns.FLAG_READ + ");"
453     */
454    /* package */
455    static String createIndex(String tableName, String columnName) {
456        return "create index " + tableName.toLowerCase() + '_' + columnName
457            + " on " + tableName + " (" + columnName + ");";
458    }
459
460    static void createMessageTable(SQLiteDatabase db) {
461        String messageColumns = MessageColumns.DISPLAY_NAME + " text, "
462            + MessageColumns.TIMESTAMP + " integer, "
463            + MessageColumns.SUBJECT + " text, "
464            + MessageColumns.FLAG_READ + " integer, "
465            + MessageColumns.FLAG_LOADED + " integer, "
466            + MessageColumns.FLAG_FAVORITE + " integer, "
467            + MessageColumns.FLAG_ATTACHMENT + " integer, "
468            + MessageColumns.FLAGS + " integer, "
469            + MessageColumns.CLIENT_ID + " integer, "
470            + MessageColumns.MESSAGE_ID + " text, "
471            + MessageColumns.MAILBOX_KEY + " integer, "
472            + MessageColumns.ACCOUNT_KEY + " integer, "
473            + MessageColumns.FROM_LIST + " text, "
474            + MessageColumns.TO_LIST + " text, "
475            + MessageColumns.CC_LIST + " text, "
476            + MessageColumns.BCC_LIST + " text, "
477            + MessageColumns.REPLY_TO_LIST + " text, "
478            + MessageColumns.MEETING_INFO + " text, "
479            + MessageColumns.SNIPPET + " text, "
480            + MessageColumns.PROTOCOL_SEARCH_INFO + " text"
481            + ");";
482
483        // This String and the following String MUST have the same columns, except for the type
484        // of those columns!
485        String createString = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
486            + SyncColumns.SERVER_ID + " text, "
487            + SyncColumns.SERVER_TIMESTAMP + " integer, "
488            + messageColumns;
489
490        // For the updated and deleted tables, the id is assigned, but we do want to keep track
491        // of the ORDER of updates using an autoincrement primary key.  We use the DATA column
492        // at this point; it has no other function
493        String altCreateString = " (" + EmailContent.RECORD_ID + " integer unique, "
494            + SyncColumns.SERVER_ID + " text, "
495            + SyncColumns.SERVER_TIMESTAMP + " integer, "
496            + messageColumns;
497
498        // The three tables have the same schema
499        db.execSQL("create table " + Message.TABLE_NAME + createString);
500        db.execSQL("create table " + Message.UPDATED_TABLE_NAME + altCreateString);
501        db.execSQL("create table " + Message.DELETED_TABLE_NAME + altCreateString);
502
503        String indexColumns[] = {
504            MessageColumns.TIMESTAMP,
505            MessageColumns.FLAG_READ,
506            MessageColumns.FLAG_LOADED,
507            MessageColumns.MAILBOX_KEY,
508            SyncColumns.SERVER_ID
509        };
510
511        for (String columnName : indexColumns) {
512            db.execSQL(createIndex(Message.TABLE_NAME, columnName));
513        }
514
515        // Deleting a Message deletes all associated Attachments
516        // Deleting the associated Body cannot be done in a trigger, because the Body is stored
517        // in a separate database, and trigger cannot operate on attached databases.
518        db.execSQL("create trigger message_delete before delete on " + Message.TABLE_NAME +
519                " begin delete from " + Attachment.TABLE_NAME +
520                "  where " + AttachmentColumns.MESSAGE_KEY + "=old." + EmailContent.RECORD_ID +
521                "; end");
522
523        // Add triggers to keep unread count accurate per mailbox
524
525        // NOTE: SQLite's before triggers are not safe when recursive triggers are involved.
526        // Use caution when changing them.
527
528        // Insert a message; if flagRead is zero, add to the unread count of the message's mailbox
529        db.execSQL("create trigger unread_message_insert before insert on " + Message.TABLE_NAME +
530                " when NEW." + MessageColumns.FLAG_READ + "=0" +
531                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
532                '=' + MailboxColumns.UNREAD_COUNT + "+1" +
533                "  where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
534                "; end");
535
536        // Delete a message; if flagRead is zero, decrement the unread count of the msg's mailbox
537        db.execSQL("create trigger unread_message_delete before delete on " + Message.TABLE_NAME +
538                " when OLD." + MessageColumns.FLAG_READ + "=0" +
539                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
540                '=' + MailboxColumns.UNREAD_COUNT + "-1" +
541                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
542                "; end");
543
544        // Change a message's mailbox
545        db.execSQL("create trigger unread_message_move before update of " +
546                MessageColumns.MAILBOX_KEY + " on " + Message.TABLE_NAME +
547                " when OLD." + MessageColumns.FLAG_READ + "=0" +
548                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
549                '=' + MailboxColumns.UNREAD_COUNT + "-1" +
550                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
551                "; update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
552                '=' + MailboxColumns.UNREAD_COUNT + "+1" +
553                " where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
554                "; end");
555
556        // Change a message's read state
557        db.execSQL("create trigger unread_message_read before update of " +
558                MessageColumns.FLAG_READ + " on " + Message.TABLE_NAME +
559                " when OLD." + MessageColumns.FLAG_READ + "!=NEW." + MessageColumns.FLAG_READ +
560                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
561                '=' + MailboxColumns.UNREAD_COUNT + "+ case OLD." + MessageColumns.FLAG_READ +
562                " when 0 then -1 else 1 end" +
563                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
564                "; end");
565
566        // Add triggers to update message count per mailbox
567
568        // Insert a message.
569        db.execSQL("create trigger message_count_message_insert after insert on " +
570                Message.TABLE_NAME +
571                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
572                '=' + MailboxColumns.MESSAGE_COUNT + "+1" +
573                "  where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
574                "; end");
575
576        // Delete a message; if flagRead is zero, decrement the unread count of the msg's mailbox
577        db.execSQL("create trigger message_count_message_delete after delete on " +
578                Message.TABLE_NAME +
579                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
580                '=' + MailboxColumns.MESSAGE_COUNT + "-1" +
581                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
582                "; end");
583
584        // Change a message's mailbox
585        db.execSQL("create trigger message_count_message_move after update of " +
586                MessageColumns.MAILBOX_KEY + " on " + Message.TABLE_NAME +
587                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
588                '=' + MailboxColumns.MESSAGE_COUNT + "-1" +
589                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
590                "; update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
591                '=' + MailboxColumns.MESSAGE_COUNT + "+1" +
592                " where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
593                "; end");
594    }
595
596    static void resetMessageTable(SQLiteDatabase db, int oldVersion, int newVersion) {
597        try {
598            db.execSQL("drop table " + Message.TABLE_NAME);
599            db.execSQL("drop table " + Message.UPDATED_TABLE_NAME);
600            db.execSQL("drop table " + Message.DELETED_TABLE_NAME);
601        } catch (SQLException e) {
602        }
603        createMessageTable(db);
604    }
605
606    @SuppressWarnings("deprecation")
607    static void createAccountTable(SQLiteDatabase db) {
608        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
609            + AccountColumns.DISPLAY_NAME + " text, "
610            + AccountColumns.EMAIL_ADDRESS + " text, "
611            + AccountColumns.SYNC_KEY + " text, "
612            + AccountColumns.SYNC_LOOKBACK + " integer, "
613            + AccountColumns.SYNC_INTERVAL + " text, "
614            + AccountColumns.HOST_AUTH_KEY_RECV + " integer, "
615            + AccountColumns.HOST_AUTH_KEY_SEND + " integer, "
616            + AccountColumns.FLAGS + " integer, "
617            + AccountColumns.IS_DEFAULT + " integer, "
618            + AccountColumns.COMPATIBILITY_UUID + " text, "
619            + AccountColumns.SENDER_NAME + " text, "
620            + AccountColumns.RINGTONE_URI + " text, "
621            + AccountColumns.PROTOCOL_VERSION + " text, "
622            + AccountColumns.NEW_MESSAGE_COUNT + " integer, "
623            + AccountColumns.SECURITY_FLAGS + " integer, "
624            + AccountColumns.SECURITY_SYNC_KEY + " text, "
625            + AccountColumns.SIGNATURE + " text, "
626            + AccountColumns.POLICY_KEY + " integer, "
627            + AccountColumns.NOTIFIED_MESSAGE_ID + " integer, "
628            + AccountColumns.NOTIFIED_MESSAGE_COUNT + " integer"
629            + ");";
630        db.execSQL("create table " + Account.TABLE_NAME + s);
631        // Deleting an account deletes associated Mailboxes and HostAuth's
632        db.execSQL(TRIGGER_ACCOUNT_DELETE);
633    }
634
635    static void resetAccountTable(SQLiteDatabase db, int oldVersion, int newVersion) {
636        try {
637            db.execSQL("drop table " +  Account.TABLE_NAME);
638        } catch (SQLException e) {
639        }
640        createAccountTable(db);
641    }
642
643    static void createPolicyTable(SQLiteDatabase db) {
644        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
645            + PolicyColumns.PASSWORD_MODE + " integer, "
646            + PolicyColumns.PASSWORD_MIN_LENGTH + " integer, "
647            + PolicyColumns.PASSWORD_EXPIRATION_DAYS + " integer, "
648            + PolicyColumns.PASSWORD_HISTORY + " integer, "
649            + PolicyColumns.PASSWORD_COMPLEX_CHARS + " integer, "
650            + PolicyColumns.PASSWORD_MAX_FAILS + " integer, "
651            + PolicyColumns.MAX_SCREEN_LOCK_TIME + " integer, "
652            + PolicyColumns.REQUIRE_REMOTE_WIPE + " integer, "
653            + PolicyColumns.REQUIRE_ENCRYPTION + " integer, "
654            + PolicyColumns.REQUIRE_ENCRYPTION_EXTERNAL + " integer, "
655            + PolicyColumns.REQUIRE_MANUAL_SYNC_WHEN_ROAMING + " integer, "
656            + PolicyColumns.DONT_ALLOW_CAMERA + " integer, "
657            + PolicyColumns.DONT_ALLOW_ATTACHMENTS + " integer, "
658            + PolicyColumns.DONT_ALLOW_HTML + " integer, "
659            + PolicyColumns.MAX_ATTACHMENT_SIZE + " integer, "
660            + PolicyColumns.MAX_TEXT_TRUNCATION_SIZE + " integer, "
661            + PolicyColumns.MAX_HTML_TRUNCATION_SIZE + " integer, "
662            + PolicyColumns.MAX_EMAIL_LOOKBACK + " integer, "
663            + PolicyColumns.MAX_CALENDAR_LOOKBACK + " integer, "
664            + PolicyColumns.PASSWORD_RECOVERY_ENABLED + " integer, "
665            + PolicyColumns.PROTOCOL_POLICIES_ENFORCED + " text, "
666            + PolicyColumns.PROTOCOL_POLICIES_UNSUPPORTED + " text"
667            + ");";
668        db.execSQL("create table " + Policy.TABLE_NAME + s);
669    }
670
671    static void createHostAuthTable(SQLiteDatabase db) {
672        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
673            + HostAuthColumns.PROTOCOL + " text, "
674            + HostAuthColumns.ADDRESS + " text, "
675            + HostAuthColumns.PORT + " integer, "
676            + HostAuthColumns.FLAGS + " integer, "
677            + HostAuthColumns.LOGIN + " text, "
678            + HostAuthColumns.PASSWORD + " text, "
679            + HostAuthColumns.DOMAIN + " text, "
680            + HostAuthColumns.ACCOUNT_KEY + " integer,"
681            + HostAuthColumns.CLIENT_CERT_ALIAS + " text"
682            + ");";
683        db.execSQL("create table " + HostAuth.TABLE_NAME + s);
684    }
685
686    static void resetHostAuthTable(SQLiteDatabase db, int oldVersion, int newVersion) {
687        try {
688            db.execSQL("drop table " + HostAuth.TABLE_NAME);
689        } catch (SQLException e) {
690        }
691        createHostAuthTable(db);
692    }
693
694    static void createMailboxTable(SQLiteDatabase db) {
695        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
696            + MailboxColumns.DISPLAY_NAME + " text, "
697            + MailboxColumns.SERVER_ID + " text, "
698            + MailboxColumns.PARENT_SERVER_ID + " text, "
699            + MailboxColumns.PARENT_KEY + " integer, "
700            + MailboxColumns.ACCOUNT_KEY + " integer, "
701            + MailboxColumns.TYPE + " integer, "
702            + MailboxColumns.DELIMITER + " integer, "
703            + MailboxColumns.SYNC_KEY + " text, "
704            + MailboxColumns.SYNC_LOOKBACK + " integer, "
705            + MailboxColumns.SYNC_INTERVAL + " integer, "
706            + MailboxColumns.SYNC_TIME + " integer, "
707            + MailboxColumns.UNREAD_COUNT + " integer, "
708            + MailboxColumns.FLAG_VISIBLE + " integer, "
709            + MailboxColumns.FLAGS + " integer, "
710            + MailboxColumns.VISIBLE_LIMIT + " integer, "
711            + MailboxColumns.SYNC_STATUS + " text, "
712            + MailboxColumns.MESSAGE_COUNT + " integer not null default 0, "
713            + MailboxColumns.LAST_SEEN_MESSAGE_KEY + " integer, "
714            + MailboxColumns.LAST_TOUCHED_TIME + " integer default 0"
715            + ");";
716        db.execSQL("create table " + Mailbox.TABLE_NAME + s);
717        db.execSQL("create index mailbox_" + MailboxColumns.SERVER_ID
718                + " on " + Mailbox.TABLE_NAME + " (" + MailboxColumns.SERVER_ID + ")");
719        db.execSQL("create index mailbox_" + MailboxColumns.ACCOUNT_KEY
720                + " on " + Mailbox.TABLE_NAME + " (" + MailboxColumns.ACCOUNT_KEY + ")");
721        // Deleting a Mailbox deletes associated Messages in all three tables
722        db.execSQL(TRIGGER_MAILBOX_DELETE);
723    }
724
725    static void resetMailboxTable(SQLiteDatabase db, int oldVersion, int newVersion) {
726        try {
727            db.execSQL("drop table " + Mailbox.TABLE_NAME);
728        } catch (SQLException e) {
729        }
730        createMailboxTable(db);
731    }
732
733    static void createAttachmentTable(SQLiteDatabase db) {
734        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
735            + AttachmentColumns.FILENAME + " text, "
736            + AttachmentColumns.MIME_TYPE + " text, "
737            + AttachmentColumns.SIZE + " integer, "
738            + AttachmentColumns.CONTENT_ID + " text, "
739            + AttachmentColumns.CONTENT_URI + " text, "
740            + AttachmentColumns.MESSAGE_KEY + " integer, "
741            + AttachmentColumns.LOCATION + " text, "
742            + AttachmentColumns.ENCODING + " text, "
743            + AttachmentColumns.CONTENT + " text, "
744            + AttachmentColumns.FLAGS + " integer, "
745            + AttachmentColumns.CONTENT_BYTES + " blob, "
746            + AttachmentColumns.ACCOUNT_KEY + " integer"
747            + ");";
748        db.execSQL("create table " + Attachment.TABLE_NAME + s);
749        db.execSQL(createIndex(Attachment.TABLE_NAME, AttachmentColumns.MESSAGE_KEY));
750    }
751
752    static void resetAttachmentTable(SQLiteDatabase db, int oldVersion, int newVersion) {
753        try {
754            db.execSQL("drop table " + Attachment.TABLE_NAME);
755        } catch (SQLException e) {
756        }
757        createAttachmentTable(db);
758    }
759
760    static void createQuickResponseTable(SQLiteDatabase db) {
761        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
762                + QuickResponseColumns.TEXT + " text, "
763                + QuickResponseColumns.ACCOUNT_KEY + " integer"
764                + ");";
765        db.execSQL("create table " + QuickResponse.TABLE_NAME + s);
766    }
767
768    static void createBodyTable(SQLiteDatabase db) {
769        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
770            + BodyColumns.MESSAGE_KEY + " integer, "
771            + BodyColumns.HTML_CONTENT + " text, "
772            + BodyColumns.TEXT_CONTENT + " text, "
773            + BodyColumns.HTML_REPLY + " text, "
774            + BodyColumns.TEXT_REPLY + " text, "
775            + BodyColumns.SOURCE_MESSAGE_KEY + " text, "
776            + BodyColumns.INTRO_TEXT + " text"
777            + ");";
778        db.execSQL("create table " + Body.TABLE_NAME + s);
779        db.execSQL(createIndex(Body.TABLE_NAME, BodyColumns.MESSAGE_KEY));
780    }
781
782    static void upgradeBodyTable(SQLiteDatabase db, int oldVersion, int newVersion) {
783        if (oldVersion < 5) {
784            try {
785                db.execSQL("drop table " + Body.TABLE_NAME);
786                createBodyTable(db);
787            } catch (SQLException e) {
788            }
789        } else if (oldVersion == 5) {
790            try {
791                db.execSQL("alter table " + Body.TABLE_NAME
792                        + " add " + BodyColumns.INTRO_TEXT + " text");
793            } catch (SQLException e) {
794                // Shouldn't be needed unless we're debugging and interrupt the process
795                Log.w(TAG, "Exception upgrading EmailProviderBody.db from v5 to v6", e);
796            }
797            oldVersion = 6;
798        }
799    }
800
801    private SQLiteDatabase mDatabase;
802    private SQLiteDatabase mBodyDatabase;
803
804    /**
805     * Orphan record deletion utility.  Generates a sqlite statement like:
806     *  delete from <table> where <column> not in (select <foreignColumn> from <foreignTable>)
807     * @param db the EmailProvider database
808     * @param table the table whose orphans are to be removed
809     * @param column the column deletion will be based on
810     * @param foreignColumn the column in the foreign table whose absence will trigger the deletion
811     * @param foreignTable the foreign table
812     */
813    @VisibleForTesting
814    void deleteUnlinked(SQLiteDatabase db, String table, String column, String foreignColumn,
815            String foreignTable) {
816        int count = db.delete(table, column + " not in (select " + foreignColumn + " from " +
817                foreignTable + ")", null);
818        if (count > 0) {
819            Log.w(TAG, "Found " + count + " orphaned row(s) in " + table);
820        }
821    }
822
823    @VisibleForTesting
824    synchronized SQLiteDatabase getDatabase(Context context) {
825        // Always return the cached database, if we've got one
826        if (mDatabase != null) {
827            return mDatabase;
828        }
829
830        // Whenever we create or re-cache the databases, make sure that we haven't lost one
831        // to corruption
832        checkDatabases();
833
834        DatabaseHelper helper = new DatabaseHelper(context, DATABASE_NAME);
835        mDatabase = helper.getWritableDatabase();
836        mDatabase.setLockingEnabled(true);
837        BodyDatabaseHelper bodyHelper = new BodyDatabaseHelper(context, BODY_DATABASE_NAME);
838        mBodyDatabase = bodyHelper.getWritableDatabase();
839        if (mBodyDatabase != null) {
840            mBodyDatabase.setLockingEnabled(true);
841            String bodyFileName = mBodyDatabase.getPath();
842            mDatabase.execSQL("attach \"" + bodyFileName + "\" as BodyDatabase");
843        }
844
845        // Restore accounts if the database is corrupted...
846        restoreIfNeeded(context, mDatabase);
847
848        if (Email.DEBUG) {
849            Log.d(TAG, "Deleting orphans...");
850        }
851        // Check for any orphaned Messages in the updated/deleted tables
852        deleteMessageOrphans(mDatabase, Message.UPDATED_TABLE_NAME);
853        deleteMessageOrphans(mDatabase, Message.DELETED_TABLE_NAME);
854        // Delete orphaned mailboxes/messages/policies (account no longer exists)
855        deleteUnlinked(mDatabase, Mailbox.TABLE_NAME, MailboxColumns.ACCOUNT_KEY, AccountColumns.ID,
856                Account.TABLE_NAME);
857        deleteUnlinked(mDatabase, Message.TABLE_NAME, MessageColumns.ACCOUNT_KEY, AccountColumns.ID,
858                Account.TABLE_NAME);
859        deleteUnlinked(mDatabase, Policy.TABLE_NAME, PolicyColumns.ID, AccountColumns.POLICY_KEY,
860                Account.TABLE_NAME);
861
862        if (Email.DEBUG) {
863            Log.d(TAG, "EmailProvider pre-caching...");
864        }
865        preCacheData();
866        if (Email.DEBUG) {
867            Log.d(TAG, "EmailProvider ready.");
868        }
869        return mDatabase;
870    }
871
872    /**
873     * Pre-cache all of the items in a given table meeting the selection criteria
874     * @param tableUri the table uri
875     * @param baseProjection the base projection of that table
876     * @param selection the selection criteria
877     */
878    private void preCacheTable(Uri tableUri, String[] baseProjection, String selection) {
879        Cursor c = query(tableUri, EmailContent.ID_PROJECTION, selection, null, null);
880        try {
881            while (c.moveToNext()) {
882                long id = c.getLong(EmailContent.ID_PROJECTION_COLUMN);
883                Cursor cachedCursor = query(ContentUris.withAppendedId(
884                        tableUri, id), baseProjection, null, null, null);
885                if (cachedCursor != null) {
886                    // For accounts, create a mailbox type map entry (if necessary)
887                    if (tableUri == Account.CONTENT_URI) {
888                        getOrCreateAccountMailboxTypeMap(id);
889                    }
890                    cachedCursor.close();
891                }
892            }
893        } finally {
894            c.close();
895        }
896    }
897
898    private final HashMap<Long, HashMap<Integer, Long>> mMailboxTypeMap =
899        new HashMap<Long, HashMap<Integer, Long>>();
900
901    private HashMap<Integer, Long> getOrCreateAccountMailboxTypeMap(long accountId) {
902        synchronized(mMailboxTypeMap) {
903            HashMap<Integer, Long> accountMailboxTypeMap = mMailboxTypeMap.get(accountId);
904            if (accountMailboxTypeMap == null) {
905                accountMailboxTypeMap = new HashMap<Integer, Long>();
906                mMailboxTypeMap.put(accountId, accountMailboxTypeMap);
907            }
908            return accountMailboxTypeMap;
909        }
910    }
911
912    private void addToMailboxTypeMap(Cursor c) {
913        long accountId = c.getLong(Mailbox.CONTENT_ACCOUNT_KEY_COLUMN);
914        int type = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
915        synchronized(mMailboxTypeMap) {
916            HashMap<Integer, Long> accountMailboxTypeMap =
917                getOrCreateAccountMailboxTypeMap(accountId);
918            accountMailboxTypeMap.put(type, c.getLong(Mailbox.CONTENT_ID_COLUMN));
919        }
920    }
921
922    private long getMailboxIdFromMailboxTypeMap(long accountId, int type) {
923        synchronized(mMailboxTypeMap) {
924            HashMap<Integer, Long> accountMap = mMailboxTypeMap.get(accountId);
925            Long mailboxId = null;
926            if (accountMap != null) {
927                mailboxId = accountMap.get(type);
928            }
929            if (mailboxId == null) return Mailbox.NO_MAILBOX;
930            return mailboxId;
931        }
932    }
933
934    private void preCacheData() {
935        synchronized(mMailboxTypeMap) {
936            mMailboxTypeMap.clear();
937
938            // Pre-cache accounts, host auth's, policies, and special mailboxes
939            preCacheTable(Account.CONTENT_URI, Account.CONTENT_PROJECTION, null);
940            preCacheTable(HostAuth.CONTENT_URI, HostAuth.CONTENT_PROJECTION, null);
941            preCacheTable(Policy.CONTENT_URI, Policy.CONTENT_PROJECTION, null);
942            preCacheTable(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
943                    MAILBOX_PRE_CACHE_SELECTION);
944
945            // Create a map from account,type to a mailbox
946            Map<String, Cursor> snapshot = mCacheMailbox.getSnapshot();
947            Collection<Cursor> values = snapshot.values();
948            if (values != null) {
949                for (Cursor c: values) {
950                    if (c.moveToFirst()) {
951                        addToMailboxTypeMap(c);
952                    }
953                }
954            }
955        }
956    }
957
958    /*package*/ static SQLiteDatabase getReadableDatabase(Context context) {
959        DatabaseHelper helper = new DatabaseHelper(context, DATABASE_NAME);
960        return helper.getReadableDatabase();
961    }
962
963    /**
964     * Restore user Account and HostAuth data from our backup database
965     */
966    public static void restoreIfNeeded(Context context, SQLiteDatabase mainDatabase) {
967        if (Email.DEBUG) {
968            Log.w(TAG, "restoreIfNeeded...");
969        }
970        // Check for legacy backup
971        String legacyBackup = Preferences.getLegacyBackupPreference(context);
972        // If there's a legacy backup, create a new-style backup and delete the legacy backup
973        // In the 1:1000000000 chance that the user gets an app update just as his database becomes
974        // corrupt, oh well...
975        if (!TextUtils.isEmpty(legacyBackup)) {
976            backupAccounts(context, mainDatabase);
977            Preferences.clearLegacyBackupPreference(context);
978            Log.w(TAG, "Created new EmailProvider backup database");
979            return;
980        }
981
982        // If we have accounts, we're done
983        Cursor c = mainDatabase.query(Account.TABLE_NAME, EmailContent.ID_PROJECTION, null, null,
984                null, null, null);
985        if (c.moveToFirst()) {
986            if (Email.DEBUG) {
987                Log.w(TAG, "restoreIfNeeded: Account exists.");
988            }
989            return; // At least one account exists.
990        }
991        restoreAccounts(context, mainDatabase);
992    }
993
994    /** {@inheritDoc} */
995    @Override
996    public void shutdown() {
997        if (mDatabase != null) {
998            mDatabase.close();
999            mDatabase = null;
1000        }
1001        if (mBodyDatabase != null) {
1002            mBodyDatabase.close();
1003            mBodyDatabase = null;
1004        }
1005    }
1006
1007    /*package*/ static void deleteMessageOrphans(SQLiteDatabase database, String tableName) {
1008        if (database != null) {
1009            // We'll look at all of the items in the table; there won't be many typically
1010            Cursor c = database.query(tableName, ORPHANS_PROJECTION, null, null, null, null, null);
1011            // Usually, there will be nothing in these tables, so make a quick check
1012            try {
1013                if (c.getCount() == 0) return;
1014                ArrayList<Long> foundMailboxes = new ArrayList<Long>();
1015                ArrayList<Long> notFoundMailboxes = new ArrayList<Long>();
1016                ArrayList<Long> deleteList = new ArrayList<Long>();
1017                String[] bindArray = new String[1];
1018                while (c.moveToNext()) {
1019                    // Get the mailbox key and see if we've already found this mailbox
1020                    // If so, we're fine
1021                    long mailboxId = c.getLong(ORPHANS_MAILBOX_KEY);
1022                    // If we already know this mailbox doesn't exist, mark the message for deletion
1023                    if (notFoundMailboxes.contains(mailboxId)) {
1024                        deleteList.add(c.getLong(ORPHANS_ID));
1025                    // If we don't know about this mailbox, we'll try to find it
1026                    } else if (!foundMailboxes.contains(mailboxId)) {
1027                        bindArray[0] = Long.toString(mailboxId);
1028                        Cursor boxCursor = database.query(Mailbox.TABLE_NAME,
1029                                Mailbox.ID_PROJECTION, WHERE_ID, bindArray, null, null, null);
1030                        try {
1031                            // If it exists, we'll add it to the "found" mailboxes
1032                            if (boxCursor.moveToFirst()) {
1033                                foundMailboxes.add(mailboxId);
1034                            // Otherwise, we'll add to "not found" and mark the message for deletion
1035                            } else {
1036                                notFoundMailboxes.add(mailboxId);
1037                                deleteList.add(c.getLong(ORPHANS_ID));
1038                            }
1039                        } finally {
1040                            boxCursor.close();
1041                        }
1042                    }
1043                }
1044                // Now, delete the orphan messages
1045                for (long messageId: deleteList) {
1046                    bindArray[0] = Long.toString(messageId);
1047                    database.delete(tableName, WHERE_ID, bindArray);
1048                }
1049            } finally {
1050                c.close();
1051            }
1052        }
1053    }
1054
1055    private class BodyDatabaseHelper extends SQLiteOpenHelper {
1056        BodyDatabaseHelper(Context context, String name) {
1057            super(context, name, null, BODY_DATABASE_VERSION);
1058        }
1059
1060        @Override
1061        public void onCreate(SQLiteDatabase db) {
1062            Log.d(TAG, "Creating EmailProviderBody database");
1063            createBodyTable(db);
1064        }
1065
1066        @Override
1067        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
1068            upgradeBodyTable(db, oldVersion, newVersion);
1069        }
1070
1071        @Override
1072        public void onOpen(SQLiteDatabase db) {
1073        }
1074    }
1075
1076    private static class DatabaseHelper extends SQLiteOpenHelper {
1077        Context mContext;
1078
1079        DatabaseHelper(Context context, String name) {
1080            super(context, name, null, DATABASE_VERSION);
1081            mContext = context;
1082        }
1083
1084        @Override
1085        public void onCreate(SQLiteDatabase db) {
1086            Log.d(TAG, "Creating EmailProvider database");
1087            // Create all tables here; each class has its own method
1088            createMessageTable(db);
1089            createAttachmentTable(db);
1090            createMailboxTable(db);
1091            createHostAuthTable(db);
1092            createAccountTable(db);
1093            createPolicyTable(db);
1094            createQuickResponseTable(db);
1095        }
1096
1097        @Override
1098        @SuppressWarnings("deprecation")
1099        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
1100            // For versions prior to 5, delete all data
1101            // Versions >= 5 require that data be preserved!
1102            if (oldVersion < 5) {
1103                android.accounts.Account[] accounts = AccountManager.get(mContext)
1104                        .getAccountsByType(AccountManagerTypes.TYPE_EXCHANGE);
1105                for (android.accounts.Account account: accounts) {
1106                    AccountManager.get(mContext).removeAccount(account, null, null);
1107                }
1108                resetMessageTable(db, oldVersion, newVersion);
1109                resetAttachmentTable(db, oldVersion, newVersion);
1110                resetMailboxTable(db, oldVersion, newVersion);
1111                resetHostAuthTable(db, oldVersion, newVersion);
1112                resetAccountTable(db, oldVersion, newVersion);
1113                return;
1114            }
1115            if (oldVersion == 5) {
1116                // Message Tables: Add SyncColumns.SERVER_TIMESTAMP
1117                try {
1118                    db.execSQL("alter table " + Message.TABLE_NAME
1119                            + " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
1120                    db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
1121                            + " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
1122                    db.execSQL("alter table " + Message.DELETED_TABLE_NAME
1123                            + " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
1124                } catch (SQLException e) {
1125                    // Shouldn't be needed unless we're debugging and interrupt the process
1126                    Log.w(TAG, "Exception upgrading EmailProvider.db from v5 to v6", e);
1127                }
1128                oldVersion = 6;
1129            }
1130            if (oldVersion == 6) {
1131                // Use the newer mailbox_delete trigger
1132                db.execSQL("drop trigger mailbox_delete;");
1133                db.execSQL(TRIGGER_MAILBOX_DELETE);
1134                oldVersion = 7;
1135            }
1136            if (oldVersion == 7) {
1137                // add the security (provisioning) column
1138                try {
1139                    db.execSQL("alter table " + Account.TABLE_NAME
1140                            + " add column " + AccountColumns.SECURITY_FLAGS + " integer" + ";");
1141                } catch (SQLException e) {
1142                    // Shouldn't be needed unless we're debugging and interrupt the process
1143                    Log.w(TAG, "Exception upgrading EmailProvider.db from 7 to 8 " + e);
1144                }
1145                oldVersion = 8;
1146            }
1147            if (oldVersion == 8) {
1148                // accounts: add security sync key & user signature columns
1149                try {
1150                    db.execSQL("alter table " + Account.TABLE_NAME
1151                            + " add column " + AccountColumns.SECURITY_SYNC_KEY + " text" + ";");
1152                    db.execSQL("alter table " + Account.TABLE_NAME
1153                            + " add column " + AccountColumns.SIGNATURE + " text" + ";");
1154                } catch (SQLException e) {
1155                    // Shouldn't be needed unless we're debugging and interrupt the process
1156                    Log.w(TAG, "Exception upgrading EmailProvider.db from 8 to 9 " + e);
1157                }
1158                oldVersion = 9;
1159            }
1160            if (oldVersion == 9) {
1161                // Message: add meeting info column into Message tables
1162                try {
1163                    db.execSQL("alter table " + Message.TABLE_NAME
1164                            + " add column " + MessageColumns.MEETING_INFO + " text" + ";");
1165                    db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
1166                            + " add column " + MessageColumns.MEETING_INFO + " text" + ";");
1167                    db.execSQL("alter table " + Message.DELETED_TABLE_NAME
1168                            + " add column " + MessageColumns.MEETING_INFO + " text" + ";");
1169                } catch (SQLException e) {
1170                    // Shouldn't be needed unless we're debugging and interrupt the process
1171                    Log.w(TAG, "Exception upgrading EmailProvider.db from 9 to 10 " + e);
1172                }
1173                oldVersion = 10;
1174            }
1175            if (oldVersion == 10) {
1176                // Attachment: add content and flags columns
1177                try {
1178                    db.execSQL("alter table " + Attachment.TABLE_NAME
1179                            + " add column " + AttachmentColumns.CONTENT + " text" + ";");
1180                    db.execSQL("alter table " + Attachment.TABLE_NAME
1181                            + " add column " + AttachmentColumns.FLAGS + " integer" + ";");
1182                } catch (SQLException e) {
1183                    // Shouldn't be needed unless we're debugging and interrupt the process
1184                    Log.w(TAG, "Exception upgrading EmailProvider.db from 10 to 11 " + e);
1185                }
1186                oldVersion = 11;
1187            }
1188            if (oldVersion == 11) {
1189                // Attachment: add content_bytes
1190                try {
1191                    db.execSQL("alter table " + Attachment.TABLE_NAME
1192                            + " add column " + AttachmentColumns.CONTENT_BYTES + " blob" + ";");
1193                } catch (SQLException e) {
1194                    // Shouldn't be needed unless we're debugging and interrupt the process
1195                    Log.w(TAG, "Exception upgrading EmailProvider.db from 11 to 12 " + e);
1196                }
1197                oldVersion = 12;
1198            }
1199            if (oldVersion == 12) {
1200                try {
1201                    db.execSQL("alter table " + Mailbox.TABLE_NAME
1202                            + " add column " + Mailbox.MESSAGE_COUNT
1203                                    +" integer not null default 0" + ";");
1204                    recalculateMessageCount(db);
1205                } catch (SQLException e) {
1206                    // Shouldn't be needed unless we're debugging and interrupt the process
1207                    Log.w(TAG, "Exception upgrading EmailProvider.db from 12 to 13 " + e);
1208                }
1209                oldVersion = 13;
1210            }
1211            if (oldVersion == 13) {
1212                try {
1213                    db.execSQL("alter table " + Message.TABLE_NAME
1214                            + " add column " + Message.SNIPPET
1215                                    +" text" + ";");
1216                } catch (SQLException e) {
1217                    // Shouldn't be needed unless we're debugging and interrupt the process
1218                    Log.w(TAG, "Exception upgrading EmailProvider.db from 13 to 14 " + e);
1219                }
1220                oldVersion = 14;
1221            }
1222            if (oldVersion == 14) {
1223                try {
1224                    db.execSQL("alter table " + Message.DELETED_TABLE_NAME
1225                            + " add column " + Message.SNIPPET +" text" + ";");
1226                    db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
1227                            + " add column " + Message.SNIPPET +" text" + ";");
1228                } catch (SQLException e) {
1229                    // Shouldn't be needed unless we're debugging and interrupt the process
1230                    Log.w(TAG, "Exception upgrading EmailProvider.db from 14 to 15 " + e);
1231                }
1232                oldVersion = 15;
1233            }
1234            if (oldVersion == 15) {
1235                try {
1236                    db.execSQL("alter table " + Attachment.TABLE_NAME
1237                            + " add column " + Attachment.ACCOUNT_KEY +" integer" + ";");
1238                    // Update all existing attachments to add the accountKey data
1239                    db.execSQL("update " + Attachment.TABLE_NAME + " set " +
1240                            Attachment.ACCOUNT_KEY + "= (SELECT " + Message.TABLE_NAME + "." +
1241                            Message.ACCOUNT_KEY + " from " + Message.TABLE_NAME + " where " +
1242                            Message.TABLE_NAME + "." + Message.RECORD_ID + " = " +
1243                            Attachment.TABLE_NAME + "." + Attachment.MESSAGE_KEY + ")");
1244                } catch (SQLException e) {
1245                    // Shouldn't be needed unless we're debugging and interrupt the process
1246                    Log.w(TAG, "Exception upgrading EmailProvider.db from 15 to 16 " + e);
1247                }
1248                oldVersion = 16;
1249            }
1250            if (oldVersion == 16) {
1251                try {
1252                    db.execSQL("alter table " + Mailbox.TABLE_NAME
1253                            + " add column " + Mailbox.PARENT_KEY + " integer;");
1254                } catch (SQLException e) {
1255                    // Shouldn't be needed unless we're debugging and interrupt the process
1256                    Log.w(TAG, "Exception upgrading EmailProvider.db from 16 to 17 " + e);
1257                }
1258                oldVersion = 17;
1259            }
1260            if (oldVersion == 17) {
1261                upgradeFromVersion17ToVersion18(db);
1262                oldVersion = 18;
1263            }
1264            if (oldVersion == 18) {
1265                try {
1266                    db.execSQL("alter table " + Account.TABLE_NAME
1267                            + " add column " + Account.POLICY_KEY + " integer;");
1268                    db.execSQL("drop trigger account_delete;");
1269                    db.execSQL(TRIGGER_ACCOUNT_DELETE);
1270                    createPolicyTable(db);
1271                    convertPolicyFlagsToPolicyTable(db);
1272                } catch (SQLException e) {
1273                    // Shouldn't be needed unless we're debugging and interrupt the process
1274                    Log.w(TAG, "Exception upgrading EmailProvider.db from 18 to 19 " + e);
1275                }
1276                oldVersion = 19;
1277            }
1278            if (oldVersion == 19) {
1279                try {
1280                    db.execSQL("alter table " + Policy.TABLE_NAME
1281                            + " add column " + PolicyColumns.REQUIRE_MANUAL_SYNC_WHEN_ROAMING +
1282                            " integer;");
1283                    db.execSQL("alter table " + Policy.TABLE_NAME
1284                            + " add column " + PolicyColumns.DONT_ALLOW_CAMERA + " integer;");
1285                    db.execSQL("alter table " + Policy.TABLE_NAME
1286                            + " add column " + PolicyColumns.DONT_ALLOW_ATTACHMENTS + " integer;");
1287                    db.execSQL("alter table " + Policy.TABLE_NAME
1288                            + " add column " + PolicyColumns.DONT_ALLOW_HTML + " integer;");
1289                    db.execSQL("alter table " + Policy.TABLE_NAME
1290                            + " add column " + PolicyColumns.MAX_ATTACHMENT_SIZE + " integer;");
1291                    db.execSQL("alter table " + Policy.TABLE_NAME
1292                            + " add column " + PolicyColumns.MAX_TEXT_TRUNCATION_SIZE +
1293                            " integer;");
1294                    db.execSQL("alter table " + Policy.TABLE_NAME
1295                            + " add column " + PolicyColumns.MAX_HTML_TRUNCATION_SIZE +
1296                            " integer;");
1297                    db.execSQL("alter table " + Policy.TABLE_NAME
1298                            + " add column " + PolicyColumns.MAX_EMAIL_LOOKBACK + " integer;");
1299                    db.execSQL("alter table " + Policy.TABLE_NAME
1300                            + " add column " + PolicyColumns.MAX_CALENDAR_LOOKBACK + " integer;");
1301                    db.execSQL("alter table " + Policy.TABLE_NAME
1302                            + " add column " + PolicyColumns.PASSWORD_RECOVERY_ENABLED +
1303                            " integer;");
1304                } catch (SQLException e) {
1305                    // Shouldn't be needed unless we're debugging and interrupt the process
1306                    Log.w(TAG, "Exception upgrading EmailProvider.db from 19 to 20 " + e);
1307                }
1308                oldVersion = 20;
1309            }
1310            if (oldVersion == 20) {
1311                upgradeFromVersion20ToVersion21(db);
1312                oldVersion = 21;
1313            }
1314            if (oldVersion == 21) {
1315                upgradeFromVersion21ToVersion22(db, mContext);
1316                oldVersion = 22;
1317            }
1318            if (oldVersion == 22) {
1319                upgradeFromVersion22ToVersion23(db);
1320                oldVersion = 23;
1321            }
1322            if (oldVersion == 23) {
1323                upgradeFromVersion23ToVersion24(db);
1324                oldVersion = 24;
1325            }
1326            if (oldVersion == 24) {
1327                upgradeFromVersion24ToVersion25(db);
1328                oldVersion = 25;
1329            }
1330            if (oldVersion == 25) {
1331                upgradeFromVersion25ToVersion26(db);
1332                oldVersion = 26;
1333            }
1334            if (oldVersion == 26) {
1335                try {
1336                    db.execSQL("alter table " + Message.TABLE_NAME
1337                            + " add column " + Message.PROTOCOL_SEARCH_INFO + " text;");
1338                    db.execSQL("alter table " + Message.DELETED_TABLE_NAME
1339                            + " add column " + Message.PROTOCOL_SEARCH_INFO +" text" + ";");
1340                    db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
1341                            + " add column " + Message.PROTOCOL_SEARCH_INFO +" text" + ";");
1342                } catch (SQLException e) {
1343                    // Shouldn't be needed unless we're debugging and interrupt the process
1344                    Log.w(TAG, "Exception upgrading EmailProvider.db from 26 to 27 " + e);
1345                }
1346                oldVersion = 27;
1347            }
1348            if (oldVersion == 27) {
1349                try {
1350                    db.execSQL("alter table " + Account.TABLE_NAME
1351                            + " add column " + Account.NOTIFIED_MESSAGE_ID + " integer;");
1352                    db.execSQL("alter table " + Account.TABLE_NAME
1353                            + " add column " + Account.NOTIFIED_MESSAGE_COUNT + " integer;");
1354                } catch (SQLException e) {
1355                    // Shouldn't be needed unless we're debugging and interrupt the process
1356                    Log.w(TAG, "Exception upgrading EmailProvider.db from 27 to 28 " + e);
1357                }
1358                oldVersion = 28;
1359            }
1360            if (oldVersion == 28) {
1361                try {
1362                    db.execSQL("alter table " + Policy.TABLE_NAME
1363                            + " add column " + Policy.PROTOCOL_POLICIES_ENFORCED + " text;");
1364                    db.execSQL("alter table " + Policy.TABLE_NAME
1365                            + " add column " + Policy.PROTOCOL_POLICIES_UNSUPPORTED + " text;");
1366                } catch (SQLException e) {
1367                    // Shouldn't be needed unless we're debugging and interrupt the process
1368                    Log.w(TAG, "Exception upgrading EmailProvider.db from 28 to 29 " + e);
1369                }
1370                oldVersion = 29;
1371            }
1372        }
1373
1374        @Override
1375        public void onOpen(SQLiteDatabase db) {
1376        }
1377    }
1378
1379    @Override
1380    public int delete(Uri uri, String selection, String[] selectionArgs) {
1381        final int match = findMatch(uri, "delete");
1382        Context context = getContext();
1383        // Pick the correct database for this operation
1384        // If we're in a transaction already (which would happen during applyBatch), then the
1385        // body database is already attached to the email database and any attempt to use the
1386        // body database directly will result in a SQLiteException (the database is locked)
1387        SQLiteDatabase db = getDatabase(context);
1388        int table = match >> BASE_SHIFT;
1389        String id = "0";
1390        boolean messageDeletion = false;
1391        ContentResolver resolver = context.getContentResolver();
1392
1393        ContentCache cache = mContentCaches[table];
1394        String tableName = TABLE_NAMES[table];
1395        int result = -1;
1396
1397        try {
1398            switch (match) {
1399                // These are cases in which one or more Messages might get deleted, either by
1400                // cascade or explicitly
1401                case MAILBOX_ID:
1402                case MAILBOX:
1403                case ACCOUNT_ID:
1404                case ACCOUNT:
1405                case MESSAGE:
1406                case SYNCED_MESSAGE_ID:
1407                case MESSAGE_ID:
1408                    // Handle lost Body records here, since this cannot be done in a trigger
1409                    // The process is:
1410                    //  1) Begin a transaction, ensuring that both databases are affected atomically
1411                    //  2) Do the requested deletion, with cascading deletions handled in triggers
1412                    //  3) End the transaction, committing all changes atomically
1413                    //
1414                    // Bodies are auto-deleted here;  Attachments are auto-deleted via trigger
1415                    messageDeletion = true;
1416                    db.beginTransaction();
1417                    break;
1418            }
1419            switch (match) {
1420                case BODY_ID:
1421                case DELETED_MESSAGE_ID:
1422                case SYNCED_MESSAGE_ID:
1423                case MESSAGE_ID:
1424                case UPDATED_MESSAGE_ID:
1425                case ATTACHMENT_ID:
1426                case MAILBOX_ID:
1427                case ACCOUNT_ID:
1428                case HOSTAUTH_ID:
1429                case POLICY_ID:
1430                case QUICK_RESPONSE_ID:
1431                    id = uri.getPathSegments().get(1);
1432                    if (match == SYNCED_MESSAGE_ID) {
1433                        // For synced messages, first copy the old message to the deleted table and
1434                        // delete it from the updated table (in case it was updated first)
1435                        // Note that this is all within a transaction, for atomicity
1436                        db.execSQL(DELETED_MESSAGE_INSERT + id);
1437                        db.execSQL(UPDATED_MESSAGE_DELETE + id);
1438                    }
1439                    if (cache != null) {
1440                        cache.lock(id);
1441                    }
1442                    try {
1443                        result = db.delete(tableName, whereWithId(id, selection), selectionArgs);
1444                        if (cache != null) {
1445                            switch(match) {
1446                                case ACCOUNT_ID:
1447                                    // Account deletion will clear all of the caches, as HostAuth's,
1448                                    // Mailboxes, and Messages will be deleted in the process
1449                                    mCacheMailbox.invalidate("Delete", uri, selection);
1450                                    mCacheHostAuth.invalidate("Delete", uri, selection);
1451                                    mCachePolicy.invalidate("Delete", uri, selection);
1452                                    //$FALL-THROUGH$
1453                                case MAILBOX_ID:
1454                                    // Mailbox deletion will clear the Message cache
1455                                    mCacheMessage.invalidate("Delete", uri, selection);
1456                                    //$FALL-THROUGH$
1457                                case SYNCED_MESSAGE_ID:
1458                                case MESSAGE_ID:
1459                                case HOSTAUTH_ID:
1460                                case POLICY_ID:
1461                                    cache.invalidate("Delete", uri, selection);
1462                                    // Make sure all data is properly cached
1463                                    if (match != MESSAGE_ID) {
1464                                        preCacheData();
1465                                    }
1466                                    break;
1467                            }
1468                        }
1469                    } finally {
1470                        if (cache != null) {
1471                            cache.unlock(id);
1472                        }
1473                    }
1474                    break;
1475                case ATTACHMENTS_MESSAGE_ID:
1476                    // All attachments for the given message
1477                    id = uri.getPathSegments().get(2);
1478                    result = db.delete(tableName,
1479                            whereWith(Attachment.MESSAGE_KEY + "=" + id, selection), selectionArgs);
1480                    break;
1481
1482                case BODY:
1483                case MESSAGE:
1484                case DELETED_MESSAGE:
1485                case UPDATED_MESSAGE:
1486                case ATTACHMENT:
1487                case MAILBOX:
1488                case ACCOUNT:
1489                case HOSTAUTH:
1490                case POLICY:
1491                    switch(match) {
1492                        // See the comments above for deletion of ACCOUNT_ID, etc
1493                        case ACCOUNT:
1494                            mCacheMailbox.invalidate("Delete", uri, selection);
1495                            mCacheHostAuth.invalidate("Delete", uri, selection);
1496                            mCachePolicy.invalidate("Delete", uri, selection);
1497                            //$FALL-THROUGH$
1498                        case MAILBOX:
1499                            mCacheMessage.invalidate("Delete", uri, selection);
1500                            //$FALL-THROUGH$
1501                        case MESSAGE:
1502                        case HOSTAUTH:
1503                        case POLICY:
1504                            cache.invalidate("Delete", uri, selection);
1505                            break;
1506                    }
1507                    result = db.delete(tableName, selection, selectionArgs);
1508                    switch(match) {
1509                        case ACCOUNT:
1510                        case MAILBOX:
1511                        case HOSTAUTH:
1512                        case POLICY:
1513                            // Make sure all data is properly cached
1514                            preCacheData();
1515                            break;
1516                    }
1517                    break;
1518
1519                default:
1520                    throw new IllegalArgumentException("Unknown URI " + uri);
1521            }
1522            if (messageDeletion) {
1523                if (match == MESSAGE_ID) {
1524                    // Delete the Body record associated with the deleted message
1525                    db.execSQL(DELETE_BODY + id);
1526                } else {
1527                    // Delete any orphaned Body records
1528                    db.execSQL(DELETE_ORPHAN_BODIES);
1529                }
1530                db.setTransactionSuccessful();
1531            }
1532        } catch (SQLiteException e) {
1533            checkDatabases();
1534            throw e;
1535        } finally {
1536            if (messageDeletion) {
1537                db.endTransaction();
1538            }
1539        }
1540
1541        // Notify all notifier cursors
1542        sendNotifierChange(getBaseNotificationUri(match), NOTIFICATION_OP_DELETE, id);
1543
1544        // Notify all email content cursors
1545        resolver.notifyChange(EmailContent.CONTENT_URI, null);
1546        return result;
1547    }
1548
1549    @Override
1550    // Use the email- prefix because message, mailbox, and account are so generic (e.g. SMS, IM)
1551    public String getType(Uri uri) {
1552        int match = findMatch(uri, "getType");
1553        switch (match) {
1554            case BODY_ID:
1555                return "vnd.android.cursor.item/email-body";
1556            case BODY:
1557                return "vnd.android.cursor.dir/email-body";
1558            case UPDATED_MESSAGE_ID:
1559            case MESSAGE_ID:
1560                // NOTE: According to the framework folks, we're supposed to invent mime types as
1561                // a way of passing information to drag & drop recipients.
1562                // If there's a mailboxId parameter in the url, we respond with a mime type that
1563                // has -n appended, where n is the mailboxId of the message.  The drag & drop code
1564                // uses this information to know not to allow dragging the item to its own mailbox
1565                String mimeType = EMAIL_MESSAGE_MIME_TYPE;
1566                String mailboxId = uri.getQueryParameter(MESSAGE_URI_PARAMETER_MAILBOX_ID);
1567                if (mailboxId != null) {
1568                    mimeType += "-" + mailboxId;
1569                }
1570                return mimeType;
1571            case UPDATED_MESSAGE:
1572            case MESSAGE:
1573                return "vnd.android.cursor.dir/email-message";
1574            case MAILBOX:
1575                return "vnd.android.cursor.dir/email-mailbox";
1576            case MAILBOX_ID:
1577                return "vnd.android.cursor.item/email-mailbox";
1578            case ACCOUNT:
1579                return "vnd.android.cursor.dir/email-account";
1580            case ACCOUNT_ID:
1581                return "vnd.android.cursor.item/email-account";
1582            case ATTACHMENTS_MESSAGE_ID:
1583            case ATTACHMENT:
1584                return "vnd.android.cursor.dir/email-attachment";
1585            case ATTACHMENT_ID:
1586                return EMAIL_ATTACHMENT_MIME_TYPE;
1587            case HOSTAUTH:
1588                return "vnd.android.cursor.dir/email-hostauth";
1589            case HOSTAUTH_ID:
1590                return "vnd.android.cursor.item/email-hostauth";
1591            default:
1592                throw new IllegalArgumentException("Unknown URI " + uri);
1593        }
1594    }
1595
1596    @Override
1597    public Uri insert(Uri uri, ContentValues values) {
1598        int match = findMatch(uri, "insert");
1599        Context context = getContext();
1600        ContentResolver resolver = context.getContentResolver();
1601
1602        // See the comment at delete(), above
1603        SQLiteDatabase db = getDatabase(context);
1604        int table = match >> BASE_SHIFT;
1605        String id = "0";
1606        long longId;
1607
1608        // We do NOT allow setting of unreadCount/messageCount via the provider
1609        // These columns are maintained via triggers
1610        if (match == MAILBOX_ID || match == MAILBOX) {
1611            values.put(MailboxColumns.UNREAD_COUNT, 0);
1612            values.put(MailboxColumns.MESSAGE_COUNT, 0);
1613        }
1614
1615        Uri resultUri = null;
1616
1617        try {
1618            switch (match) {
1619                // NOTE: It is NOT legal for production code to insert directly into UPDATED_MESSAGE
1620                // or DELETED_MESSAGE; see the comment below for details
1621                case UPDATED_MESSAGE:
1622                case DELETED_MESSAGE:
1623                case MESSAGE:
1624                case BODY:
1625                case ATTACHMENT:
1626                case MAILBOX:
1627                case ACCOUNT:
1628                case HOSTAUTH:
1629                case POLICY:
1630                case QUICK_RESPONSE:
1631                    longId = db.insert(TABLE_NAMES[table], "foo", values);
1632                    resultUri = ContentUris.withAppendedId(uri, longId);
1633                    switch(match) {
1634                        case MAILBOX:
1635                            if (values.containsKey(MailboxColumns.TYPE)) {
1636                                // Only cache special mailbox types
1637                                int type = values.getAsInteger(MailboxColumns.TYPE);
1638                                if (type != Mailbox.TYPE_INBOX && type != Mailbox.TYPE_OUTBOX &&
1639                                        type != Mailbox.TYPE_DRAFTS && type != Mailbox.TYPE_SENT &&
1640                                        type != Mailbox.TYPE_TRASH && type != Mailbox.TYPE_SEARCH) {
1641                                    break;
1642                                }
1643                            }
1644                            //$FALL-THROUGH$
1645                        case ACCOUNT:
1646                        case HOSTAUTH:
1647                        case POLICY:
1648                            // Cache new account, host auth, policy, and some mailbox rows
1649                            Cursor c = query(resultUri, CACHE_PROJECTIONS[table], null, null, null);
1650                            if (c != null) {
1651                                if (match == MAILBOX) {
1652                                    addToMailboxTypeMap(c);
1653                                } else if (match == ACCOUNT) {
1654                                    getOrCreateAccountMailboxTypeMap(longId);
1655                                }
1656                                c.close();
1657                            }
1658                            break;
1659                    }
1660                    // Clients shouldn't normally be adding rows to these tables, as they are
1661                    // maintained by triggers.  However, we need to be able to do this for unit
1662                    // testing, so we allow the insert and then throw the same exception that we
1663                    // would if this weren't allowed.
1664                    if (match == UPDATED_MESSAGE || match == DELETED_MESSAGE) {
1665                        throw new IllegalArgumentException("Unknown URL " + uri);
1666                    }
1667                    if (match == ATTACHMENT) {
1668                        int flags = 0;
1669                        if (values.containsKey(Attachment.FLAGS)) {
1670                            flags = values.getAsInteger(Attachment.FLAGS);
1671                        }
1672                        // Report all new attachments to the download service
1673                        mAttachmentService.attachmentChanged(getContext(), longId, flags);
1674                    }
1675                    break;
1676                case MAILBOX_ID:
1677                    // This implies adding a message to a mailbox
1678                    // Hmm, a problem here is that we can't link the account as well, so it must be
1679                    // already in the values...
1680                    longId = Long.parseLong(uri.getPathSegments().get(1));
1681                    values.put(MessageColumns.MAILBOX_KEY, longId);
1682                    return insert(Message.CONTENT_URI, values); // Recurse
1683                case MESSAGE_ID:
1684                    // This implies adding an attachment to a message.
1685                    id = uri.getPathSegments().get(1);
1686                    longId = Long.parseLong(id);
1687                    values.put(AttachmentColumns.MESSAGE_KEY, longId);
1688                    return insert(Attachment.CONTENT_URI, values); // Recurse
1689                case ACCOUNT_ID:
1690                    // This implies adding a mailbox to an account.
1691                    longId = Long.parseLong(uri.getPathSegments().get(1));
1692                    values.put(MailboxColumns.ACCOUNT_KEY, longId);
1693                    return insert(Mailbox.CONTENT_URI, values); // Recurse
1694                case ATTACHMENTS_MESSAGE_ID:
1695                    longId = db.insert(TABLE_NAMES[table], "foo", values);
1696                    resultUri = ContentUris.withAppendedId(Attachment.CONTENT_URI, longId);
1697                    break;
1698                default:
1699                    throw new IllegalArgumentException("Unknown URL " + uri);
1700            }
1701        } catch (SQLiteException e) {
1702            checkDatabases();
1703            throw e;
1704        }
1705
1706        // Notify all notifier cursors
1707        sendNotifierChange(getBaseNotificationUri(match), NOTIFICATION_OP_INSERT, id);
1708
1709        // Notify all existing cursors.
1710        resolver.notifyChange(EmailContent.CONTENT_URI, null);
1711        return resultUri;
1712    }
1713
1714    @Override
1715    public boolean onCreate() {
1716        checkDatabases();
1717        return false;
1718    }
1719
1720    /**
1721     * The idea here is that the two databases (EmailProvider.db and EmailProviderBody.db must
1722     * always be in sync (i.e. there are two database or NO databases).  This code will delete
1723     * any "orphan" database, so that both will be created together.  Note that an "orphan" database
1724     * will exist after either of the individual databases is deleted due to data corruption.
1725     */
1726    public void checkDatabases() {
1727        // Uncache the databases
1728        if (mDatabase != null) {
1729            mDatabase = null;
1730        }
1731        if (mBodyDatabase != null) {
1732            mBodyDatabase = null;
1733        }
1734        // Look for orphans, and delete as necessary; these must always be in sync
1735        File databaseFile = getContext().getDatabasePath(DATABASE_NAME);
1736        File bodyFile = getContext().getDatabasePath(BODY_DATABASE_NAME);
1737
1738        // TODO Make sure attachments are deleted
1739        if (databaseFile.exists() && !bodyFile.exists()) {
1740            Log.w(TAG, "Deleting orphaned EmailProvider database...");
1741            databaseFile.delete();
1742        } else if (bodyFile.exists() && !databaseFile.exists()) {
1743            Log.w(TAG, "Deleting orphaned EmailProviderBody database...");
1744            bodyFile.delete();
1745        }
1746    }
1747
1748    @Override
1749    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
1750            String sortOrder) {
1751        long time = 0L;
1752        if (Email.DEBUG) {
1753            time = System.nanoTime();
1754        }
1755        Cursor c = null;
1756        int match;
1757        try {
1758            match = findMatch(uri, "query");
1759        } catch (IllegalArgumentException e) {
1760            String uriString = uri.toString();
1761            // If we were passed an illegal uri, see if it ends in /-1
1762            // if so, and if substituting 0 for -1 results in a valid uri, return an empty cursor
1763            if (uriString != null && uriString.endsWith("/-1")) {
1764                uri = Uri.parse(uriString.substring(0, uriString.length() - 2) + "0");
1765                match = findMatch(uri, "query");
1766                switch (match) {
1767                    case BODY_ID:
1768                    case MESSAGE_ID:
1769                    case DELETED_MESSAGE_ID:
1770                    case UPDATED_MESSAGE_ID:
1771                    case ATTACHMENT_ID:
1772                    case MAILBOX_ID:
1773                    case ACCOUNT_ID:
1774                    case HOSTAUTH_ID:
1775                    case POLICY_ID:
1776                        return new MatrixCursor(projection, 0);
1777                }
1778            }
1779            throw e;
1780        }
1781        Context context = getContext();
1782        // See the comment at delete(), above
1783        SQLiteDatabase db = getDatabase(context);
1784        int table = match >> BASE_SHIFT;
1785        String limit = uri.getQueryParameter(EmailContent.PARAMETER_LIMIT);
1786        String id;
1787
1788        // Find the cache for this query's table (if any)
1789        ContentCache cache = null;
1790        String tableName = TABLE_NAMES[table];
1791        // We can only use the cache if there's no selection
1792        if (selection == null) {
1793            cache = mContentCaches[table];
1794        }
1795        if (cache == null) {
1796            ContentCache.notCacheable(uri, selection);
1797        }
1798
1799        try {
1800            switch (match) {
1801                case ACCOUNT_DEFAULT_ID:
1802                    // Start with a snapshot of the cache
1803                    Map<String, Cursor> accountCache = mCacheAccount.getSnapshot();
1804                    long accountId = Account.NO_ACCOUNT;
1805                    // Find the account with "isDefault" set, or the lowest account ID otherwise.
1806                    // Note that the snapshot from the cached isn't guaranteed to be sorted in any
1807                    // way.
1808                    Collection<Cursor> accounts = accountCache.values();
1809                    for (Cursor accountCursor: accounts) {
1810                        // For now, at least, we can have zero count cursors (e.g. if someone looks
1811                        // up a non-existent id); we need to skip these
1812                        if (accountCursor.moveToFirst()) {
1813                            boolean isDefault =
1814                                accountCursor.getInt(Account.CONTENT_IS_DEFAULT_COLUMN) == 1;
1815                            long iterId = accountCursor.getLong(Account.CONTENT_ID_COLUMN);
1816                            // We'll remember this one if it's the default or the first one we see
1817                            if (isDefault) {
1818                                accountId = iterId;
1819                                break;
1820                            } else if ((accountId == Account.NO_ACCOUNT) || (iterId < accountId)) {
1821                                accountId = iterId;
1822                            }
1823                        }
1824                    }
1825                    // Return a cursor with an id projection
1826                    MatrixCursor mc = new MatrixCursor(EmailContent.ID_PROJECTION);
1827                    mc.addRow(new Object[] {accountId});
1828                    c = mc;
1829                    break;
1830                case MAILBOX_ID_FROM_ACCOUNT_AND_TYPE:
1831                    // Get accountId and type and find the mailbox in our map
1832                    List<String> pathSegments = uri.getPathSegments();
1833                    accountId = Long.parseLong(pathSegments.get(1));
1834                    int type = Integer.parseInt(pathSegments.get(2));
1835                    long mailboxId = getMailboxIdFromMailboxTypeMap(accountId, type);
1836                    // Return a cursor with an id projection
1837                    mc = new MatrixCursor(EmailContent.ID_PROJECTION);
1838                    mc.addRow(new Object[] {mailboxId});
1839                    c = mc;
1840                    break;
1841                case BODY:
1842                case MESSAGE:
1843                case UPDATED_MESSAGE:
1844                case DELETED_MESSAGE:
1845                case ATTACHMENT:
1846                case MAILBOX:
1847                case ACCOUNT:
1848                case HOSTAUTH:
1849                case POLICY:
1850                case QUICK_RESPONSE:
1851                    // Special-case "count of accounts"; it's common and we always know it
1852                    if (match == ACCOUNT && Arrays.equals(projection, EmailContent.COUNT_COLUMNS) &&
1853                            selection == null && limit.equals("1")) {
1854                        int accountCount = mMailboxTypeMap.size();
1855                        // In the rare case there are MAX_CACHED_ACCOUNTS or more, we can't do this
1856                        if (accountCount < MAX_CACHED_ACCOUNTS) {
1857                            mc = new MatrixCursor(projection, 1);
1858                            mc.addRow(new Object[] {accountCount});
1859                            c = mc;
1860                            break;
1861                        }
1862                    }
1863                    c = db.query(tableName, projection,
1864                            selection, selectionArgs, null, null, sortOrder, limit);
1865                    break;
1866                case BODY_ID:
1867                case MESSAGE_ID:
1868                case DELETED_MESSAGE_ID:
1869                case UPDATED_MESSAGE_ID:
1870                case ATTACHMENT_ID:
1871                case MAILBOX_ID:
1872                case ACCOUNT_ID:
1873                case HOSTAUTH_ID:
1874                case POLICY_ID:
1875                case QUICK_RESPONSE_ID:
1876                    id = uri.getPathSegments().get(1);
1877                    if (cache != null) {
1878                        c = cache.getCachedCursor(id, projection);
1879                    }
1880                    if (c == null) {
1881                        CacheToken token = null;
1882                        if (cache != null) {
1883                            token = cache.getCacheToken(id);
1884                        }
1885                        c = db.query(tableName, projection, whereWithId(id, selection),
1886                                selectionArgs, null, null, sortOrder, limit);
1887                        if (cache != null) {
1888                            c = cache.putCursor(c, id, projection, token);
1889                        }
1890                    }
1891                    break;
1892                case ATTACHMENTS_MESSAGE_ID:
1893                    // All attachments for the given message
1894                    id = uri.getPathSegments().get(2);
1895                    c = db.query(Attachment.TABLE_NAME, projection,
1896                            whereWith(Attachment.MESSAGE_KEY + "=" + id, selection),
1897                            selectionArgs, null, null, sortOrder, limit);
1898                    break;
1899                case QUICK_RESPONSE_ACCOUNT_ID:
1900                    // All quick responses for the given account
1901                    id = uri.getPathSegments().get(2);
1902                    c = db.query(QuickResponse.TABLE_NAME, projection,
1903                            whereWith(QuickResponse.ACCOUNT_KEY + "=" + id, selection),
1904                            selectionArgs, null, null, sortOrder);
1905                    break;
1906                default:
1907                    throw new IllegalArgumentException("Unknown URI " + uri);
1908            }
1909        } catch (SQLiteException e) {
1910            checkDatabases();
1911            throw e;
1912        } catch (RuntimeException e) {
1913            checkDatabases();
1914            e.printStackTrace();
1915            throw e;
1916        } finally {
1917            if (cache != null && c != null && Email.DEBUG) {
1918                cache.recordQueryTime(c, System.nanoTime() - time);
1919            }
1920            if (c == null) {
1921                // This should never happen, but let's be sure to log it...
1922                Log.e(TAG, "Query returning null for uri: " + uri + ", selection: " + selection);
1923            }
1924        }
1925
1926        if ((c != null) && !isTemporary()) {
1927            c.setNotificationUri(getContext().getContentResolver(), uri);
1928        }
1929        return c;
1930    }
1931
1932    private String whereWithId(String id, String selection) {
1933        StringBuilder sb = new StringBuilder(256);
1934        sb.append("_id=");
1935        sb.append(id);
1936        if (selection != null) {
1937            sb.append(" AND (");
1938            sb.append(selection);
1939            sb.append(')');
1940        }
1941        return sb.toString();
1942    }
1943
1944    /**
1945     * Combine a locally-generated selection with a user-provided selection
1946     *
1947     * This introduces risk that the local selection might insert incorrect chars
1948     * into the SQL, so use caution.
1949     *
1950     * @param where locally-generated selection, must not be null
1951     * @param selection user-provided selection, may be null
1952     * @return a single selection string
1953     */
1954    private String whereWith(String where, String selection) {
1955        if (selection == null) {
1956            return where;
1957        }
1958        StringBuilder sb = new StringBuilder(where);
1959        sb.append(" AND (");
1960        sb.append(selection);
1961        sb.append(')');
1962
1963        return sb.toString();
1964    }
1965
1966    /**
1967     * Restore a HostAuth from a database, given its unique id
1968     * @param db the database
1969     * @param id the unique id (_id) of the row
1970     * @return a fully populated HostAuth or null if the row does not exist
1971     */
1972    private static HostAuth restoreHostAuth(SQLiteDatabase db, long id) {
1973        Cursor c = db.query(HostAuth.TABLE_NAME, HostAuth.CONTENT_PROJECTION,
1974                HostAuth.RECORD_ID + "=?", new String[] {Long.toString(id)}, null, null, null);
1975        try {
1976            if (c.moveToFirst()) {
1977                HostAuth hostAuth = new HostAuth();
1978                hostAuth.restore(c);
1979                return hostAuth;
1980            }
1981            return null;
1982        } finally {
1983            c.close();
1984        }
1985    }
1986
1987    /**
1988     * Copy the Account and HostAuth tables from one database to another
1989     * @param fromDatabase the source database
1990     * @param toDatabase the destination database
1991     * @return the number of accounts copied, or -1 if an error occurred
1992     */
1993    private static int copyAccountTables(SQLiteDatabase fromDatabase, SQLiteDatabase toDatabase) {
1994        if (fromDatabase == null || toDatabase == null) return -1;
1995        int copyCount = 0;
1996        try {
1997            // Lock both databases; for the "from" database, we don't want anyone changing it from
1998            // under us; for the "to" database, we want to make the operation atomic
1999            fromDatabase.beginTransaction();
2000            toDatabase.beginTransaction();
2001            // Delete anything hanging around here
2002            toDatabase.delete(Account.TABLE_NAME, null, null);
2003            toDatabase.delete(HostAuth.TABLE_NAME, null, null);
2004            // Get our account cursor
2005            Cursor c = fromDatabase.query(Account.TABLE_NAME, Account.CONTENT_PROJECTION,
2006                    null, null, null, null, null);
2007            boolean noErrors = true;
2008            try {
2009                // Loop through accounts, copying them and associated host auth's
2010                while (c.moveToNext()) {
2011                    Account account = new Account();
2012                    account.restore(c);
2013
2014                    // Clear security sync key and sync key, as these were specific to the state of
2015                    // the account, and we've reset that...
2016                    // Clear policy key so that we can re-establish policies from the server
2017                    // TODO This is pretty EAS specific, but there's a lot of that around
2018                    account.mSecuritySyncKey = null;
2019                    account.mSyncKey = null;
2020                    account.mPolicyKey = 0;
2021
2022                    // Copy host auth's and update foreign keys
2023                    HostAuth hostAuth = restoreHostAuth(fromDatabase, account.mHostAuthKeyRecv);
2024                    // The account might have gone away, though very unlikely
2025                    if (hostAuth == null) continue;
2026                    account.mHostAuthKeyRecv = toDatabase.insert(HostAuth.TABLE_NAME, null,
2027                            hostAuth.toContentValues());
2028                    // EAS accounts have no send HostAuth
2029                    if (account.mHostAuthKeySend > 0) {
2030                        hostAuth = restoreHostAuth(fromDatabase, account.mHostAuthKeySend);
2031                        // Belt and suspenders; I can't imagine that this is possible, since we
2032                        // checked the validity of the account above, and the database is now locked
2033                        if (hostAuth == null) continue;
2034                        account.mHostAuthKeySend = toDatabase.insert(HostAuth.TABLE_NAME, null,
2035                                hostAuth.toContentValues());
2036                    }
2037                    // Now, create the account in the "to" database
2038                    toDatabase.insert(Account.TABLE_NAME, null, account.toContentValues());
2039                    copyCount++;
2040                }
2041            } catch (SQLiteException e) {
2042                noErrors = false;
2043                copyCount = -1;
2044            } finally {
2045                fromDatabase.endTransaction();
2046                if (noErrors) {
2047                    // Say it's ok to commit
2048                    toDatabase.setTransactionSuccessful();
2049                }
2050                toDatabase.endTransaction();
2051                c.close();
2052            }
2053        } catch (SQLiteException e) {
2054            copyCount = -1;
2055        }
2056        return copyCount;
2057    }
2058
2059    private static SQLiteDatabase getBackupDatabase(Context context) {
2060        DatabaseHelper helper = new DatabaseHelper(context, BACKUP_DATABASE_NAME);
2061        return helper.getWritableDatabase();
2062    }
2063
2064    /**
2065     * Backup account data, returning the number of accounts backed up
2066     */
2067    private static int backupAccounts(Context context, SQLiteDatabase mainDatabase) {
2068        if (Email.DEBUG) {
2069            Log.d(TAG, "backupAccounts...");
2070        }
2071        SQLiteDatabase backupDatabase = getBackupDatabase(context);
2072        try {
2073            int numBackedUp = copyAccountTables(mainDatabase, backupDatabase);
2074            if (numBackedUp < 0) {
2075                Log.e(TAG, "Account backup failed!");
2076            } else if (Email.DEBUG) {
2077                Log.d(TAG, "Backed up " + numBackedUp + " accounts...");
2078            }
2079            return numBackedUp;
2080        } finally {
2081            if (backupDatabase != null) {
2082                backupDatabase.close();
2083            }
2084        }
2085    }
2086
2087    /**
2088     * Restore account data, returning the number of accounts restored
2089     */
2090    private static int restoreAccounts(Context context, SQLiteDatabase mainDatabase) {
2091        if (Email.DEBUG) {
2092            Log.d(TAG, "restoreAccounts...");
2093        }
2094        SQLiteDatabase backupDatabase = getBackupDatabase(context);
2095        try {
2096            int numRecovered = copyAccountTables(backupDatabase, mainDatabase);
2097            if (numRecovered > 0) {
2098                Log.e(TAG, "Recovered " + numRecovered + " accounts!");
2099            } else if (numRecovered < 0) {
2100                Log.e(TAG, "Account recovery failed?");
2101            } else if (Email.DEBUG) {
2102                Log.d(TAG, "No accounts to restore...");
2103            }
2104            return numRecovered;
2105        } finally {
2106            if (backupDatabase != null) {
2107                backupDatabase.close();
2108            }
2109        }
2110    }
2111
2112    @Override
2113    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
2114        // Handle this special case the fastest possible way
2115        if (uri == INTEGRITY_CHECK_URI) {
2116            checkDatabases();
2117            return 0;
2118        } else if (uri == ACCOUNT_BACKUP_URI) {
2119            return backupAccounts(getContext(), getDatabase(getContext()));
2120        }
2121
2122        // Notify all existing cursors, except for ACCOUNT_RESET_NEW_COUNT(_ID)
2123        Uri notificationUri = EmailContent.CONTENT_URI;
2124
2125        int match = findMatch(uri, "update");
2126        Context context = getContext();
2127        ContentResolver resolver = context.getContentResolver();
2128        // See the comment at delete(), above
2129        SQLiteDatabase db = getDatabase(context);
2130        int table = match >> BASE_SHIFT;
2131        int result;
2132
2133        // We do NOT allow setting of unreadCount/messageCount via the provider
2134        // These columns are maintained via triggers
2135        if (match == MAILBOX_ID || match == MAILBOX) {
2136            values.remove(MailboxColumns.UNREAD_COUNT);
2137            values.remove(MailboxColumns.MESSAGE_COUNT);
2138        }
2139
2140        ContentCache cache = mContentCaches[table];
2141        String tableName = TABLE_NAMES[table];
2142        String id = "0";
2143
2144        try {
2145outer:
2146            switch (match) {
2147                case MAILBOX_ID_ADD_TO_FIELD:
2148                case ACCOUNT_ID_ADD_TO_FIELD:
2149                    id = uri.getPathSegments().get(1);
2150                    String field = values.getAsString(EmailContent.FIELD_COLUMN_NAME);
2151                    Long add = values.getAsLong(EmailContent.ADD_COLUMN_NAME);
2152                    if (field == null || add == null) {
2153                        throw new IllegalArgumentException("No field/add specified " + uri);
2154                    }
2155                    ContentValues actualValues = new ContentValues();
2156                    if (cache != null) {
2157                        cache.lock(id);
2158                    }
2159                    try {
2160                        db.beginTransaction();
2161                        try {
2162                            Cursor c = db.query(tableName,
2163                                    new String[] {EmailContent.RECORD_ID, field},
2164                                    whereWithId(id, selection),
2165                                    selectionArgs, null, null, null);
2166                            try {
2167                                result = 0;
2168                                String[] bind = new String[1];
2169                                if (c.moveToNext()) {
2170                                    bind[0] = c.getString(0); // _id
2171                                    long value = c.getLong(1) + add;
2172                                    actualValues.put(field, value);
2173                                    result = db.update(tableName, actualValues, ID_EQUALS, bind);
2174                                }
2175                                db.setTransactionSuccessful();
2176                            } finally {
2177                                c.close();
2178                            }
2179                        } finally {
2180                            db.endTransaction();
2181                        }
2182                    } finally {
2183                        if (cache != null) {
2184                            cache.unlock(id, actualValues);
2185                        }
2186                    }
2187                    break;
2188                case SYNCED_MESSAGE_ID:
2189                case UPDATED_MESSAGE_ID:
2190                case MESSAGE_ID:
2191                case BODY_ID:
2192                case ATTACHMENT_ID:
2193                case MAILBOX_ID:
2194                case ACCOUNT_ID:
2195                case HOSTAUTH_ID:
2196                case QUICK_RESPONSE_ID:
2197                case POLICY_ID:
2198                    id = uri.getPathSegments().get(1);
2199                    if (cache != null) {
2200                        cache.lock(id);
2201                    }
2202                    try {
2203                        if (match == SYNCED_MESSAGE_ID) {
2204                            // For synced messages, first copy the old message to the updated table
2205                            // Note the insert or ignore semantics, guaranteeing that only the first
2206                            // update will be reflected in the updated message table; therefore this
2207                            // row will always have the "original" data
2208                            db.execSQL(UPDATED_MESSAGE_INSERT + id);
2209                        } else if (match == MESSAGE_ID) {
2210                            db.execSQL(UPDATED_MESSAGE_DELETE + id);
2211                        }
2212                        result = db.update(tableName, values, whereWithId(id, selection),
2213                                selectionArgs);
2214                    } catch (SQLiteException e) {
2215                        // Null out values (so they aren't cached) and re-throw
2216                        values = null;
2217                        throw e;
2218                    } finally {
2219                        if (cache != null) {
2220                            cache.unlock(id, values);
2221                        }
2222                    }
2223                    if (match == ATTACHMENT_ID) {
2224                        if (values.containsKey(Attachment.FLAGS)) {
2225                            int flags = values.getAsInteger(Attachment.FLAGS);
2226                            mAttachmentService.attachmentChanged(getContext(),
2227                                    Integer.parseInt(id), flags);
2228                        }
2229                    }
2230                    break;
2231                case BODY:
2232                case MESSAGE:
2233                case UPDATED_MESSAGE:
2234                case ATTACHMENT:
2235                case MAILBOX:
2236                case ACCOUNT:
2237                case HOSTAUTH:
2238                case POLICY:
2239                    switch(match) {
2240                        // To avoid invalidating the cache on updates, we execute them one at a
2241                        // time using the XXX_ID uri; these are all executed atomically
2242                        case ACCOUNT:
2243                        case MAILBOX:
2244                        case HOSTAUTH:
2245                        case POLICY:
2246                            Cursor c = db.query(tableName, EmailContent.ID_PROJECTION,
2247                                    selection, selectionArgs, null, null, null);
2248                            db.beginTransaction();
2249                            result = 0;
2250                            try {
2251                                while (c.moveToNext()) {
2252                                    update(ContentUris.withAppendedId(
2253                                                uri, c.getLong(EmailContent.ID_PROJECTION_COLUMN)),
2254                                            values, null, null);
2255                                    result++;
2256                                }
2257                                db.setTransactionSuccessful();
2258                            } finally {
2259                                db.endTransaction();
2260                                c.close();
2261                            }
2262                            break outer;
2263                        // Any cached table other than those above should be invalidated here
2264                        case MESSAGE:
2265                            // If we're doing some generic update, the whole cache needs to be
2266                            // invalidated.  This case should be quite rare
2267                            cache.invalidate("Update", uri, selection);
2268                            //$FALL-THROUGH$
2269                        default:
2270                            result = db.update(tableName, values, selection, selectionArgs);
2271                            break outer;
2272                    }
2273                case ACCOUNT_RESET_NEW_COUNT_ID:
2274                    id = uri.getPathSegments().get(1);
2275                    if (cache != null) {
2276                        cache.lock(id);
2277                    }
2278                    ContentValues newMessageCount = CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT;
2279                    if (values != null) {
2280                        Long set = values.getAsLong(EmailContent.SET_COLUMN_NAME);
2281                        if (set != null) {
2282                            newMessageCount = new ContentValues();
2283                            newMessageCount.put(Account.NEW_MESSAGE_COUNT, set);
2284                        }
2285                    }
2286                    try {
2287                        result = db.update(tableName, newMessageCount,
2288                                whereWithId(id, selection), selectionArgs);
2289                    } finally {
2290                        if (cache != null) {
2291                            cache.unlock(id, values);
2292                        }
2293                    }
2294                    notificationUri = Account.CONTENT_URI; // Only notify account cursors.
2295                    break;
2296                case ACCOUNT_RESET_NEW_COUNT:
2297                    result = db.update(tableName, CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT,
2298                            selection, selectionArgs);
2299                    // Affects all accounts.  Just invalidate all account cache.
2300                    cache.invalidate("Reset all new counts", null, null);
2301                    notificationUri = Account.CONTENT_URI; // Only notify account cursors.
2302                    break;
2303                default:
2304                    throw new IllegalArgumentException("Unknown URI " + uri);
2305            }
2306        } catch (SQLiteException e) {
2307            checkDatabases();
2308            throw e;
2309        }
2310
2311        // Notify all notifier cursors
2312        sendNotifierChange(getBaseNotificationUri(match), NOTIFICATION_OP_UPDATE, id);
2313
2314        resolver.notifyChange(notificationUri, null);
2315        return result;
2316    }
2317
2318    /**
2319     * Returns the base notification URI for the given content type.
2320     *
2321     * @param match The type of content that was modified.
2322     */
2323    private Uri getBaseNotificationUri(int match) {
2324        Uri baseUri = null;
2325        switch (match) {
2326            case MESSAGE:
2327            case MESSAGE_ID:
2328            case SYNCED_MESSAGE_ID:
2329                baseUri = Message.NOTIFIER_URI;
2330                break;
2331            case ACCOUNT:
2332            case ACCOUNT_ID:
2333                baseUri = Account.NOTIFIER_URI;
2334                break;
2335        }
2336        return baseUri;
2337    }
2338
2339    /**
2340     * Sends a change notification to any cursors observers of the given base URI. The final
2341     * notification URI is dynamically built to contain the specified information. It will be
2342     * of the format <<baseURI>>/<<op>>/<<id>>; where <<op>> and <<id>> are optional depending
2343     * upon the given values.
2344     * NOTE: If <<op>> is specified, notifications for <<baseURI>>/<<id>> will NOT be invoked.
2345     * If this is necessary, it can be added. However, due to the implementation of
2346     * {@link ContentObserver}, observers of <<baseURI>> will receive multiple notifications.
2347     *
2348     * @param baseUri The base URI to send notifications to. Must be able to take appended IDs.
2349     * @param op Optional operation to be appended to the URI.
2350     * @param id If a positive value, the ID to append to the base URI. Otherwise, no ID will be
2351     *           appended to the base URI.
2352     */
2353    private void sendNotifierChange(Uri baseUri, String op, String id) {
2354        if (baseUri == null) return;
2355
2356        final ContentResolver resolver = getContext().getContentResolver();
2357
2358        // Append the operation, if specified
2359        if (op != null) {
2360            baseUri = baseUri.buildUpon().appendEncodedPath(op).build();
2361        }
2362
2363        long longId = 0L;
2364        try {
2365            longId = Long.valueOf(id);
2366        } catch (NumberFormatException ignore) {}
2367        if (longId > 0) {
2368            resolver.notifyChange(ContentUris.withAppendedId(baseUri, longId), null);
2369        } else {
2370            resolver.notifyChange(baseUri, null);
2371        }
2372
2373        // We want to send the message list changed notification if baseUri is Message.NOTIFIER_URI.
2374        if (baseUri.equals(Message.NOTIFIER_URI)) {
2375            sendMessageListDataChangedNotification();
2376        }
2377    }
2378
2379    private void sendMessageListDataChangedNotification() {
2380        final Context context = getContext();
2381        final Intent intent = new Intent(ACTION_NOTIFY_MESSAGE_LIST_DATASET_CHANGED);
2382        // Ideally this intent would contain information about which account changed, to limit the
2383        // updates to that particular account.  Unfortunately, that information is not available in
2384        // sendNotifierChange().
2385        context.sendBroadcast(intent);
2386    }
2387
2388    @Override
2389    public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
2390            throws OperationApplicationException {
2391        Context context = getContext();
2392        SQLiteDatabase db = getDatabase(context);
2393        db.beginTransaction();
2394        try {
2395            ContentProviderResult[] results = super.applyBatch(operations);
2396            db.setTransactionSuccessful();
2397            return results;
2398        } finally {
2399            db.endTransaction();
2400        }
2401    }
2402
2403    /** Counts the number of messages in each mailbox, and updates the message count column. */
2404    @VisibleForTesting
2405    static void recalculateMessageCount(SQLiteDatabase db) {
2406        db.execSQL("update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
2407                "= (select count(*) from " + Message.TABLE_NAME +
2408                " where " + Message.MAILBOX_KEY + " = " +
2409                    Mailbox.TABLE_NAME + "." + EmailContent.RECORD_ID + ")");
2410    }
2411
2412    @VisibleForTesting
2413    @SuppressWarnings("deprecation")
2414    static void convertPolicyFlagsToPolicyTable(SQLiteDatabase db) {
2415        Cursor c = db.query(Account.TABLE_NAME,
2416                new String[] {EmailContent.RECORD_ID /*0*/, AccountColumns.SECURITY_FLAGS /*1*/},
2417                AccountColumns.SECURITY_FLAGS + ">0", null, null, null, null);
2418        ContentValues cv = new ContentValues();
2419        String[] args = new String[1];
2420        while (c.moveToNext()) {
2421            long securityFlags = c.getLong(1 /*SECURITY_FLAGS*/);
2422            Policy policy = LegacyPolicySet.flagsToPolicy(securityFlags);
2423            long policyId = db.insert(Policy.TABLE_NAME, null, policy.toContentValues());
2424            cv.put(AccountColumns.POLICY_KEY, policyId);
2425            cv.putNull(AccountColumns.SECURITY_FLAGS);
2426            args[0] = Long.toString(c.getLong(0 /*RECORD_ID*/));
2427            db.update(Account.TABLE_NAME, cv, EmailContent.RECORD_ID + "=?", args);
2428        }
2429    }
2430
2431    /** Upgrades the database from v17 to v18 */
2432    @VisibleForTesting
2433    static void upgradeFromVersion17ToVersion18(SQLiteDatabase db) {
2434        // Copy the displayName column to the serverId column. In v18 of the database,
2435        // we use the serverId for IMAP/POP3 mailboxes instead of overloading the
2436        // display name.
2437        //
2438        // For posterity; this is the command we're executing:
2439        //sqlite> UPDATE mailbox SET serverid=displayname WHERE mailbox._id in (
2440        //        ...> SELECT mailbox._id FROM mailbox,account,hostauth WHERE
2441        //        ...> (mailbox.parentkey isnull OR mailbox.parentkey=0) AND
2442        //        ...> mailbox.accountkey=account._id AND
2443        //        ...> account.hostauthkeyrecv=hostauth._id AND
2444        //        ...> (hostauth.protocol='imap' OR hostauth.protocol='pop3'));
2445        try {
2446            db.execSQL(
2447                    "UPDATE " + Mailbox.TABLE_NAME + " SET "
2448                    + MailboxColumns.SERVER_ID + "=" + MailboxColumns.DISPLAY_NAME
2449                    + " WHERE "
2450                    + Mailbox.TABLE_NAME + "." + MailboxColumns.ID + " IN ( SELECT "
2451                    + Mailbox.TABLE_NAME + "." + MailboxColumns.ID + " FROM "
2452                    + Mailbox.TABLE_NAME + "," + Account.TABLE_NAME + ","
2453                    + HostAuth.TABLE_NAME + " WHERE "
2454                    + "("
2455                    + Mailbox.TABLE_NAME + "." + MailboxColumns.PARENT_KEY + " isnull OR "
2456                    + Mailbox.TABLE_NAME + "." + MailboxColumns.PARENT_KEY + "=0 "
2457                    + ") AND "
2458                    + Mailbox.TABLE_NAME + "." + MailboxColumns.ACCOUNT_KEY + "="
2459                    + Account.TABLE_NAME + "." + AccountColumns.ID + " AND "
2460                    + Account.TABLE_NAME + "." + AccountColumns.HOST_AUTH_KEY_RECV + "="
2461                    + HostAuth.TABLE_NAME + "." + HostAuthColumns.ID + " AND ( "
2462                    + HostAuth.TABLE_NAME + "." + HostAuthColumns.PROTOCOL + "='imap' OR "
2463                    + HostAuth.TABLE_NAME + "." + HostAuthColumns.PROTOCOL + "='pop3' ) )");
2464        } catch (SQLException e) {
2465            // Shouldn't be needed unless we're debugging and interrupt the process
2466            Log.w(TAG, "Exception upgrading EmailProvider.db from 17 to 18 " + e);
2467        }
2468        ContentCache.invalidateAllCaches();
2469    }
2470
2471    /** Upgrades the database from v20 to v21 */
2472    private static void upgradeFromVersion20ToVersion21(SQLiteDatabase db) {
2473        try {
2474            db.execSQL("alter table " + Mailbox.TABLE_NAME
2475                    + " add column " + Mailbox.LAST_SEEN_MESSAGE_KEY + " integer;");
2476        } catch (SQLException e) {
2477            // Shouldn't be needed unless we're debugging and interrupt the process
2478            Log.w(TAG, "Exception upgrading EmailProvider.db from 20 to 21 " + e);
2479        }
2480    }
2481
2482    /**
2483     * Upgrade the database from v21 to v22
2484     * This entails creating AccountManager accounts for all pop3 and imap accounts
2485     */
2486
2487    private static final String[] V21_ACCOUNT_PROJECTION =
2488        new String[] {AccountColumns.HOST_AUTH_KEY_RECV, AccountColumns.EMAIL_ADDRESS};
2489    private static final int V21_ACCOUNT_RECV = 0;
2490    private static final int V21_ACCOUNT_EMAIL = 1;
2491
2492    private static final String[] V21_HOSTAUTH_PROJECTION =
2493        new String[] {HostAuthColumns.PROTOCOL, HostAuthColumns.PASSWORD};
2494    private static final int V21_HOSTAUTH_PROTOCOL = 0;
2495    private static final int V21_HOSTAUTH_PASSWORD = 1;
2496
2497    static private void createAccountManagerAccount(Context context, String login,
2498            String password) {
2499        AccountManager accountManager = AccountManager.get(context);
2500        android.accounts.Account amAccount =
2501            new android.accounts.Account(login, AccountManagerTypes.TYPE_POP_IMAP);
2502        accountManager.addAccountExplicitly(amAccount, password, null);
2503        ContentResolver.setIsSyncable(amAccount, EmailContent.AUTHORITY, 1);
2504        ContentResolver.setSyncAutomatically(amAccount, EmailContent.AUTHORITY, true);
2505        ContentResolver.setIsSyncable(amAccount, ContactsContract.AUTHORITY, 0);
2506        ContentResolver.setIsSyncable(amAccount, CalendarProviderStub.AUTHORITY, 0);
2507    }
2508
2509    @VisibleForTesting
2510    static void upgradeFromVersion21ToVersion22(SQLiteDatabase db, Context accountManagerContext) {
2511        try {
2512            // Loop through accounts, looking for pop/imap accounts
2513            Cursor accountCursor = db.query(Account.TABLE_NAME, V21_ACCOUNT_PROJECTION, null,
2514                    null, null, null, null);
2515            try {
2516                String[] hostAuthArgs = new String[1];
2517                while (accountCursor.moveToNext()) {
2518                    hostAuthArgs[0] = accountCursor.getString(V21_ACCOUNT_RECV);
2519                    // Get the "receive" HostAuth for this account
2520                    Cursor hostAuthCursor = db.query(HostAuth.TABLE_NAME,
2521                            V21_HOSTAUTH_PROJECTION, HostAuth.RECORD_ID + "=?", hostAuthArgs,
2522                            null, null, null);
2523                    try {
2524                        if (hostAuthCursor.moveToFirst()) {
2525                            String protocol = hostAuthCursor.getString(V21_HOSTAUTH_PROTOCOL);
2526                            // If this is a pop3 or imap account, create the account manager account
2527                            if (HostAuth.SCHEME_IMAP.equals(protocol) ||
2528                                    HostAuth.SCHEME_POP3.equals(protocol)) {
2529                                if (Email.DEBUG) {
2530                                    Log.d(TAG, "Create AccountManager account for " + protocol +
2531                                            "account: " +
2532                                            accountCursor.getString(V21_ACCOUNT_EMAIL));
2533                                }
2534                                createAccountManagerAccount(accountManagerContext,
2535                                        accountCursor.getString(V21_ACCOUNT_EMAIL),
2536                                        hostAuthCursor.getString(V21_HOSTAUTH_PASSWORD));
2537                            // If an EAS account, make Email sync automatically (equivalent of
2538                            // checking the "Sync Email" box in settings
2539                            } else if (HostAuth.SCHEME_EAS.equals(protocol)) {
2540                                android.accounts.Account amAccount =
2541                                        new android.accounts.Account(
2542                                                accountCursor.getString(V21_ACCOUNT_EMAIL),
2543                                                AccountManagerTypes.TYPE_EXCHANGE);
2544                                ContentResolver.setIsSyncable(amAccount, EmailContent.AUTHORITY, 1);
2545                                ContentResolver.setSyncAutomatically(amAccount,
2546                                        EmailContent.AUTHORITY, true);
2547
2548                            }
2549                        }
2550                    } finally {
2551                        hostAuthCursor.close();
2552                    }
2553                }
2554            } finally {
2555                accountCursor.close();
2556            }
2557        } catch (SQLException e) {
2558            // Shouldn't be needed unless we're debugging and interrupt the process
2559            Log.w(TAG, "Exception upgrading EmailProvider.db from 20 to 21 " + e);
2560        }
2561    }
2562
2563    /** Upgrades the database from v22 to v23 */
2564    private static void upgradeFromVersion22ToVersion23(SQLiteDatabase db) {
2565        try {
2566            db.execSQL("alter table " + Mailbox.TABLE_NAME
2567                    + " add column " + Mailbox.LAST_TOUCHED_TIME + " integer default 0;");
2568        } catch (SQLException e) {
2569            // Shouldn't be needed unless we're debugging and interrupt the process
2570            Log.w(TAG, "Exception upgrading EmailProvider.db from 22 to 23 " + e);
2571        }
2572    }
2573
2574    /** Adds in a column for information about a client certificate to use. */
2575    private static void upgradeFromVersion23ToVersion24(SQLiteDatabase db) {
2576        try {
2577            db.execSQL("alter table " + HostAuth.TABLE_NAME
2578                    + " add column " + HostAuth.CLIENT_CERT_ALIAS + " text;");
2579        } catch (SQLException e) {
2580            // Shouldn't be needed unless we're debugging and interrupt the process
2581            Log.w(TAG, "Exception upgrading EmailProvider.db from 23 to 24 " + e);
2582        }
2583    }
2584
2585    /** Upgrades the database from v24 to v25 by creating table for quick responses */
2586    private static void upgradeFromVersion24ToVersion25(SQLiteDatabase db) {
2587        try {
2588            createQuickResponseTable(db);
2589        } catch (SQLException e) {
2590            // Shouldn't be needed unless we're debugging and interrupt the process
2591            Log.w(TAG, "Exception upgrading EmailProvider.db from 24 to 25 " + e);
2592        }
2593    }
2594
2595    private static final String[] V25_ACCOUNT_PROJECTION =
2596        new String[] {AccountColumns.ID, AccountColumns.FLAGS, AccountColumns.HOST_AUTH_KEY_RECV};
2597    private static final int V25_ACCOUNT_ID = 0;
2598    private static final int V25_ACCOUNT_FLAGS = 1;
2599    private static final int V25_ACCOUNT_RECV = 2;
2600
2601    private static final String[] V25_HOSTAUTH_PROJECTION = new String[] {HostAuthColumns.PROTOCOL};
2602    private static final int V25_HOSTAUTH_PROTOCOL = 0;
2603
2604    /** Upgrades the database from v25 to v26 by adding FLAG_SUPPORTS_SEARCH to IMAP accounts */
2605    private static void upgradeFromVersion25ToVersion26(SQLiteDatabase db) {
2606        try {
2607            // Loop through accounts, looking for imap accounts
2608            Cursor accountCursor = db.query(Account.TABLE_NAME, V25_ACCOUNT_PROJECTION, null,
2609                    null, null, null, null);
2610            ContentValues cv = new ContentValues();
2611            try {
2612                String[] hostAuthArgs = new String[1];
2613                while (accountCursor.moveToNext()) {
2614                    hostAuthArgs[0] = accountCursor.getString(V25_ACCOUNT_RECV);
2615                    // Get the "receive" HostAuth for this account
2616                    Cursor hostAuthCursor = db.query(HostAuth.TABLE_NAME,
2617                            V25_HOSTAUTH_PROJECTION, HostAuth.RECORD_ID + "=?", hostAuthArgs,
2618                            null, null, null);
2619                    try {
2620                        if (hostAuthCursor.moveToFirst()) {
2621                            String protocol = hostAuthCursor.getString(V25_HOSTAUTH_PROTOCOL);
2622                            // If this is an imap account, add the search flag
2623                            if (HostAuth.SCHEME_IMAP.equals(protocol)) {
2624                                String id = accountCursor.getString(V25_ACCOUNT_ID);
2625                                int flags = accountCursor.getInt(V25_ACCOUNT_FLAGS);
2626                                cv.put(AccountColumns.FLAGS, flags | Account.FLAGS_SUPPORTS_SEARCH);
2627                                db.update(Account.TABLE_NAME, cv, Account.RECORD_ID + "=?",
2628                                        new String[] {id});
2629                            }
2630                        }
2631                    } finally {
2632                        hostAuthCursor.close();
2633                    }
2634                }
2635            } finally {
2636                accountCursor.close();
2637            }
2638        } catch (SQLException e) {
2639            // Shouldn't be needed unless we're debugging and interrupt the process
2640            Log.w(TAG, "Exception upgrading EmailProvider.db from 25 to 26 " + e);
2641        }
2642    }
2643
2644        /**
2645     * For testing purposes, check whether a given row is cached
2646     * @param baseUri the base uri of the EmailContent
2647     * @param id the row id of the EmailContent
2648     * @return whether or not the row is currently cached
2649     */
2650    @VisibleForTesting
2651    protected boolean isCached(Uri baseUri, long id) {
2652        int match = findMatch(baseUri, "isCached");
2653        int table = match >> BASE_SHIFT;
2654        ContentCache cache = mContentCaches[table];
2655        if (cache == null) return false;
2656        Cursor cc = cache.get(Long.toString(id));
2657        return (cc != null);
2658    }
2659
2660    public static interface AttachmentService {
2661        /**
2662         * Notify the service that an attachment has changed.
2663         */
2664        void attachmentChanged(Context context, long id, int flags);
2665    }
2666
2667    private final AttachmentService DEFAULT_ATTACHMENT_SERVICE = new AttachmentService() {
2668        @Override
2669        public void attachmentChanged(Context context, long id, int flags) {
2670            // The default implementation delegates to the real service.
2671            AttachmentDownloadService.attachmentChanged(context, id, flags);
2672        }
2673    };
2674    private AttachmentService mAttachmentService = DEFAULT_ATTACHMENT_SERVICE;
2675
2676    /**
2677     * Injects a custom attachment service handler. If null is specified, will reset to the
2678     * default service.
2679     */
2680    public void injectAttachmentService(AttachmentService as) {
2681        mAttachmentService = (as == null) ? DEFAULT_ATTACHMENT_SERVICE : as;
2682    }
2683}
2684