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