EmailProvider.java revision e7fb4ac9e3b098ece98d004403a89652f88bbe7a
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 com.android.email.Email;
20import com.android.email.provider.ContentCache.CacheToken;
21import com.android.email.service.AttachmentDownloadService;
22import com.android.emailcommon.AccountManagerTypes;
23import com.android.emailcommon.provider.EmailContent;
24import com.android.emailcommon.provider.EmailContent.Account;
25import com.android.emailcommon.provider.EmailContent.AccountColumns;
26import com.android.emailcommon.provider.EmailContent.Attachment;
27import com.android.emailcommon.provider.EmailContent.AttachmentColumns;
28import com.android.emailcommon.provider.EmailContent.Body;
29import com.android.emailcommon.provider.EmailContent.BodyColumns;
30import com.android.emailcommon.provider.EmailContent.HostAuth;
31import com.android.emailcommon.provider.EmailContent.HostAuthColumns;
32import com.android.emailcommon.provider.EmailContent.Mailbox;
33import com.android.emailcommon.provider.EmailContent.MailboxColumns;
34import com.android.emailcommon.provider.EmailContent.Message;
35import com.android.emailcommon.provider.EmailContent.MessageColumns;
36import com.android.emailcommon.provider.EmailContent.PolicyColumns;
37import com.android.emailcommon.provider.EmailContent.SyncColumns;
38import com.android.emailcommon.provider.Policy;
39import com.android.emailcommon.service.LegacyPolicySet;
40import com.google.common.annotations.VisibleForTesting;
41
42import android.accounts.AccountManager;
43import android.content.ContentProvider;
44import android.content.ContentProviderOperation;
45import android.content.ContentProviderResult;
46import android.content.ContentResolver;
47import android.content.ContentUris;
48import android.content.ContentValues;
49import android.content.Context;
50import android.content.OperationApplicationException;
51import android.content.UriMatcher;
52import android.database.ContentObserver;
53import android.database.Cursor;
54import android.database.MatrixCursor;
55import android.database.SQLException;
56import android.database.sqlite.SQLiteDatabase;
57import android.database.sqlite.SQLiteException;
58import android.database.sqlite.SQLiteOpenHelper;
59import android.net.Uri;
60import android.util.Log;
61
62import java.io.File;
63import java.util.ArrayList;
64
65public class EmailProvider extends ContentProvider {
66
67    private static final String TAG = "EmailProvider";
68
69    protected static final String DATABASE_NAME = "EmailProvider.db";
70    protected static final String BODY_DATABASE_NAME = "EmailProviderBody.db";
71    protected static final String BACKUP_DATABASE_NAME = "EmailProviderBackup.db";
72
73    public static final String ACTION_ATTACHMENT_UPDATED = "com.android.email.ATTACHMENT_UPDATED";
74    public static final String ATTACHMENT_UPDATED_EXTRA_FLAGS =
75        "com.android.email.ATTACHMENT_UPDATED_FLAGS";
76
77    public static final String EMAIL_MESSAGE_MIME_TYPE =
78        "vnd.android.cursor.item/email-message";
79    public static final String EMAIL_ATTACHMENT_MIME_TYPE =
80        "vnd.android.cursor.item/email-attachment";
81
82    public static final Uri INTEGRITY_CHECK_URI =
83        Uri.parse("content://" + EmailContent.AUTHORITY + "/integrityCheck");
84    public static final Uri ACCOUNT_BACKUP_URI =
85        Uri.parse("content://" + EmailContent.AUTHORITY + "/accountBackup");
86    public static final Uri ACCOUNT_RESTORE_URI =
87        Uri.parse("content://" + EmailContent.AUTHORITY + "/accountRestore");
88
89    /** Appended to the notification URI for delete operations */
90    public static final String NOTIFICATION_OP_DELETE = "delete";
91    /** Appended to the notification URI for insert operations */
92    public static final String NOTIFICATION_OP_INSERT = "insert";
93    /** Appended to the notification URI for update operations */
94    public static final String NOTIFICATION_OP_UPDATE = "update";
95
96    // Definitions for our queries looking for orphaned messages
97    private static final String[] ORPHANS_PROJECTION
98        = new String[] {MessageColumns.ID, MessageColumns.MAILBOX_KEY};
99    private static final int ORPHANS_ID = 0;
100    private static final int ORPHANS_MAILBOX_KEY = 1;
101
102    private static final String WHERE_ID = EmailContent.RECORD_ID + "=?";
103
104    // We'll cache the following four tables; sizes are best estimates of effective values
105    private static final ContentCache sCacheAccount =
106        new ContentCache("Account", Account.CONTENT_PROJECTION, 4);
107    private static final ContentCache sCacheHostAuth =
108        new ContentCache("HostAuth", HostAuth.CONTENT_PROJECTION, 8);
109    /*package*/ static final ContentCache sCacheMailbox =
110        new ContentCache("Mailbox", Mailbox.CONTENT_PROJECTION, 8);
111    private static final ContentCache sCacheMessage =
112        new ContentCache("Message", Message.CONTENT_PROJECTION, 8);
113    private static final ContentCache sCachePolicy =
114        new ContentCache("Policy", Policy.CONTENT_PROJECTION, 4);
115
116    // Any changes to the database format *must* include update-in-place code.
117    // Original version: 3
118    // Version 4: Database wipe required; changing AccountManager interface w/Exchange
119    // Version 5: Database wipe required; changing AccountManager interface w/Exchange
120    // Version 6: Adding Message.mServerTimeStamp column
121    // Version 7: Replace the mailbox_delete trigger with a version that removes orphaned messages
122    //            from the Message_Deletes and Message_Updates tables
123    // Version 8: Add security flags column to accounts table
124    // Version 9: Add security sync key and signature to accounts table
125    // Version 10: Add meeting info to message table
126    // Version 11: Add content and flags to attachment table
127    // Version 12: Add content_bytes to attachment table. content is deprecated.
128    // Version 13: Add messageCount to Mailbox table.
129    // Version 14: Add snippet to Message table
130    // Version 15: Fix upgrade problem in version 14.
131    // Version 16: Add accountKey to Attachment table
132    // Version 17: Add parentKey to Mailbox table
133    // Version 18: Copy Mailbox.displayName to Mailbox.serverId for all IMAP & POP3 mailboxes.
134    //             Column Mailbox.serverId is used for the server-side pathname of a mailbox.
135    // Version 19: Add Policy table; add policyKey to Account table and trigger to delete an
136    //             Account's policy when the Account is deleted
137    // Version 20: Add new policies to Policy table
138    // Version 21: Add lastSeenMessageKey column to Mailbox table
139    public static final int DATABASE_VERSION = 21;
140
141    // Any changes to the database format *must* include update-in-place code.
142    // Original version: 2
143    // Version 3: Add "sourceKey" column
144    // Version 4: Database wipe required; changing AccountManager interface w/Exchange
145    // Version 5: Database wipe required; changing AccountManager interface w/Exchange
146    // Version 6: Adding Body.mIntroText column
147    public static final int BODY_DATABASE_VERSION = 6;
148
149    private static final int ACCOUNT_BASE = 0;
150    private static final int ACCOUNT = ACCOUNT_BASE;
151    private static final int ACCOUNT_ID = ACCOUNT_BASE + 1;
152    private static final int ACCOUNT_ID_ADD_TO_FIELD = ACCOUNT_BASE + 2;
153    private static final int ACCOUNT_RESET_NEW_COUNT = ACCOUNT_BASE + 3;
154    private static final int ACCOUNT_RESET_NEW_COUNT_ID = ACCOUNT_BASE + 4;
155
156    private static final int MAILBOX_BASE = 0x1000;
157    private static final int MAILBOX = MAILBOX_BASE;
158    private static final int MAILBOX_ID = MAILBOX_BASE + 1;
159    private static final int MAILBOX_ID_ADD_TO_FIELD = MAILBOX_BASE + 2;
160
161    private static final int MESSAGE_BASE = 0x2000;
162    private static final int MESSAGE = MESSAGE_BASE;
163    private static final int MESSAGE_ID = MESSAGE_BASE + 1;
164    private static final int SYNCED_MESSAGE_ID = MESSAGE_BASE + 2;
165
166    private static final int ATTACHMENT_BASE = 0x3000;
167    private static final int ATTACHMENT = ATTACHMENT_BASE;
168    private static final int ATTACHMENT_ID = ATTACHMENT_BASE + 1;
169    private static final int ATTACHMENTS_MESSAGE_ID = ATTACHMENT_BASE + 2;
170
171    private static final int HOSTAUTH_BASE = 0x4000;
172    private static final int HOSTAUTH = HOSTAUTH_BASE;
173    private static final int HOSTAUTH_ID = HOSTAUTH_BASE + 1;
174
175    private static final int UPDATED_MESSAGE_BASE = 0x5000;
176    private static final int UPDATED_MESSAGE = UPDATED_MESSAGE_BASE;
177    private static final int UPDATED_MESSAGE_ID = UPDATED_MESSAGE_BASE + 1;
178
179    private static final int DELETED_MESSAGE_BASE = 0x6000;
180    private static final int DELETED_MESSAGE = DELETED_MESSAGE_BASE;
181    private static final int DELETED_MESSAGE_ID = DELETED_MESSAGE_BASE + 1;
182
183    private static final int POLICY_BASE = 0x7000;
184    private static final int POLICY = POLICY_BASE;
185    private static final int POLICY_ID = POLICY_BASE + 1;
186
187    // MUST ALWAYS EQUAL THE LAST OF THE PREVIOUS BASE CONSTANTS
188    private static final int LAST_EMAIL_PROVIDER_DB_BASE = POLICY_BASE;
189
190    // DO NOT CHANGE BODY_BASE!!
191    private static final int BODY_BASE = LAST_EMAIL_PROVIDER_DB_BASE + 0x1000;
192    private static final int BODY = BODY_BASE;
193    private static final int BODY_ID = BODY_BASE + 1;
194
195    private static final int BASE_SHIFT = 12;  // 12 bits to the base type: 0, 0x1000, 0x2000, etc.
196
197    // TABLE_NAMES MUST remain in the order of the BASE constants above (e.g. ACCOUNT_BASE = 0x0000,
198    // MESSAGE_BASE = 0x1000, etc.)
199    private static final String[] TABLE_NAMES = {
200        EmailContent.Account.TABLE_NAME,
201        EmailContent.Mailbox.TABLE_NAME,
202        EmailContent.Message.TABLE_NAME,
203        EmailContent.Attachment.TABLE_NAME,
204        EmailContent.HostAuth.TABLE_NAME,
205        EmailContent.Message.UPDATED_TABLE_NAME,
206        EmailContent.Message.DELETED_TABLE_NAME,
207        Policy.TABLE_NAME,
208        EmailContent.Body.TABLE_NAME
209    };
210
211    // CONTENT_CACHES MUST remain in the order of the BASE constants above
212    private static final ContentCache[] CONTENT_CACHES = {
213        sCacheAccount,
214        sCacheMailbox,
215        sCacheMessage,
216        null, // Attachment
217        sCacheHostAuth,
218        null, // Updated message
219        null, // Deleted message
220        sCachePolicy,
221        null  // Body
222    };
223
224    private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
225
226    /**
227     * Let's only generate these SQL strings once, as they are used frequently
228     * Note that this isn't relevant for table creation strings, since they are used only once
229     */
230    private static final String UPDATED_MESSAGE_INSERT = "insert or ignore into " +
231        Message.UPDATED_TABLE_NAME + " select * from " + Message.TABLE_NAME + " where " +
232        EmailContent.RECORD_ID + '=';
233
234    private static final String UPDATED_MESSAGE_DELETE = "delete from " +
235        Message.UPDATED_TABLE_NAME + " where " + EmailContent.RECORD_ID + '=';
236
237    private static final String DELETED_MESSAGE_INSERT = "insert or replace into " +
238        Message.DELETED_TABLE_NAME + " select * from " + Message.TABLE_NAME + " where " +
239        EmailContent.RECORD_ID + '=';
240
241    private static final String DELETE_ORPHAN_BODIES = "delete from " + Body.TABLE_NAME +
242        " where " + BodyColumns.MESSAGE_KEY + " in " + "(select " + BodyColumns.MESSAGE_KEY +
243        " from " + Body.TABLE_NAME + " except select " + EmailContent.RECORD_ID + " from " +
244        Message.TABLE_NAME + ')';
245
246    private static final String DELETE_BODY = "delete from " + Body.TABLE_NAME +
247        " where " + BodyColumns.MESSAGE_KEY + '=';
248
249    private static final String ID_EQUALS = EmailContent.RECORD_ID + "=?";
250
251    private static final String TRIGGER_MAILBOX_DELETE =
252        "create trigger mailbox_delete before delete on " + Mailbox.TABLE_NAME +
253        " begin" +
254        " delete from " + Message.TABLE_NAME +
255        "  where " + MessageColumns.MAILBOX_KEY + "=old." + EmailContent.RECORD_ID +
256        "; delete from " + Message.UPDATED_TABLE_NAME +
257        "  where " + MessageColumns.MAILBOX_KEY + "=old." + EmailContent.RECORD_ID +
258        "; delete from " + Message.DELETED_TABLE_NAME +
259        "  where " + MessageColumns.MAILBOX_KEY + "=old." + EmailContent.RECORD_ID +
260        "; end";
261
262    private static final String TRIGGER_ACCOUNT_DELETE =
263        "create trigger account_delete before delete on " + Account.TABLE_NAME +
264        " begin delete from " + Mailbox.TABLE_NAME +
265        " where " + MailboxColumns.ACCOUNT_KEY + "=old." + EmailContent.RECORD_ID +
266        "; delete from " + HostAuth.TABLE_NAME +
267        " where " + EmailContent.RECORD_ID + "=old." + AccountColumns.HOST_AUTH_KEY_RECV +
268        "; delete from " + HostAuth.TABLE_NAME +
269        " where " + EmailContent.RECORD_ID + "=old." + AccountColumns.HOST_AUTH_KEY_SEND +
270        "; delete from " + Policy.TABLE_NAME +
271        " where " + EmailContent.RECORD_ID + "=old." + AccountColumns.POLICY_KEY +
272        "; end";
273
274    private static final ContentValues CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT;
275
276    public static final String MESSAGE_URI_PARAMETER_MAILBOX_ID = "mailboxId";
277
278    static {
279        // Email URI matching table
280        UriMatcher matcher = sURIMatcher;
281
282        // All accounts
283        matcher.addURI(EmailContent.AUTHORITY, "account", ACCOUNT);
284        // A specific account
285        // insert into this URI causes a mailbox to be added to the account
286        matcher.addURI(EmailContent.AUTHORITY, "account/#", ACCOUNT_ID);
287
288        // Special URI to reset the new message count.  Only update works, and content values
289        // will be ignored.
290        matcher.addURI(EmailContent.AUTHORITY, "resetNewMessageCount",
291                ACCOUNT_RESET_NEW_COUNT);
292        matcher.addURI(EmailContent.AUTHORITY, "resetNewMessageCount/#",
293                ACCOUNT_RESET_NEW_COUNT_ID);
294
295        // All mailboxes
296        matcher.addURI(EmailContent.AUTHORITY, "mailbox", MAILBOX);
297        // A specific mailbox
298        // insert into this URI causes a message to be added to the mailbox
299        // ** NOTE For now, the accountKey must be set manually in the values!
300        matcher.addURI(EmailContent.AUTHORITY, "mailbox/#", MAILBOX_ID);
301
302        // All messages
303        matcher.addURI(EmailContent.AUTHORITY, "message", MESSAGE);
304        // A specific message
305        // insert into this URI causes an attachment to be added to the message
306        matcher.addURI(EmailContent.AUTHORITY, "message/#", MESSAGE_ID);
307
308        // A specific attachment
309        matcher.addURI(EmailContent.AUTHORITY, "attachment", ATTACHMENT);
310        // A specific attachment (the header information)
311        matcher.addURI(EmailContent.AUTHORITY, "attachment/#", ATTACHMENT_ID);
312        // The attachments of a specific message (query only) (insert & delete TBD)
313        matcher.addURI(EmailContent.AUTHORITY, "attachment/message/#",
314                ATTACHMENTS_MESSAGE_ID);
315
316        // All mail bodies
317        matcher.addURI(EmailContent.AUTHORITY, "body", BODY);
318        // A specific mail body
319        matcher.addURI(EmailContent.AUTHORITY, "body/#", BODY_ID);
320
321        // All hostauth records
322        matcher.addURI(EmailContent.AUTHORITY, "hostauth", HOSTAUTH);
323        // A specific hostauth
324        matcher.addURI(EmailContent.AUTHORITY, "hostauth/#", HOSTAUTH_ID);
325
326        // Atomically a constant value to a particular field of a mailbox/account
327        matcher.addURI(EmailContent.AUTHORITY, "mailboxIdAddToField/#",
328                MAILBOX_ID_ADD_TO_FIELD);
329        matcher.addURI(EmailContent.AUTHORITY, "accountIdAddToField/#",
330                ACCOUNT_ID_ADD_TO_FIELD);
331
332        /**
333         * THIS URI HAS SPECIAL SEMANTICS
334         * ITS USE IS INTENDED FOR THE UI APPLICATION TO MARK CHANGES THAT NEED TO BE SYNCED BACK
335         * TO A SERVER VIA A SYNC ADAPTER
336         */
337        matcher.addURI(EmailContent.AUTHORITY, "syncedMessage/#", SYNCED_MESSAGE_ID);
338
339        /**
340         * THE URIs BELOW THIS POINT ARE INTENDED TO BE USED BY SYNC ADAPTERS ONLY
341         * THEY REFER TO DATA CREATED AND MAINTAINED BY CALLS TO THE SYNCED_MESSAGE_ID URI
342         * BY THE UI APPLICATION
343         */
344        // All deleted messages
345        matcher.addURI(EmailContent.AUTHORITY, "deletedMessage", DELETED_MESSAGE);
346        // A specific deleted message
347        matcher.addURI(EmailContent.AUTHORITY, "deletedMessage/#", DELETED_MESSAGE_ID);
348
349        // All updated messages
350        matcher.addURI(EmailContent.AUTHORITY, "updatedMessage", UPDATED_MESSAGE);
351        // A specific updated message
352        matcher.addURI(EmailContent.AUTHORITY, "updatedMessage/#", UPDATED_MESSAGE_ID);
353
354        CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT = new ContentValues();
355        CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT.put(Account.NEW_MESSAGE_COUNT, 0);
356
357        matcher.addURI(EmailContent.AUTHORITY, "policy", POLICY);
358        matcher.addURI(EmailContent.AUTHORITY, "policy/#", POLICY_ID);
359    }
360
361
362    /**
363     * Wrap the UriMatcher call so we can throw a runtime exception if an unknown Uri is passed in
364     * @param uri the Uri to match
365     * @return the match value
366     */
367    private static int findMatch(Uri uri, String methodName) {
368        int match = sURIMatcher.match(uri);
369        if (match < 0) {
370            throw new IllegalArgumentException("Unknown uri: " + uri);
371        } else if (Email.LOGD) {
372            Log.v(TAG, methodName + ": uri=" + uri + ", match is " + match);
373        }
374        return match;
375    }
376
377    /*
378     * Internal helper method for index creation.
379     * Example:
380     * "create index message_" + MessageColumns.FLAG_READ
381     * + " on " + Message.TABLE_NAME + " (" + MessageColumns.FLAG_READ + ");"
382     */
383    /* package */
384    static String createIndex(String tableName, String columnName) {
385        return "create index " + tableName.toLowerCase() + '_' + columnName
386            + " on " + tableName + " (" + columnName + ");";
387    }
388
389    static void createMessageTable(SQLiteDatabase db) {
390        String messageColumns = MessageColumns.DISPLAY_NAME + " text, "
391            + MessageColumns.TIMESTAMP + " integer, "
392            + MessageColumns.SUBJECT + " text, "
393            + MessageColumns.FLAG_READ + " integer, "
394            + MessageColumns.FLAG_LOADED + " integer, "
395            + MessageColumns.FLAG_FAVORITE + " integer, "
396            + MessageColumns.FLAG_ATTACHMENT + " integer, "
397            + MessageColumns.FLAGS + " integer, "
398            + MessageColumns.CLIENT_ID + " integer, "
399            + MessageColumns.MESSAGE_ID + " text, "
400            + MessageColumns.MAILBOX_KEY + " integer, "
401            + MessageColumns.ACCOUNT_KEY + " integer, "
402            + MessageColumns.FROM_LIST + " text, "
403            + MessageColumns.TO_LIST + " text, "
404            + MessageColumns.CC_LIST + " text, "
405            + MessageColumns.BCC_LIST + " text, "
406            + MessageColumns.REPLY_TO_LIST + " text, "
407            + MessageColumns.MEETING_INFO + " text, "
408            + MessageColumns.SNIPPET + " text"
409            + ");";
410
411        // This String and the following String MUST have the same columns, except for the type
412        // of those columns!
413        String createString = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
414            + SyncColumns.SERVER_ID + " text, "
415            + SyncColumns.SERVER_TIMESTAMP + " integer, "
416            + messageColumns;
417
418        // For the updated and deleted tables, the id is assigned, but we do want to keep track
419        // of the ORDER of updates using an autoincrement primary key.  We use the DATA column
420        // at this point; it has no other function
421        String altCreateString = " (" + EmailContent.RECORD_ID + " integer unique, "
422            + SyncColumns.SERVER_ID + " text, "
423            + SyncColumns.SERVER_TIMESTAMP + " integer, "
424            + messageColumns;
425
426        // The three tables have the same schema
427        db.execSQL("create table " + Message.TABLE_NAME + createString);
428        db.execSQL("create table " + Message.UPDATED_TABLE_NAME + altCreateString);
429        db.execSQL("create table " + Message.DELETED_TABLE_NAME + altCreateString);
430
431        String indexColumns[] = {
432            MessageColumns.TIMESTAMP,
433            MessageColumns.FLAG_READ,
434            MessageColumns.FLAG_LOADED,
435            MessageColumns.MAILBOX_KEY,
436            SyncColumns.SERVER_ID
437        };
438
439        for (String columnName : indexColumns) {
440            db.execSQL(createIndex(Message.TABLE_NAME, columnName));
441        }
442
443        // Deleting a Message deletes all associated Attachments
444        // Deleting the associated Body cannot be done in a trigger, because the Body is stored
445        // in a separate database, and trigger cannot operate on attached databases.
446        db.execSQL("create trigger message_delete before delete on " + Message.TABLE_NAME +
447                " begin delete from " + Attachment.TABLE_NAME +
448                "  where " + AttachmentColumns.MESSAGE_KEY + "=old." + EmailContent.RECORD_ID +
449                "; end");
450
451        // Add triggers to keep unread count accurate per mailbox
452
453        // NOTE: SQLite's before triggers are not safe when recursive triggers are involved.
454        // Use caution when changing them.
455
456        // Insert a message; if flagRead is zero, add to the unread count of the message's mailbox
457        db.execSQL("create trigger unread_message_insert before insert on " + Message.TABLE_NAME +
458                " when NEW." + MessageColumns.FLAG_READ + "=0" +
459                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
460                '=' + MailboxColumns.UNREAD_COUNT + "+1" +
461                "  where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
462                "; end");
463
464        // Delete a message; if flagRead is zero, decrement the unread count of the msg's mailbox
465        db.execSQL("create trigger unread_message_delete before delete on " + Message.TABLE_NAME +
466                " when OLD." + MessageColumns.FLAG_READ + "=0" +
467                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
468                '=' + MailboxColumns.UNREAD_COUNT + "-1" +
469                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
470                "; end");
471
472        // Change a message's mailbox
473        db.execSQL("create trigger unread_message_move before update of " +
474                MessageColumns.MAILBOX_KEY + " on " + Message.TABLE_NAME +
475                " when OLD." + MessageColumns.FLAG_READ + "=0" +
476                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
477                '=' + MailboxColumns.UNREAD_COUNT + "-1" +
478                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
479                "; update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
480                '=' + MailboxColumns.UNREAD_COUNT + "+1" +
481                " where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
482                "; end");
483
484        // Change a message's read state
485        db.execSQL("create trigger unread_message_read before update of " +
486                MessageColumns.FLAG_READ + " on " + Message.TABLE_NAME +
487                " when OLD." + MessageColumns.FLAG_READ + "!=NEW." + MessageColumns.FLAG_READ +
488                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.UNREAD_COUNT +
489                '=' + MailboxColumns.UNREAD_COUNT + "+ case OLD." + MessageColumns.FLAG_READ +
490                " when 0 then -1 else 1 end" +
491                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
492                "; end");
493
494        // Add triggers to update message count per mailbox
495
496        // Insert a message.
497        db.execSQL("create trigger message_count_message_insert after insert on " +
498                Message.TABLE_NAME +
499                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
500                '=' + MailboxColumns.MESSAGE_COUNT + "+1" +
501                "  where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
502                "; end");
503
504        // Delete a message; if flagRead is zero, decrement the unread count of the msg's mailbox
505        db.execSQL("create trigger message_count_message_delete after delete on " +
506                Message.TABLE_NAME +
507                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
508                '=' + MailboxColumns.MESSAGE_COUNT + "-1" +
509                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
510                "; end");
511
512        // Change a message's mailbox
513        db.execSQL("create trigger message_count_message_move after update of " +
514                MessageColumns.MAILBOX_KEY + " on " + Message.TABLE_NAME +
515                " begin update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
516                '=' + MailboxColumns.MESSAGE_COUNT + "-1" +
517                "  where " + EmailContent.RECORD_ID + "=OLD." + MessageColumns.MAILBOX_KEY +
518                "; update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
519                '=' + MailboxColumns.MESSAGE_COUNT + "+1" +
520                " where " + EmailContent.RECORD_ID + "=NEW." + MessageColumns.MAILBOX_KEY +
521                "; end");
522    }
523
524    static void resetMessageTable(SQLiteDatabase db, int oldVersion, int newVersion) {
525        try {
526            db.execSQL("drop table " + Message.TABLE_NAME);
527            db.execSQL("drop table " + Message.UPDATED_TABLE_NAME);
528            db.execSQL("drop table " + Message.DELETED_TABLE_NAME);
529        } catch (SQLException e) {
530        }
531        createMessageTable(db);
532    }
533
534    @SuppressWarnings("deprecation")
535    static void createAccountTable(SQLiteDatabase db) {
536        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
537            + AccountColumns.DISPLAY_NAME + " text, "
538            + AccountColumns.EMAIL_ADDRESS + " text, "
539            + AccountColumns.SYNC_KEY + " text, "
540            + AccountColumns.SYNC_LOOKBACK + " integer, "
541            + AccountColumns.SYNC_INTERVAL + " text, "
542            + AccountColumns.HOST_AUTH_KEY_RECV + " integer, "
543            + AccountColumns.HOST_AUTH_KEY_SEND + " integer, "
544            + AccountColumns.FLAGS + " integer, "
545            + AccountColumns.IS_DEFAULT + " integer, "
546            + AccountColumns.COMPATIBILITY_UUID + " text, "
547            + AccountColumns.SENDER_NAME + " text, "
548            + AccountColumns.RINGTONE_URI + " text, "
549            + AccountColumns.PROTOCOL_VERSION + " text, "
550            + AccountColumns.NEW_MESSAGE_COUNT + " integer, "
551            + AccountColumns.SECURITY_FLAGS + " integer, "
552            + AccountColumns.SECURITY_SYNC_KEY + " text, "
553            + AccountColumns.SIGNATURE + " text, "
554            + AccountColumns.POLICY_KEY + " integer"
555            + ");";
556        db.execSQL("create table " + Account.TABLE_NAME + s);
557        // Deleting an account deletes associated Mailboxes and HostAuth's
558        db.execSQL(TRIGGER_ACCOUNT_DELETE);
559    }
560
561    static void resetAccountTable(SQLiteDatabase db, int oldVersion, int newVersion) {
562        try {
563            db.execSQL("drop table " +  Account.TABLE_NAME);
564        } catch (SQLException e) {
565        }
566        createAccountTable(db);
567    }
568
569    static void createPolicyTable(SQLiteDatabase db) {
570        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
571            + PolicyColumns.PASSWORD_MODE + " integer, "
572            + PolicyColumns.PASSWORD_MIN_LENGTH + " integer, "
573            + PolicyColumns.PASSWORD_EXPIRATION_DAYS + " integer, "
574            + PolicyColumns.PASSWORD_HISTORY + " integer, "
575            + PolicyColumns.PASSWORD_COMPLEX_CHARS + " integer, "
576            + PolicyColumns.PASSWORD_MAX_FAILS + " integer, "
577            + PolicyColumns.MAX_SCREEN_LOCK_TIME + " integer, "
578            + PolicyColumns.REQUIRE_REMOTE_WIPE + " integer, "
579            + PolicyColumns.REQUIRE_ENCRYPTION + " integer, "
580            + PolicyColumns.REQUIRE_ENCRYPTION_EXTERNAL + " integer, "
581            + PolicyColumns.REQUIRE_MANUAL_SYNC_WHEN_ROAMING + " integer, "
582            + PolicyColumns.DONT_ALLOW_CAMERA + " integer, "
583            + PolicyColumns.DONT_ALLOW_ATTACHMENTS + " integer, "
584            + PolicyColumns.DONT_ALLOW_HTML + " integer, "
585            + PolicyColumns.MAX_ATTACHMENT_SIZE + " integer, "
586            + PolicyColumns.MAX_TEXT_TRUNCATION_SIZE + " integer, "
587            + PolicyColumns.MAX_HTML_TRUNCATION_SIZE + " integer, "
588            + PolicyColumns.MAX_EMAIL_LOOKBACK + " integer, "
589            + PolicyColumns.MAX_CALENDAR_LOOKBACK + " integer, "
590            + PolicyColumns.PASSWORD_RECOVERY_ENABLED + " integer"
591            + ");";
592        db.execSQL("create table " + Policy.TABLE_NAME + s);
593    }
594
595    static void createHostAuthTable(SQLiteDatabase db) {
596        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
597            + HostAuthColumns.PROTOCOL + " text, "
598            + HostAuthColumns.ADDRESS + " text, "
599            + HostAuthColumns.PORT + " integer, "
600            + HostAuthColumns.FLAGS + " integer, "
601            + HostAuthColumns.LOGIN + " text, "
602            + HostAuthColumns.PASSWORD + " text, "
603            + HostAuthColumns.DOMAIN + " text, "
604            + HostAuthColumns.ACCOUNT_KEY + " integer"
605            + ");";
606        db.execSQL("create table " + HostAuth.TABLE_NAME + s);
607    }
608
609    static void resetHostAuthTable(SQLiteDatabase db, int oldVersion, int newVersion) {
610        try {
611            db.execSQL("drop table " + HostAuth.TABLE_NAME);
612        } catch (SQLException e) {
613        }
614        createHostAuthTable(db);
615    }
616
617    static void createMailboxTable(SQLiteDatabase db) {
618        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
619            + MailboxColumns.DISPLAY_NAME + " text, "
620            + MailboxColumns.SERVER_ID + " text, "
621            + MailboxColumns.PARENT_SERVER_ID + " text, "
622            + MailboxColumns.PARENT_KEY + " integer, "
623            + MailboxColumns.ACCOUNT_KEY + " integer, "
624            + MailboxColumns.TYPE + " integer, "
625            + MailboxColumns.DELIMITER + " integer, "
626            + MailboxColumns.SYNC_KEY + " text, "
627            + MailboxColumns.SYNC_LOOKBACK + " integer, "
628            + MailboxColumns.SYNC_INTERVAL + " integer, "
629            + MailboxColumns.SYNC_TIME + " integer, "
630            + MailboxColumns.UNREAD_COUNT + " integer, "
631            + MailboxColumns.FLAG_VISIBLE + " integer, "
632            + MailboxColumns.FLAGS + " integer, "
633            + MailboxColumns.VISIBLE_LIMIT + " integer, "
634            + MailboxColumns.SYNC_STATUS + " text, "
635            + MailboxColumns.MESSAGE_COUNT + " integer not null default 0, "
636            + MailboxColumns.LAST_SEEN_MESSAGE_KEY + " integer"
637            + ");";
638        db.execSQL("create table " + Mailbox.TABLE_NAME + s);
639        db.execSQL("create index mailbox_" + MailboxColumns.SERVER_ID
640                + " on " + Mailbox.TABLE_NAME + " (" + MailboxColumns.SERVER_ID + ")");
641        db.execSQL("create index mailbox_" + MailboxColumns.ACCOUNT_KEY
642                + " on " + Mailbox.TABLE_NAME + " (" + MailboxColumns.ACCOUNT_KEY + ")");
643        // Deleting a Mailbox deletes associated Messages in all three tables
644        db.execSQL(TRIGGER_MAILBOX_DELETE);
645    }
646
647    static void resetMailboxTable(SQLiteDatabase db, int oldVersion, int newVersion) {
648        try {
649            db.execSQL("drop table " + Mailbox.TABLE_NAME);
650        } catch (SQLException e) {
651        }
652        createMailboxTable(db);
653    }
654
655    static void createAttachmentTable(SQLiteDatabase db) {
656        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
657            + AttachmentColumns.FILENAME + " text, "
658            + AttachmentColumns.MIME_TYPE + " text, "
659            + AttachmentColumns.SIZE + " integer, "
660            + AttachmentColumns.CONTENT_ID + " text, "
661            + AttachmentColumns.CONTENT_URI + " text, "
662            + AttachmentColumns.MESSAGE_KEY + " integer, "
663            + AttachmentColumns.LOCATION + " text, "
664            + AttachmentColumns.ENCODING + " text, "
665            + AttachmentColumns.CONTENT + " text, "
666            + AttachmentColumns.FLAGS + " integer, "
667            + AttachmentColumns.CONTENT_BYTES + " blob, "
668            + AttachmentColumns.ACCOUNT_KEY + " integer"
669            + ");";
670        db.execSQL("create table " + Attachment.TABLE_NAME + s);
671        db.execSQL(createIndex(Attachment.TABLE_NAME, AttachmentColumns.MESSAGE_KEY));
672    }
673
674    static void resetAttachmentTable(SQLiteDatabase db, int oldVersion, int newVersion) {
675        try {
676            db.execSQL("drop table " + Attachment.TABLE_NAME);
677        } catch (SQLException e) {
678        }
679        createAttachmentTable(db);
680    }
681
682    static void createBodyTable(SQLiteDatabase db) {
683        String s = " (" + EmailContent.RECORD_ID + " integer primary key autoincrement, "
684            + BodyColumns.MESSAGE_KEY + " integer, "
685            + BodyColumns.HTML_CONTENT + " text, "
686            + BodyColumns.TEXT_CONTENT + " text, "
687            + BodyColumns.HTML_REPLY + " text, "
688            + BodyColumns.TEXT_REPLY + " text, "
689            + BodyColumns.SOURCE_MESSAGE_KEY + " text, "
690            + BodyColumns.INTRO_TEXT + " text"
691            + ");";
692        db.execSQL("create table " + Body.TABLE_NAME + s);
693        db.execSQL(createIndex(Body.TABLE_NAME, BodyColumns.MESSAGE_KEY));
694    }
695
696    static void upgradeBodyTable(SQLiteDatabase db, int oldVersion, int newVersion) {
697        if (oldVersion < 5) {
698            try {
699                db.execSQL("drop table " + Body.TABLE_NAME);
700                createBodyTable(db);
701            } catch (SQLException e) {
702            }
703        } else if (oldVersion == 5) {
704            try {
705                db.execSQL("alter table " + Body.TABLE_NAME
706                        + " add " + BodyColumns.INTRO_TEXT + " text");
707            } catch (SQLException e) {
708                // Shouldn't be needed unless we're debugging and interrupt the process
709                Log.w(TAG, "Exception upgrading EmailProviderBody.db from v5 to v6", e);
710            }
711            oldVersion = 6;
712        }
713    }
714
715    private SQLiteDatabase mDatabase;
716    private SQLiteDatabase mBodyDatabase;
717
718    public synchronized SQLiteDatabase getDatabase(Context context) {
719        // Always return the cached database, if we've got one
720        if (mDatabase != null) {
721            return mDatabase;
722        }
723
724        // Whenever we create or re-cache the databases, make sure that we haven't lost one
725        // to corruption
726        checkDatabases();
727
728        DatabaseHelper helper = new DatabaseHelper(context, DATABASE_NAME);
729        mDatabase = helper.getWritableDatabase();
730        if (mDatabase != null) {
731            mDatabase.setLockingEnabled(true);
732            BodyDatabaseHelper bodyHelper = new BodyDatabaseHelper(context, BODY_DATABASE_NAME);
733            mBodyDatabase = bodyHelper.getWritableDatabase();
734            if (mBodyDatabase != null) {
735                mBodyDatabase.setLockingEnabled(true);
736                String bodyFileName = mBodyDatabase.getPath();
737                mDatabase.execSQL("attach \"" + bodyFileName + "\" as BodyDatabase");
738            }
739        }
740
741        // Check for any orphaned Messages in the updated/deleted tables
742        deleteOrphans(mDatabase, Message.UPDATED_TABLE_NAME);
743        deleteOrphans(mDatabase, Message.DELETED_TABLE_NAME);
744
745        return mDatabase;
746    }
747
748    /*package*/ static SQLiteDatabase getReadableDatabase(Context context) {
749        DatabaseHelper helper = new EmailProvider().new DatabaseHelper(context, DATABASE_NAME);
750        return helper.getReadableDatabase();
751    }
752
753    /** {@inheritDoc} */
754    @Override
755    public void shutdown() {
756        if (mDatabase != null) {
757            mDatabase.close();
758            mDatabase = null;
759        }
760        if (mBodyDatabase != null) {
761            mBodyDatabase.close();
762            mBodyDatabase = null;
763        }
764    }
765
766    /*package*/ static void deleteOrphans(SQLiteDatabase database, String tableName) {
767        if (database != null) {
768            // We'll look at all of the items in the table; there won't be many typically
769            Cursor c = database.query(tableName, ORPHANS_PROJECTION, null, null, null, null, null);
770            // Usually, there will be nothing in these tables, so make a quick check
771            try {
772                if (c.getCount() == 0) return;
773                ArrayList<Long> foundMailboxes = new ArrayList<Long>();
774                ArrayList<Long> notFoundMailboxes = new ArrayList<Long>();
775                ArrayList<Long> deleteList = new ArrayList<Long>();
776                String[] bindArray = new String[1];
777                while (c.moveToNext()) {
778                    // Get the mailbox key and see if we've already found this mailbox
779                    // If so, we're fine
780                    long mailboxId = c.getLong(ORPHANS_MAILBOX_KEY);
781                    // If we already know this mailbox doesn't exist, mark the message for deletion
782                    if (notFoundMailboxes.contains(mailboxId)) {
783                        deleteList.add(c.getLong(ORPHANS_ID));
784                    // If we don't know about this mailbox, we'll try to find it
785                    } else if (!foundMailboxes.contains(mailboxId)) {
786                        bindArray[0] = Long.toString(mailboxId);
787                        Cursor boxCursor = database.query(Mailbox.TABLE_NAME,
788                                Mailbox.ID_PROJECTION, WHERE_ID, bindArray, null, null, null);
789                        try {
790                            // If it exists, we'll add it to the "found" mailboxes
791                            if (boxCursor.moveToFirst()) {
792                                foundMailboxes.add(mailboxId);
793                            // Otherwise, we'll add to "not found" and mark the message for deletion
794                            } else {
795                                notFoundMailboxes.add(mailboxId);
796                                deleteList.add(c.getLong(ORPHANS_ID));
797                            }
798                        } finally {
799                            boxCursor.close();
800                        }
801                    }
802                }
803                // Now, delete the orphan messages
804                for (long messageId: deleteList) {
805                    bindArray[0] = Long.toString(messageId);
806                    database.delete(tableName, WHERE_ID, bindArray);
807                }
808            } finally {
809                c.close();
810            }
811        }
812    }
813
814    private class BodyDatabaseHelper extends SQLiteOpenHelper {
815        BodyDatabaseHelper(Context context, String name) {
816            super(context, name, null, BODY_DATABASE_VERSION);
817        }
818
819        @Override
820        public void onCreate(SQLiteDatabase db) {
821            Log.d(TAG, "Creating EmailProviderBody database");
822            createBodyTable(db);
823        }
824
825        @Override
826        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
827            upgradeBodyTable(db, oldVersion, newVersion);
828        }
829
830        @Override
831        public void onOpen(SQLiteDatabase db) {
832        }
833    }
834
835    private class DatabaseHelper extends SQLiteOpenHelper {
836        Context mContext;
837
838        DatabaseHelper(Context context, String name) {
839            super(context, name, null, DATABASE_VERSION);
840            mContext = context;
841        }
842
843        @Override
844        public void onCreate(SQLiteDatabase db) {
845            Log.d(TAG, "Creating EmailProvider database");
846            // Create all tables here; each class has its own method
847            createMessageTable(db);
848            createAttachmentTable(db);
849            createMailboxTable(db);
850            createHostAuthTable(db);
851            createAccountTable(db);
852            createPolicyTable(db);
853        }
854
855        @Override
856        @SuppressWarnings("deprecation")
857        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
858            // For versions prior to 5, delete all data
859            // Versions >= 5 require that data be preserved!
860            if (oldVersion < 5) {
861                android.accounts.Account[] accounts = AccountManager.get(mContext)
862                        .getAccountsByType(AccountManagerTypes.TYPE_EXCHANGE);
863                for (android.accounts.Account account: accounts) {
864                    AccountManager.get(mContext).removeAccount(account, null, null);
865                }
866                resetMessageTable(db, oldVersion, newVersion);
867                resetAttachmentTable(db, oldVersion, newVersion);
868                resetMailboxTable(db, oldVersion, newVersion);
869                resetHostAuthTable(db, oldVersion, newVersion);
870                resetAccountTable(db, oldVersion, newVersion);
871                return;
872            }
873            if (oldVersion == 5) {
874                // Message Tables: Add SyncColumns.SERVER_TIMESTAMP
875                try {
876                    db.execSQL("alter table " + Message.TABLE_NAME
877                            + " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
878                    db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
879                            + " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
880                    db.execSQL("alter table " + Message.DELETED_TABLE_NAME
881                            + " add column " + SyncColumns.SERVER_TIMESTAMP + " integer" + ";");
882                } catch (SQLException e) {
883                    // Shouldn't be needed unless we're debugging and interrupt the process
884                    Log.w(TAG, "Exception upgrading EmailProvider.db from v5 to v6", e);
885                }
886                oldVersion = 6;
887            }
888            if (oldVersion == 6) {
889                // Use the newer mailbox_delete trigger
890                db.execSQL("drop trigger mailbox_delete;");
891                db.execSQL(TRIGGER_MAILBOX_DELETE);
892                oldVersion = 7;
893            }
894            if (oldVersion == 7) {
895                // add the security (provisioning) column
896                try {
897                    db.execSQL("alter table " + Account.TABLE_NAME
898                            + " add column " + AccountColumns.SECURITY_FLAGS + " integer" + ";");
899                } catch (SQLException e) {
900                    // Shouldn't be needed unless we're debugging and interrupt the process
901                    Log.w(TAG, "Exception upgrading EmailProvider.db from 7 to 8 " + e);
902                }
903                oldVersion = 8;
904            }
905            if (oldVersion == 8) {
906                // accounts: add security sync key & user signature columns
907                try {
908                    db.execSQL("alter table " + Account.TABLE_NAME
909                            + " add column " + AccountColumns.SECURITY_SYNC_KEY + " text" + ";");
910                    db.execSQL("alter table " + Account.TABLE_NAME
911                            + " add column " + AccountColumns.SIGNATURE + " text" + ";");
912                } catch (SQLException e) {
913                    // Shouldn't be needed unless we're debugging and interrupt the process
914                    Log.w(TAG, "Exception upgrading EmailProvider.db from 8 to 9 " + e);
915                }
916                oldVersion = 9;
917            }
918            if (oldVersion == 9) {
919                // Message: add meeting info column into Message tables
920                try {
921                    db.execSQL("alter table " + Message.TABLE_NAME
922                            + " add column " + MessageColumns.MEETING_INFO + " text" + ";");
923                    db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
924                            + " add column " + MessageColumns.MEETING_INFO + " text" + ";");
925                    db.execSQL("alter table " + Message.DELETED_TABLE_NAME
926                            + " add column " + MessageColumns.MEETING_INFO + " text" + ";");
927                } catch (SQLException e) {
928                    // Shouldn't be needed unless we're debugging and interrupt the process
929                    Log.w(TAG, "Exception upgrading EmailProvider.db from 9 to 10 " + e);
930                }
931                oldVersion = 10;
932            }
933            if (oldVersion == 10) {
934                // Attachment: add content and flags columns
935                try {
936                    db.execSQL("alter table " + Attachment.TABLE_NAME
937                            + " add column " + AttachmentColumns.CONTENT + " text" + ";");
938                    db.execSQL("alter table " + Attachment.TABLE_NAME
939                            + " add column " + AttachmentColumns.FLAGS + " integer" + ";");
940                } catch (SQLException e) {
941                    // Shouldn't be needed unless we're debugging and interrupt the process
942                    Log.w(TAG, "Exception upgrading EmailProvider.db from 10 to 11 " + e);
943                }
944                oldVersion = 11;
945            }
946            if (oldVersion == 11) {
947                // Attachment: add content_bytes
948                try {
949                    db.execSQL("alter table " + Attachment.TABLE_NAME
950                            + " add column " + AttachmentColumns.CONTENT_BYTES + " blob" + ";");
951                } catch (SQLException e) {
952                    // Shouldn't be needed unless we're debugging and interrupt the process
953                    Log.w(TAG, "Exception upgrading EmailProvider.db from 11 to 12 " + e);
954                }
955                oldVersion = 12;
956            }
957            if (oldVersion == 12) {
958                try {
959                    db.execSQL("alter table " + Mailbox.TABLE_NAME
960                            + " add column " + Mailbox.MESSAGE_COUNT
961                                    +" integer not null default 0" + ";");
962                    recalculateMessageCount(db);
963                } catch (SQLException e) {
964                    // Shouldn't be needed unless we're debugging and interrupt the process
965                    Log.w(TAG, "Exception upgrading EmailProvider.db from 12 to 13 " + e);
966                }
967                oldVersion = 13;
968            }
969            if (oldVersion == 13) {
970                try {
971                    db.execSQL("alter table " + Message.TABLE_NAME
972                            + " add column " + Message.SNIPPET
973                                    +" text" + ";");
974                } catch (SQLException e) {
975                    // Shouldn't be needed unless we're debugging and interrupt the process
976                    Log.w(TAG, "Exception upgrading EmailProvider.db from 13 to 14 " + e);
977                }
978                oldVersion = 14;
979            }
980            if (oldVersion == 14) {
981                try {
982                    db.execSQL("alter table " + Message.DELETED_TABLE_NAME
983                            + " add column " + Message.SNIPPET +" text" + ";");
984                    db.execSQL("alter table " + Message.UPDATED_TABLE_NAME
985                            + " add column " + Message.SNIPPET +" text" + ";");
986                } catch (SQLException e) {
987                    // Shouldn't be needed unless we're debugging and interrupt the process
988                    Log.w(TAG, "Exception upgrading EmailProvider.db from 14 to 15 " + e);
989                }
990                oldVersion = 15;
991            }
992            if (oldVersion == 15) {
993                try {
994                    db.execSQL("alter table " + Attachment.TABLE_NAME
995                            + " add column " + Attachment.ACCOUNT_KEY +" integer" + ";");
996                    // Update all existing attachments to add the accountKey data
997                    db.execSQL("update " + Attachment.TABLE_NAME + " set " +
998                            Attachment.ACCOUNT_KEY + "= (SELECT " + Message.TABLE_NAME + "." +
999                            Message.ACCOUNT_KEY + " from " + Message.TABLE_NAME + " where " +
1000                            Message.TABLE_NAME + "." + Message.RECORD_ID + " = " +
1001                            Attachment.TABLE_NAME + "." + Attachment.MESSAGE_KEY + ")");
1002                } catch (SQLException e) {
1003                    // Shouldn't be needed unless we're debugging and interrupt the process
1004                    Log.w(TAG, "Exception upgrading EmailProvider.db from 15 to 16 " + e);
1005                }
1006                oldVersion = 16;
1007            }
1008            if (oldVersion == 16) {
1009                try {
1010                    db.execSQL("alter table " + Mailbox.TABLE_NAME
1011                            + " add column " + Mailbox.PARENT_KEY + " integer;");
1012                } catch (SQLException e) {
1013                    // Shouldn't be needed unless we're debugging and interrupt the process
1014                    Log.w(TAG, "Exception upgrading EmailProvider.db from 16 to 17 " + e);
1015                }
1016                oldVersion = 17;
1017            }
1018            if (oldVersion == 17) {
1019                upgradeFromVersion17ToVersion18(db);
1020                oldVersion = 18;
1021            }
1022            if (oldVersion == 18) {
1023                try {
1024                    db.execSQL("alter table " + Account.TABLE_NAME
1025                            + " add column " + Account.POLICY_KEY + " integer;");
1026                    db.execSQL("drop trigger account_delete;");
1027                    db.execSQL(TRIGGER_ACCOUNT_DELETE);
1028                    createPolicyTable(db);
1029                    convertPolicyFlagsToPolicyTable(db);
1030                } catch (SQLException e) {
1031                    // Shouldn't be needed unless we're debugging and interrupt the process
1032                    Log.w(TAG, "Exception upgrading EmailProvider.db from 18 to 19 " + e);
1033                }
1034                oldVersion = 19;
1035            }
1036            if (oldVersion == 19) {
1037                try {
1038                    db.execSQL("alter table " + Policy.TABLE_NAME
1039                            + " add column " + PolicyColumns.REQUIRE_MANUAL_SYNC_WHEN_ROAMING +
1040                            " integer;");
1041                    db.execSQL("alter table " + Policy.TABLE_NAME
1042                            + " add column " + PolicyColumns.DONT_ALLOW_CAMERA + " integer;");
1043                    db.execSQL("alter table " + Policy.TABLE_NAME
1044                            + " add column " + PolicyColumns.DONT_ALLOW_ATTACHMENTS + " integer;");
1045                    db.execSQL("alter table " + Policy.TABLE_NAME
1046                            + " add column " + PolicyColumns.DONT_ALLOW_HTML + " integer;");
1047                    db.execSQL("alter table " + Policy.TABLE_NAME
1048                            + " add column " + PolicyColumns.MAX_ATTACHMENT_SIZE + " integer;");
1049                    db.execSQL("alter table " + Policy.TABLE_NAME
1050                            + " add column " + PolicyColumns.MAX_TEXT_TRUNCATION_SIZE +
1051                            " integer;");
1052                    db.execSQL("alter table " + Policy.TABLE_NAME
1053                            + " add column " + PolicyColumns.MAX_HTML_TRUNCATION_SIZE +
1054                            " integer;");
1055                    db.execSQL("alter table " + Policy.TABLE_NAME
1056                            + " add column " + PolicyColumns.MAX_EMAIL_LOOKBACK + " integer;");
1057                    db.execSQL("alter table " + Policy.TABLE_NAME
1058                            + " add column " + PolicyColumns.MAX_CALENDAR_LOOKBACK + " integer;");
1059                    db.execSQL("alter table " + Policy.TABLE_NAME
1060                            + " add column " + PolicyColumns.PASSWORD_RECOVERY_ENABLED +
1061                            " integer;");
1062                } catch (SQLException e) {
1063                    // Shouldn't be needed unless we're debugging and interrupt the process
1064                    Log.w(TAG, "Exception upgrading EmailProvider.db from 19 to 20 " + e);
1065                }
1066                oldVersion = 20;
1067            }
1068            if (oldVersion == 20) {
1069                upgradeFromVersion20ToVersion21(db);
1070                oldVersion = 21;
1071            }
1072        }
1073
1074        @Override
1075        public void onOpen(SQLiteDatabase db) {
1076        }
1077    }
1078
1079    @Override
1080    public int delete(Uri uri, String selection, String[] selectionArgs) {
1081        final int match = findMatch(uri, "delete");
1082        Context context = getContext();
1083        // Pick the correct database for this operation
1084        // If we're in a transaction already (which would happen during applyBatch), then the
1085        // body database is already attached to the email database and any attempt to use the
1086        // body database directly will result in a SQLiteException (the database is locked)
1087        SQLiteDatabase db = getDatabase(context);
1088        int table = match >> BASE_SHIFT;
1089        String id = "0";
1090        boolean messageDeletion = false;
1091        ContentResolver resolver = context.getContentResolver();
1092
1093        ContentCache cache = CONTENT_CACHES[table];
1094        String tableName = TABLE_NAMES[table];
1095        int result = -1;
1096
1097        try {
1098            switch (match) {
1099                // These are cases in which one or more Messages might get deleted, either by
1100                // cascade or explicitly
1101                case MAILBOX_ID:
1102                case MAILBOX:
1103                case ACCOUNT_ID:
1104                case ACCOUNT:
1105                case MESSAGE:
1106                case SYNCED_MESSAGE_ID:
1107                case MESSAGE_ID:
1108                    // Handle lost Body records here, since this cannot be done in a trigger
1109                    // The process is:
1110                    //  1) Begin a transaction, ensuring that both databases are affected atomically
1111                    //  2) Do the requested deletion, with cascading deletions handled in triggers
1112                    //  3) End the transaction, committing all changes atomically
1113                    //
1114                    // Bodies are auto-deleted here;  Attachments are auto-deleted via trigger
1115                    messageDeletion = true;
1116                    db.beginTransaction();
1117                    break;
1118            }
1119            switch (match) {
1120                case BODY_ID:
1121                case DELETED_MESSAGE_ID:
1122                case SYNCED_MESSAGE_ID:
1123                case MESSAGE_ID:
1124                case UPDATED_MESSAGE_ID:
1125                case ATTACHMENT_ID:
1126                case MAILBOX_ID:
1127                case ACCOUNT_ID:
1128                case HOSTAUTH_ID:
1129                case POLICY_ID:
1130                    id = uri.getPathSegments().get(1);
1131                    if (match == SYNCED_MESSAGE_ID) {
1132                        // For synced messages, first copy the old message to the deleted table and
1133                        // delete it from the updated table (in case it was updated first)
1134                        // Note that this is all within a transaction, for atomicity
1135                        db.execSQL(DELETED_MESSAGE_INSERT + id);
1136                        db.execSQL(UPDATED_MESSAGE_DELETE + id);
1137                    }
1138                    if (cache != null) {
1139                        cache.lock(id);
1140                    }
1141                    try {
1142                        result = db.delete(tableName, whereWithId(id, selection), selectionArgs);
1143                        if (cache != null) {
1144                            switch(match) {
1145                                case ACCOUNT_ID:
1146                                    // Account deletion will clear all of the caches, as HostAuth's,
1147                                    // Mailboxes, and Messages will be deleted in the process
1148                                    sCacheMailbox.invalidate("Delete", uri, selection);
1149                                    sCacheHostAuth.invalidate("Delete", uri, selection);
1150                                    //$FALL-THROUGH$
1151                                case MAILBOX_ID:
1152                                    // Mailbox deletion will clear the Message cache
1153                                    sCacheMessage.invalidate("Delete", uri, selection);
1154                                    //$FALL-THROUGH$
1155                                case SYNCED_MESSAGE_ID:
1156                                case MESSAGE_ID:
1157                                case HOSTAUTH_ID:
1158                                    cache.invalidate("Delete", uri, selection);
1159                                    break;
1160                            }
1161                        }
1162                    } finally {
1163                        if (cache != null) {
1164                            cache.unlock(id);
1165                        }
1166                    }
1167                    break;
1168                case ATTACHMENTS_MESSAGE_ID:
1169                    // All attachments for the given message
1170                    id = uri.getPathSegments().get(2);
1171                    result = db.delete(tableName,
1172                            whereWith(Attachment.MESSAGE_KEY + "=" + id, selection), selectionArgs);
1173                    break;
1174
1175                case BODY:
1176                case MESSAGE:
1177                case DELETED_MESSAGE:
1178                case UPDATED_MESSAGE:
1179                case ATTACHMENT:
1180                case MAILBOX:
1181                case ACCOUNT:
1182                case HOSTAUTH:
1183                case POLICY:
1184                    switch(match) {
1185                        // See the comments above for deletion of ACCOUNT_ID, etc
1186                        case ACCOUNT:
1187                            sCacheMailbox.invalidate("Delete", uri, selection);
1188                            sCacheHostAuth.invalidate("Delete", uri, selection);
1189                            //$FALL-THROUGH$
1190                        case MAILBOX:
1191                            sCacheMessage.invalidate("Delete", uri, selection);
1192                            //$FALL-THROUGH$
1193                        case MESSAGE:
1194                        case HOSTAUTH:
1195                            cache.invalidate("Delete", uri, selection);
1196                            break;
1197                    }
1198                    result = db.delete(tableName, selection, selectionArgs);
1199                    break;
1200
1201                default:
1202                    throw new IllegalArgumentException("Unknown URI " + uri);
1203            }
1204            if (messageDeletion) {
1205                if (match == MESSAGE_ID) {
1206                    // Delete the Body record associated with the deleted message
1207                    db.execSQL(DELETE_BODY + id);
1208                } else {
1209                    // Delete any orphaned Body records
1210                    db.execSQL(DELETE_ORPHAN_BODIES);
1211                }
1212                db.setTransactionSuccessful();
1213            }
1214        } catch (SQLiteException e) {
1215            checkDatabases();
1216            throw e;
1217        } finally {
1218            if (messageDeletion) {
1219                db.endTransaction();
1220            }
1221        }
1222
1223        // Notify all notifier cursors
1224        sendNotifierChange(getBaseNotificationUri(match), NOTIFICATION_OP_DELETE, id);
1225
1226        // Notify all email content cursors
1227        resolver.notifyChange(EmailContent.CONTENT_URI, null);
1228        return result;
1229    }
1230
1231    @Override
1232    // Use the email- prefix because message, mailbox, and account are so generic (e.g. SMS, IM)
1233    public String getType(Uri uri) {
1234        int match = findMatch(uri, "getType");
1235        switch (match) {
1236            case BODY_ID:
1237                return "vnd.android.cursor.item/email-body";
1238            case BODY:
1239                return "vnd.android.cursor.dir/email-body";
1240            case UPDATED_MESSAGE_ID:
1241            case MESSAGE_ID:
1242                // NOTE: According to the framework folks, we're supposed to invent mime types as
1243                // a way of passing information to drag & drop recipients.
1244                // If there's a mailboxId parameter in the url, we respond with a mime type that
1245                // has -n appended, where n is the mailboxId of the message.  The drag & drop code
1246                // uses this information to know not to allow dragging the item to its own mailbox
1247                String mimeType = EMAIL_MESSAGE_MIME_TYPE;
1248                String mailboxId = uri.getQueryParameter(MESSAGE_URI_PARAMETER_MAILBOX_ID);
1249                if (mailboxId != null) {
1250                    mimeType += "-" + mailboxId;
1251                }
1252                return mimeType;
1253            case UPDATED_MESSAGE:
1254            case MESSAGE:
1255                return "vnd.android.cursor.dir/email-message";
1256            case MAILBOX:
1257                return "vnd.android.cursor.dir/email-mailbox";
1258            case MAILBOX_ID:
1259                return "vnd.android.cursor.item/email-mailbox";
1260            case ACCOUNT:
1261                return "vnd.android.cursor.dir/email-account";
1262            case ACCOUNT_ID:
1263                return "vnd.android.cursor.item/email-account";
1264            case ATTACHMENTS_MESSAGE_ID:
1265            case ATTACHMENT:
1266                return "vnd.android.cursor.dir/email-attachment";
1267            case ATTACHMENT_ID:
1268                return EMAIL_ATTACHMENT_MIME_TYPE;
1269            case HOSTAUTH:
1270                return "vnd.android.cursor.dir/email-hostauth";
1271            case HOSTAUTH_ID:
1272                return "vnd.android.cursor.item/email-hostauth";
1273            default:
1274                throw new IllegalArgumentException("Unknown URI " + uri);
1275        }
1276    }
1277
1278    @Override
1279    public Uri insert(Uri uri, ContentValues values) {
1280        int match = findMatch(uri, "insert");
1281        Context context = getContext();
1282        ContentResolver resolver = context.getContentResolver();
1283
1284        // See the comment at delete(), above
1285        SQLiteDatabase db = getDatabase(context);
1286        int table = match >> BASE_SHIFT;
1287        String id = "0";
1288        long longId;
1289
1290        // We do NOT allow setting of unreadCount/messageCount via the provider
1291        // These columns are maintained via triggers
1292        if (match == MAILBOX_ID || match == MAILBOX) {
1293            values.put(MailboxColumns.UNREAD_COUNT, 0);
1294            values.put(MailboxColumns.MESSAGE_COUNT, 0);
1295        }
1296
1297        Uri resultUri = null;
1298
1299        try {
1300            switch (match) {
1301                case MESSAGE:
1302                case UPDATED_MESSAGE:
1303                case DELETED_MESSAGE:
1304                case BODY:
1305                case ATTACHMENT:
1306                case MAILBOX:
1307                case ACCOUNT:
1308                case HOSTAUTH:
1309                case POLICY:
1310                    longId = db.insert(TABLE_NAMES[table], "foo", values);
1311                    resultUri = ContentUris.withAppendedId(uri, longId);
1312                    // Clients shouldn't normally be adding rows to these tables, as they are
1313                    // maintained by triggers.  However, we need to be able to do this for unit
1314                    // testing, so we allow the insert and then throw the same exception that we
1315                    // would if this weren't allowed.
1316                    if (match == UPDATED_MESSAGE || match == DELETED_MESSAGE) {
1317                        throw new IllegalArgumentException("Unknown URL " + uri);
1318                    }
1319                    if (match == ATTACHMENT) {
1320                        int flags = 0;
1321                        if (values.containsKey(Attachment.FLAGS)) {
1322                            flags = values.getAsInteger(Attachment.FLAGS);
1323                        }
1324                        // Report all new attachments to the download service
1325                        AttachmentDownloadService.attachmentChanged(longId, flags);
1326                    }
1327                    break;
1328                case MAILBOX_ID:
1329                    // This implies adding a message to a mailbox
1330                    // Hmm, a problem here is that we can't link the account as well, so it must be
1331                    // already in the values...
1332                    longId = Long.parseLong(uri.getPathSegments().get(1));
1333                    values.put(MessageColumns.MAILBOX_KEY, longId);
1334                    return insert(Message.CONTENT_URI, values); // Recurse
1335                case MESSAGE_ID:
1336                    // This implies adding an attachment to a message.
1337                    id = uri.getPathSegments().get(1);
1338                    longId = Long.parseLong(id);
1339                    values.put(AttachmentColumns.MESSAGE_KEY, longId);
1340                    return insert(Attachment.CONTENT_URI, values); // Recurse
1341                case ACCOUNT_ID:
1342                    // This implies adding a mailbox to an account.
1343                    longId = Long.parseLong(uri.getPathSegments().get(1));
1344                    values.put(MailboxColumns.ACCOUNT_KEY, longId);
1345                    return insert(Mailbox.CONTENT_URI, values); // Recurse
1346                case ATTACHMENTS_MESSAGE_ID:
1347                    longId = db.insert(TABLE_NAMES[table], "foo", values);
1348                    resultUri = ContentUris.withAppendedId(Attachment.CONTENT_URI, longId);
1349                    break;
1350                default:
1351                    throw new IllegalArgumentException("Unknown URL " + uri);
1352            }
1353        } catch (SQLiteException e) {
1354            checkDatabases();
1355            throw e;
1356        }
1357
1358        // Notify all notifier cursors
1359        sendNotifierChange(getBaseNotificationUri(match), NOTIFICATION_OP_INSERT, id);
1360
1361        // Notify all existing cursors.
1362        resolver.notifyChange(EmailContent.CONTENT_URI, null);
1363        return resultUri;
1364    }
1365
1366    @Override
1367    public boolean onCreate() {
1368        checkDatabases();
1369        return false;
1370    }
1371
1372    /**
1373     * The idea here is that the two databases (EmailProvider.db and EmailProviderBody.db must
1374     * always be in sync (i.e. there are two database or NO databases).  This code will delete
1375     * any "orphan" database, so that both will be created together.  Note that an "orphan" database
1376     * will exist after either of the individual databases is deleted due to data corruption.
1377     */
1378    public void checkDatabases() {
1379        // Uncache the databases
1380        if (mDatabase != null) {
1381            mDatabase = null;
1382        }
1383        if (mBodyDatabase != null) {
1384            mBodyDatabase = null;
1385        }
1386        // Look for orphans, and delete as necessary; these must always be in sync
1387        File databaseFile = getContext().getDatabasePath(DATABASE_NAME);
1388        File bodyFile = getContext().getDatabasePath(BODY_DATABASE_NAME);
1389
1390        // TODO Make sure attachments are deleted
1391        if (databaseFile.exists() && !bodyFile.exists()) {
1392            Log.w(TAG, "Deleting orphaned EmailProvider database...");
1393            databaseFile.delete();
1394        } else if (bodyFile.exists() && !databaseFile.exists()) {
1395            Log.w(TAG, "Deleting orphaned EmailProviderBody database...");
1396            bodyFile.delete();
1397        }
1398    }
1399
1400    @Override
1401    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
1402            String sortOrder) {
1403        long time = 0L;
1404        if (Email.DEBUG) {
1405            time = System.nanoTime();
1406        }
1407        Cursor c = null;
1408        int match;
1409        try {
1410            match = findMatch(uri, "query");
1411        } catch (IllegalArgumentException e) {
1412            String uriString = uri.toString();
1413            // If we were passed an illegal uri, see if it ends in /-1
1414            // if so, and if substituting 0 for -1 results in a valid uri, return an empty cursor
1415            if (uriString != null && uriString.endsWith("/-1")) {
1416                uri = Uri.parse(uriString.substring(0, uriString.length() - 2) + "0");
1417                match = findMatch(uri, "query");
1418                switch (match) {
1419                    case BODY_ID:
1420                    case MESSAGE_ID:
1421                    case DELETED_MESSAGE_ID:
1422                    case UPDATED_MESSAGE_ID:
1423                    case ATTACHMENT_ID:
1424                    case MAILBOX_ID:
1425                    case ACCOUNT_ID:
1426                    case HOSTAUTH_ID:
1427                    case POLICY_ID:
1428                        return new MatrixCursor(projection, 0);
1429                }
1430            }
1431            throw e;
1432        }
1433        Context context = getContext();
1434        // See the comment at delete(), above
1435        SQLiteDatabase db = getDatabase(context);
1436        int table = match >> BASE_SHIFT;
1437        String limit = uri.getQueryParameter(EmailContent.PARAMETER_LIMIT);
1438        String id;
1439
1440        // Find the cache for this query's table (if any)
1441        ContentCache cache = null;
1442        String tableName = TABLE_NAMES[table];
1443        // We can only use the cache if there's no selection
1444        if (selection == null) {
1445            cache = CONTENT_CACHES[table];
1446        }
1447        if (cache == null) {
1448            ContentCache.notCacheable(uri, selection);
1449        }
1450
1451        try {
1452            switch (match) {
1453                case BODY:
1454                case MESSAGE:
1455                case UPDATED_MESSAGE:
1456                case DELETED_MESSAGE:
1457                case ATTACHMENT:
1458                case MAILBOX:
1459                case ACCOUNT:
1460                case HOSTAUTH:
1461                case POLICY:
1462                    c = db.query(tableName, projection,
1463                            selection, selectionArgs, null, null, sortOrder, limit);
1464                    break;
1465                case BODY_ID:
1466                case MESSAGE_ID:
1467                case DELETED_MESSAGE_ID:
1468                case UPDATED_MESSAGE_ID:
1469                case ATTACHMENT_ID:
1470                case MAILBOX_ID:
1471                case ACCOUNT_ID:
1472                case HOSTAUTH_ID:
1473                case POLICY_ID:
1474                    id = uri.getPathSegments().get(1);
1475                    if (cache != null) {
1476                        c = cache.getCachedCursor(id, projection);
1477                    }
1478                    if (c == null) {
1479                        CacheToken token = null;
1480                        if (cache != null) {
1481                            token = cache.getCacheToken(id);
1482                        }
1483                        c = db.query(tableName, projection, whereWithId(id, selection),
1484                                selectionArgs, null, null, sortOrder, limit);
1485                        if (cache != null) {
1486                            c = cache.putCursor(c, id, projection, token);
1487                        }
1488                    }
1489                    break;
1490                case ATTACHMENTS_MESSAGE_ID:
1491                    // All attachments for the given message
1492                    id = uri.getPathSegments().get(2);
1493                    c = db.query(Attachment.TABLE_NAME, projection,
1494                            whereWith(Attachment.MESSAGE_KEY + "=" + id, selection),
1495                            selectionArgs, null, null, sortOrder, limit);
1496                    break;
1497                default:
1498                    throw new IllegalArgumentException("Unknown URI " + uri);
1499            }
1500        } catch (SQLiteException e) {
1501            checkDatabases();
1502            throw e;
1503        } catch (RuntimeException e) {
1504            checkDatabases();
1505            e.printStackTrace();
1506            throw e;
1507        } finally {
1508            if (cache != null && Email.DEBUG) {
1509                cache.recordQueryTime(c, System.nanoTime() - time);
1510            }
1511        }
1512
1513        if ((c != null) && !isTemporary()) {
1514            c.setNotificationUri(getContext().getContentResolver(), uri);
1515        }
1516        return c;
1517    }
1518
1519    private String whereWithId(String id, String selection) {
1520        StringBuilder sb = new StringBuilder(256);
1521        sb.append("_id=");
1522        sb.append(id);
1523        if (selection != null) {
1524            sb.append(" AND (");
1525            sb.append(selection);
1526            sb.append(')');
1527        }
1528        return sb.toString();
1529    }
1530
1531    /**
1532     * Combine a locally-generated selection with a user-provided selection
1533     *
1534     * This introduces risk that the local selection might insert incorrect chars
1535     * into the SQL, so use caution.
1536     *
1537     * @param where locally-generated selection, must not be null
1538     * @param selection user-provided selection, may be null
1539     * @return a single selection string
1540     */
1541    private String whereWith(String where, String selection) {
1542        if (selection == null) {
1543            return where;
1544        }
1545        StringBuilder sb = new StringBuilder(where);
1546        sb.append(" AND (");
1547        sb.append(selection);
1548        sb.append(')');
1549
1550        return sb.toString();
1551    }
1552
1553    /**
1554     * Restore a HostAuth from a database, given its unique id
1555     * @param db the database
1556     * @param id the unique id (_id) of the row
1557     * @return a fully populated HostAuth or null if the row does not exist
1558     */
1559    private HostAuth restoreHostAuth(SQLiteDatabase db, long id) {
1560        Cursor c = db.query(HostAuth.TABLE_NAME, HostAuth.CONTENT_PROJECTION,
1561                HostAuth.RECORD_ID + "=?", new String[] {Long.toString(id)}, null, null, null);
1562        try {
1563            if (c.moveToFirst()) {
1564                HostAuth hostAuth = new HostAuth();
1565                hostAuth.restore(c);
1566                return hostAuth;
1567            }
1568            return null;
1569        } finally {
1570            c.close();
1571        }
1572    }
1573
1574    /**
1575     * Copy the Account and HostAuth tables from one database to another
1576     * @param fromDatabase the source database
1577     * @param toDatabase the destination database
1578     * @return the number of accounts copied, or -1 if an error occurred
1579     */
1580    private int copyAccountTables(SQLiteDatabase fromDatabase, SQLiteDatabase toDatabase) {
1581        if (fromDatabase == null || toDatabase == null) return -1;
1582        int copyCount = 0;
1583        try {
1584            // Lock both databases; for the "from" database, we don't want anyone changing it from
1585            // under us; for the "to" database, we want to make the operation atomic
1586            fromDatabase.beginTransaction();
1587            toDatabase.beginTransaction();
1588            // Delete anything hanging around here
1589            toDatabase.delete(Account.TABLE_NAME, null, null);
1590            toDatabase.delete(HostAuth.TABLE_NAME, null, null);
1591            // Get our account cursor
1592            Cursor c = fromDatabase.query(Account.TABLE_NAME, Account.CONTENT_PROJECTION,
1593                    null, null, null, null, null);
1594            boolean noErrors = true;
1595            try {
1596                // Loop through accounts, copying them and associated host auth's
1597                while (c.moveToNext()) {
1598                    Account account = new Account();
1599                    account.restore(c);
1600
1601                    // Clear security sync key and sync key, as these were specific to the state of
1602                    // the account, and we've reset that...
1603                    // Clear policy key so that we can re-establish policies from the server
1604                    // TODO This is pretty EAS specific, but there's a lot of that around
1605                    account.mSecuritySyncKey = null;
1606                    account.mSyncKey = null;
1607                    account.mPolicyKey = 0;
1608
1609                    // Copy host auth's and update foreign keys
1610                    HostAuth hostAuth = restoreHostAuth(fromDatabase, account.mHostAuthKeyRecv);
1611                    // The account might have gone away, though very unlikely
1612                    if (hostAuth == null) continue;
1613                    account.mHostAuthKeyRecv = toDatabase.insert(HostAuth.TABLE_NAME, null,
1614                            hostAuth.toContentValues());
1615                    // EAS accounts have no send HostAuth
1616                    if (account.mHostAuthKeySend > 0) {
1617                        hostAuth = restoreHostAuth(fromDatabase, account.mHostAuthKeySend);
1618                        // Belt and suspenders; I can't imagine that this is possible, since we
1619                        // checked the validity of the account above, and the database is now locked
1620                        if (hostAuth == null) continue;
1621                        account.mHostAuthKeySend = toDatabase.insert(HostAuth.TABLE_NAME, null,
1622                                hostAuth.toContentValues());
1623                    }
1624                    // Now, create the account in the "to" database
1625                    toDatabase.insert(Account.TABLE_NAME, null, account.toContentValues());
1626                    copyCount++;
1627                }
1628            } catch (SQLiteException e) {
1629                noErrors = false;
1630                copyCount = -1;
1631            } finally {
1632                fromDatabase.endTransaction();
1633                if (noErrors) {
1634                    // Say it's ok to commit
1635                    toDatabase.setTransactionSuccessful();
1636                }
1637                toDatabase.endTransaction();
1638                c.close();
1639            }
1640        } catch (SQLiteException e) {
1641            copyCount = -1;
1642        }
1643        return copyCount;
1644    }
1645
1646    private SQLiteDatabase getBackupDatabase(Context context) {
1647        DatabaseHelper helper = new DatabaseHelper(context, BACKUP_DATABASE_NAME);
1648        return helper.getWritableDatabase();
1649    }
1650
1651    /**
1652     * Backup account data, returning the number of accounts backed up
1653     */
1654    private int backupAccounts() {
1655        Context context = getContext();
1656        SQLiteDatabase backupDatabase = getBackupDatabase(context);
1657        try {
1658            return copyAccountTables(getDatabase(context), backupDatabase);
1659        } finally {
1660            if (backupDatabase != null) {
1661                backupDatabase.close();
1662            }
1663        }
1664    }
1665
1666    /**
1667     * Restore account data, returning the number of accounts restored
1668     */
1669    private int restoreAccounts() {
1670        Context context = getContext();
1671        SQLiteDatabase backupDatabase = getBackupDatabase(context);
1672        try {
1673            return copyAccountTables(backupDatabase, getDatabase(context));
1674        } finally {
1675            if (backupDatabase != null) {
1676                backupDatabase.close();
1677            }
1678        }
1679    }
1680
1681    @Override
1682    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
1683        // Handle this special case the fastest possible way
1684        if (uri == INTEGRITY_CHECK_URI) {
1685            checkDatabases();
1686            return 0;
1687        } else if (uri == ACCOUNT_BACKUP_URI) {
1688            return backupAccounts();
1689        } else if (uri == ACCOUNT_RESTORE_URI) {
1690            return restoreAccounts();
1691        }
1692
1693        // Notify all existing cursors, except for ACCOUNT_RESET_NEW_COUNT(_ID)
1694        Uri notificationUri = EmailContent.CONTENT_URI;
1695
1696        int match = findMatch(uri, "update");
1697        Context context = getContext();
1698        ContentResolver resolver = context.getContentResolver();
1699        // See the comment at delete(), above
1700        SQLiteDatabase db = getDatabase(context);
1701        int table = match >> BASE_SHIFT;
1702        int result;
1703
1704        // We do NOT allow setting of unreadCount/messageCount via the provider
1705        // These columns are maintained via triggers
1706        if (match == MAILBOX_ID || match == MAILBOX) {
1707            values.remove(MailboxColumns.UNREAD_COUNT);
1708            values.remove(MailboxColumns.MESSAGE_COUNT);
1709        }
1710
1711        ContentCache cache = CONTENT_CACHES[table];
1712        String tableName = TABLE_NAMES[table];
1713        String id = "0";
1714
1715        try {
1716            switch (match) {
1717                case MAILBOX_ID_ADD_TO_FIELD:
1718                case ACCOUNT_ID_ADD_TO_FIELD:
1719                    id = uri.getPathSegments().get(1);
1720                    String field = values.getAsString(EmailContent.FIELD_COLUMN_NAME);
1721                    Long add = values.getAsLong(EmailContent.ADD_COLUMN_NAME);
1722                    if (field == null || add == null) {
1723                        throw new IllegalArgumentException("No field/add specified " + uri);
1724                    }
1725                    ContentValues actualValues = new ContentValues();
1726                    if (cache != null) {
1727                        cache.lock(id);
1728                    }
1729                    try {
1730                        db.beginTransaction();
1731                        try {
1732                            Cursor c = db.query(tableName,
1733                                    new String[] {EmailContent.RECORD_ID, field},
1734                                    whereWithId(id, selection),
1735                                    selectionArgs, null, null, null);
1736                            try {
1737                                result = 0;
1738                                String[] bind = new String[1];
1739                                if (c.moveToNext()) {
1740                                    bind[0] = c.getString(0); // _id
1741                                    long value = c.getLong(1) + add;
1742                                    actualValues.put(field, value);
1743                                    result = db.update(tableName, actualValues, ID_EQUALS, bind);
1744                                }
1745                                db.setTransactionSuccessful();
1746                            } finally {
1747                                c.close();
1748                            }
1749                        } finally {
1750                            db.endTransaction();
1751                        }
1752                    } finally {
1753                        if (cache != null) {
1754                            cache.unlock(id, actualValues);
1755                        }
1756                    }
1757                    break;
1758                case SYNCED_MESSAGE_ID:
1759                case UPDATED_MESSAGE_ID:
1760                case MESSAGE_ID:
1761                case BODY_ID:
1762                case ATTACHMENT_ID:
1763                case MAILBOX_ID:
1764                case ACCOUNT_ID:
1765                case HOSTAUTH_ID:
1766                    id = uri.getPathSegments().get(1);
1767                    if (cache != null) {
1768                        cache.lock(id);
1769                    }
1770                    try {
1771                        if (match == SYNCED_MESSAGE_ID) {
1772                            // For synced messages, first copy the old message to the updated table
1773                            // Note the insert or ignore semantics, guaranteeing that only the first
1774                            // update will be reflected in the updated message table; therefore this
1775                            // row will always have the "original" data
1776                            db.execSQL(UPDATED_MESSAGE_INSERT + id);
1777                        } else if (match == MESSAGE_ID) {
1778                            db.execSQL(UPDATED_MESSAGE_DELETE + id);
1779                        }
1780                        result = db.update(tableName, values, whereWithId(id, selection),
1781                                selectionArgs);
1782                    } catch (SQLiteException e) {
1783                        // Null out values (so they aren't cached) and re-throw
1784                        values = null;
1785                        throw e;
1786                    } finally {
1787                        if (cache != null) {
1788                            cache.unlock(id, values);
1789                        }
1790                    }
1791                    if (match == ATTACHMENT_ID) {
1792                        if (values.containsKey(Attachment.FLAGS)) {
1793                            int flags = values.getAsInteger(Attachment.FLAGS);
1794                            AttachmentDownloadService.attachmentChanged(
1795                                    Integer.parseInt(id), flags);
1796                        }
1797                    }
1798                    break;
1799                case BODY:
1800                case MESSAGE:
1801                case UPDATED_MESSAGE:
1802                case ATTACHMENT:
1803                case MAILBOX:
1804                case ACCOUNT:
1805                case HOSTAUTH:
1806                    switch(match) {
1807                        case MESSAGE:
1808                        case ACCOUNT:
1809                        case MAILBOX:
1810                        case HOSTAUTH:
1811                            // If we're doing some generic update, the whole cache needs to be
1812                            // invalidated.  This case should be quite rare
1813                            cache.invalidate("Update", uri, selection);
1814                            break;
1815                    }
1816                    result = db.update(tableName, values, selection, selectionArgs);
1817                    break;
1818                case ACCOUNT_RESET_NEW_COUNT_ID:
1819                    id = uri.getPathSegments().get(1);
1820                    if (cache != null) {
1821                        cache.lock(id);
1822                    }
1823                    ContentValues newMessageCount = CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT;
1824                    if (values != null) {
1825                        Long set = values.getAsLong(EmailContent.SET_COLUMN_NAME);
1826                        if (set != null) {
1827                            newMessageCount = new ContentValues();
1828                            newMessageCount.put(Account.NEW_MESSAGE_COUNT, set);
1829                        }
1830                    }
1831                    try {
1832                        result = db.update(tableName, newMessageCount,
1833                                whereWithId(id, selection), selectionArgs);
1834                    } finally {
1835                        if (cache != null) {
1836                            cache.unlock(id, values);
1837                        }
1838                    }
1839                    notificationUri = Account.CONTENT_URI; // Only notify account cursors.
1840                    break;
1841                case ACCOUNT_RESET_NEW_COUNT:
1842                    result = db.update(tableName, CONTENT_VALUES_RESET_NEW_MESSAGE_COUNT,
1843                            selection, selectionArgs);
1844                    // Affects all accounts.  Just invalidate all account cache.
1845                    cache.invalidate("Reset all new counts", null, null);
1846                    notificationUri = Account.CONTENT_URI; // Only notify account cursors.
1847                    break;
1848                default:
1849                    throw new IllegalArgumentException("Unknown URI " + uri);
1850            }
1851        } catch (SQLiteException e) {
1852            checkDatabases();
1853            throw e;
1854        }
1855
1856        // Notify all notifier cursors
1857        sendNotifierChange(getBaseNotificationUri(match), NOTIFICATION_OP_UPDATE, id);
1858
1859        resolver.notifyChange(notificationUri, null);
1860        return result;
1861    }
1862
1863    /**
1864     * Returns the base notification URI for the given content type.
1865     *
1866     * @param match The type of content that was modified.
1867     */
1868    private Uri getBaseNotificationUri(int match) {
1869        Uri baseUri = null;
1870        switch (match) {
1871            case MESSAGE:
1872            case MESSAGE_ID:
1873            case SYNCED_MESSAGE_ID:
1874                baseUri = Message.NOTIFIER_URI;
1875                break;
1876            case ACCOUNT:
1877            case ACCOUNT_ID:
1878                baseUri = Account.NOTIFIER_URI;
1879                break;
1880        }
1881        return baseUri;
1882    }
1883
1884    /**
1885     * Sends a change notification to any cursors observers of the given base URI. The final
1886     * notification URI is dynamically built to contain the specified information. It will be
1887     * of the format <<baseURI>>/<<op>>/<<id>>; where <<op>> and <<id>> are optional depending
1888     * upon the given values.
1889     * NOTE: If <<op>> is specified, notifications for <<baseURI>>/<<id>> will NOT be invoked.
1890     * If this is necessary, it can be added. However, due to the implementation of
1891     * {@link ContentObserver}, observers of <<baseURI>> will receive multiple notifications.
1892     *
1893     * @param baseUri The base URI to send notifications to. Must be able to take appended IDs.
1894     * @param op Optional operation to be appended to the URI.
1895     * @param id If a positive value, the ID to append to the base URI. Otherwise, no ID will be
1896     *           appended to the base URI.
1897     */
1898    private void sendNotifierChange(Uri baseUri, String op, String id) {
1899        if (baseUri == null) return;
1900
1901        final ContentResolver resolver = getContext().getContentResolver();
1902
1903        // Append the operation, if specified
1904        if (op != null) {
1905            baseUri = baseUri.buildUpon().appendEncodedPath(op).build();
1906        }
1907
1908        long longId = 0L;
1909        try {
1910            longId = Long.valueOf(id);
1911        } catch (NumberFormatException ignore) {}
1912        if (longId > 0) {
1913            resolver.notifyChange(ContentUris.withAppendedId(baseUri, longId), null);
1914        } else {
1915            resolver.notifyChange(baseUri, null);
1916        }
1917    }
1918
1919    @Override
1920    public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
1921            throws OperationApplicationException {
1922        Context context = getContext();
1923        SQLiteDatabase db = getDatabase(context);
1924        db.beginTransaction();
1925        try {
1926            ContentProviderResult[] results = super.applyBatch(operations);
1927            db.setTransactionSuccessful();
1928            return results;
1929        } finally {
1930            db.endTransaction();
1931        }
1932    }
1933
1934    /** Counts the number of messages in each mailbox, and updates the message count column. */
1935    @VisibleForTesting
1936    static void recalculateMessageCount(SQLiteDatabase db) {
1937        db.execSQL("update " + Mailbox.TABLE_NAME + " set " + MailboxColumns.MESSAGE_COUNT +
1938                "= (select count(*) from " + Message.TABLE_NAME +
1939                " where " + Message.MAILBOX_KEY + " = " +
1940                    Mailbox.TABLE_NAME + "." + EmailContent.RECORD_ID + ")");
1941    }
1942
1943    @VisibleForTesting
1944    @SuppressWarnings("deprecation")
1945    void convertPolicyFlagsToPolicyTable(SQLiteDatabase db) {
1946        Cursor c = db.query(Account.TABLE_NAME,
1947                new String[] {EmailContent.RECORD_ID /*0*/, AccountColumns.SECURITY_FLAGS /*1*/},
1948                AccountColumns.SECURITY_FLAGS + ">0", null, null, null, null);
1949        ContentValues cv = new ContentValues();
1950        String[] args = new String[1];
1951        while (c.moveToNext()) {
1952            long securityFlags = c.getLong(1 /*SECURITY_FLAGS*/);
1953            Policy policy = LegacyPolicySet.flagsToPolicy(securityFlags);
1954            long policyId = db.insert(Policy.TABLE_NAME, null, policy.toContentValues());
1955            cv.put(AccountColumns.POLICY_KEY, policyId);
1956            cv.putNull(AccountColumns.SECURITY_FLAGS);
1957            args[0] = Long.toString(c.getLong(0 /*RECORD_ID*/));
1958            db.update(Account.TABLE_NAME, cv, EmailContent.RECORD_ID + "=?", args);
1959        }
1960    }
1961
1962    /** Upgrades the database from v17 to v18 */
1963    @VisibleForTesting
1964    static void upgradeFromVersion17ToVersion18(SQLiteDatabase db) {
1965        // Copy the displayName column to the serverId column. In v18 of the database,
1966        // we use the serverId for IMAP/POP3 mailboxes instead of overloading the
1967        // display name.
1968        //
1969        // For posterity; this is the command we're executing:
1970        //sqlite> UPDATE mailbox SET serverid=displayname WHERE mailbox._id in (
1971        //        ...> SELECT mailbox._id FROM mailbox,account,hostauth WHERE
1972        //        ...> mailbox.parentkey=0 AND mailbox.accountkey=account._id AND
1973        //        ...> account.hostauthkeyrecv=hostauth._id AND
1974        //        ...> (hostauth.protocol='imap' OR hostauth.protocol='pop3'));
1975        try {
1976            db.execSQL(
1977                    "UPDATE " + Mailbox.TABLE_NAME + " SET "
1978                    + MailboxColumns.SERVER_ID + "=" + MailboxColumns.DISPLAY_NAME
1979                    + " WHERE "
1980                    + Mailbox.TABLE_NAME + "." + MailboxColumns.ID + " IN ( SELECT "
1981                    + Mailbox.TABLE_NAME + "." + MailboxColumns.ID + " FROM "
1982                    + Mailbox.TABLE_NAME + "," + Account.TABLE_NAME + ","
1983                    + HostAuth.TABLE_NAME + " WHERE "
1984                    + Mailbox.TABLE_NAME + "." + MailboxColumns.PARENT_KEY + "=0 AND "
1985                    + Mailbox.TABLE_NAME + "." + MailboxColumns.ACCOUNT_KEY + "="
1986                    + Account.TABLE_NAME + "." + AccountColumns.ID + " AND "
1987                    + Account.TABLE_NAME + "." + AccountColumns.HOST_AUTH_KEY_RECV + "="
1988                    + HostAuth.TABLE_NAME + "." + HostAuthColumns.ID + " AND ( "
1989                    + HostAuth.TABLE_NAME + "." + HostAuthColumns.PROTOCOL + "='imap' OR "
1990                    + HostAuth.TABLE_NAME + "." + HostAuthColumns.PROTOCOL + "='pop3' ) )");
1991        } catch (SQLException e) {
1992            // Shouldn't be needed unless we're debugging and interrupt the process
1993            Log.w(TAG, "Exception upgrading EmailProvider.db from 17 to 18 " + e);
1994        }
1995    }
1996
1997    /** Upgrades the database from v20 to v21 */
1998    private static void upgradeFromVersion20ToVersion21(SQLiteDatabase db) {
1999        try {
2000            db.execSQL("alter table " + Mailbox.TABLE_NAME
2001                    + " add column " + Mailbox.LAST_SEEN_MESSAGE_KEY + " integer;");
2002        } catch (SQLException e) {
2003            // Shouldn't be needed unless we're debugging and interrupt the process
2004            Log.w(TAG, "Exception upgrading EmailProvider.db from 20 to 21 " + e);
2005        }
2006    }
2007}
2008