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