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