aboutsummaryrefslogtreecommitdiff
path: root/src/com/android/providers/contacts/CallLogProvider.java
blob: 01f3d57745e58e39cb4cc21cef7566dbbbb68049 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

package com.android.providers.contacts;

import static com.android.providers.contacts.util.DbQueryUtils.checkForSupportedColumns;
import static com.android.providers.contacts.util.DbQueryUtils.getEqualityClause;
import static com.android.providers.contacts.util.DbQueryUtils.getInequalityClause;
import static com.android.providers.contacts.util.PhoneAccountHandleMigrationUtils.TELEPHONY_COMPONENT_NAME;

import android.annotation.NonNull;
import android.annotation.Nullable;
import android.app.AppOpsManager;
import android.content.BroadcastReceiver;
import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.OperationApplicationException;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.database.sqlite.SQLiteTokenizer;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.os.ParcelableException;
import android.os.StatFs;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.CallLog;
import android.provider.CallLog.Calls;
import android.telecom.PhoneAccount;
import android.telecom.PhoneAccountHandle;
import android.telecom.TelecomManager;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.EventLog;
import android.util.LocalLog;
import android.util.Log;

import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.ProviderAccessStats;
import com.android.providers.contacts.CallLogDatabaseHelper.DbProperties;
import com.android.providers.contacts.CallLogDatabaseHelper.Tables;
import com.android.providers.contacts.util.FileUtilities;
import com.android.providers.contacts.util.NeededForTesting;
import com.android.providers.contacts.util.SelectionBuilder;
import com.android.providers.contacts.util.UserUtils;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.nio.file.attribute.FileTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/**
 * Call log content provider.
 */
public class CallLogProvider extends ContentProvider {
    private static final String TAG = "CallLogProvider";

    public static final boolean VERBOSE_LOGGING = Log.isLoggable(TAG, Log.VERBOSE);

    @VisibleForTesting
    protected static final int BACKGROUND_TASK_INITIALIZE = 0;
    private static final int BACKGROUND_TASK_ADJUST_PHONE_ACCOUNT = 1;
    private static final int BACKGROUND_TASK_MIGRATE_PHONE_ACCOUNT_HANDLES = 2;

    /** Selection clause for selecting all calls that were made after a certain time */
    private static final String MORE_RECENT_THAN_SELECTION = Calls.DATE + "> ?";
    /** Selection clause to use to exclude voicemail records.  */
    private static final String EXCLUDE_VOICEMAIL_SELECTION = getInequalityClause(
            Calls.TYPE, Calls.VOICEMAIL_TYPE);
    /** Selection clause to exclude hidden records. */
    private static final String EXCLUDE_HIDDEN_SELECTION = getEqualityClause(
            Calls.PHONE_ACCOUNT_HIDDEN, 0);

    private static final String CALL_COMPOSER_PICTURE_DIRECTORY_NAME = "call_composer_pics";
    private static final String CALL_COMPOSER_ALL_USERS_DIRECTORY_NAME = "all_users";

    // Constants to be used with ContentProvider#call in order to sync call composer pics between
    // users. Defined here because they're for internal use only.
    /**
     * Method name used to get a list of {@link Uri}s for call composer pictures inserted for all
     * users after a certain date
     */
    private static final String GET_CALL_COMPOSER_IMAGE_URIS =
            "com.android.providers.contacts.GET_CALL_COMPOSER_IMAGE_URIS";

    /**
     * Long-valued extra containing the date to filter by expressed as milliseconds after the epoch.
     */
    private static final String EXTRA_SINCE_DATE =
            "com.android.providers.contacts.extras.SINCE_DATE";

    /**
     * Boolean-valued extra indicating whether to read from the shadow portion of the calllog
     * (i.e. device-encrypted storage rather than credential-encrypted)
     */
    private static final String EXTRA_IS_SHADOW =
            "com.android.providers.contacts.extras.IS_SHADOW";

    /**
     * Boolean-valued extra indicating whether to return Uris only for those images that are
     * supposed to be inserted for all users.
     */
    private static final String EXTRA_ALL_USERS_ONLY =
            "com.android.providers.contacts.extras.ALL_USERS_ONLY";

    private static final String EXTRA_RESULT_URIS =
            "com.android.provider.contacts.extras.EXTRA_RESULT_URIS";

    @VisibleForTesting
    static final String[] CALL_LOG_SYNC_PROJECTION = new String[] {
            Calls.NUMBER,
            Calls.NUMBER_PRESENTATION,
            Calls.TYPE,
            Calls.FEATURES,
            Calls.DATE,
            Calls.DURATION,
            Calls.DATA_USAGE,
            Calls.PHONE_ACCOUNT_COMPONENT_NAME,
            Calls.PHONE_ACCOUNT_ID,
            Calls.PRIORITY,
            Calls.SUBJECT,
            Calls.COMPOSER_PHOTO_URI,
            // Location is deliberately omitted
            Calls.ADD_FOR_ALL_USERS
    };

    static final String[] MINIMAL_PROJECTION = new String[] { Calls._ID };

    private static final int CALLS = 1;

    private static final int CALLS_ID = 2;

    private static final int CALLS_FILTER = 3;

    private static final int CALL_COMPOSER_NEW_PICTURE = 4;

    private static final int CALL_COMPOSER_PICTURE = 5;

    private static final String UNHIDE_BY_PHONE_ACCOUNT_QUERY =
            "UPDATE " + Tables.CALLS + " SET " + Calls.PHONE_ACCOUNT_HIDDEN + "=0 WHERE " +
            Calls.PHONE_ACCOUNT_COMPONENT_NAME + "=? AND " + Calls.PHONE_ACCOUNT_ID + "=?;";

    private static final String UNHIDE_BY_ADDRESS_QUERY =
            "UPDATE " + Tables.CALLS + " SET " + Calls.PHONE_ACCOUNT_HIDDEN + "=0 WHERE " +
            Calls.PHONE_ACCOUNT_ADDRESS + "=?;";

    private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    static {
        sURIMatcher.addURI(CallLog.AUTHORITY, "calls", CALLS);
        sURIMatcher.addURI(CallLog.AUTHORITY, "calls/#", CALLS_ID);
        sURIMatcher.addURI(CallLog.AUTHORITY, "calls/filter/*", CALLS_FILTER);
        sURIMatcher.addURI(CallLog.AUTHORITY, CallLog.CALL_COMPOSER_SEGMENT,
                CALL_COMPOSER_NEW_PICTURE);
        sURIMatcher.addURI(CallLog.AUTHORITY, CallLog.CALL_COMPOSER_SEGMENT + "/*",
                CALL_COMPOSER_PICTURE);

        // Shadow provider only supports "/calls" and "/call_composer".
        sURIMatcher.addURI(CallLog.SHADOW_AUTHORITY, "calls", CALLS);
        sURIMatcher.addURI(CallLog.SHADOW_AUTHORITY, CallLog.CALL_COMPOSER_SEGMENT,
                CALL_COMPOSER_NEW_PICTURE);
        sURIMatcher.addURI(CallLog.SHADOW_AUTHORITY, CallLog.CALL_COMPOSER_SEGMENT + "/*",
                CALL_COMPOSER_PICTURE);
    }

    public static final ArrayMap<String, String> sCallsProjectionMap;
    static {

        // Calls projection map
        sCallsProjectionMap = new ArrayMap<>();
        sCallsProjectionMap.put(Calls._ID, Calls._ID);
        sCallsProjectionMap.put(Calls.NUMBER, Calls.NUMBER);
        sCallsProjectionMap.put(Calls.POST_DIAL_DIGITS, Calls.POST_DIAL_DIGITS);
        sCallsProjectionMap.put(Calls.VIA_NUMBER, Calls.VIA_NUMBER);
        sCallsProjectionMap.put(Calls.NUMBER_PRESENTATION, Calls.NUMBER_PRESENTATION);
        sCallsProjectionMap.put(Calls.DATE, Calls.DATE);
        sCallsProjectionMap.put(Calls.DURATION, Calls.DURATION);
        sCallsProjectionMap.put(Calls.DATA_USAGE, Calls.DATA_USAGE);
        sCallsProjectionMap.put(Calls.TYPE, Calls.TYPE);
        sCallsProjectionMap.put(Calls.FEATURES, Calls.FEATURES);
        sCallsProjectionMap.put(Calls.PHONE_ACCOUNT_COMPONENT_NAME, Calls.PHONE_ACCOUNT_COMPONENT_NAME);
        sCallsProjectionMap.put(Calls.PHONE_ACCOUNT_ID, Calls.PHONE_ACCOUNT_ID);
        sCallsProjectionMap.put(Calls.PHONE_ACCOUNT_HIDDEN, Calls.PHONE_ACCOUNT_HIDDEN);
        sCallsProjectionMap.put(Calls.PHONE_ACCOUNT_ADDRESS, Calls.PHONE_ACCOUNT_ADDRESS);
        sCallsProjectionMap.put(Calls.NEW, Calls.NEW);
        sCallsProjectionMap.put(Calls.VOICEMAIL_URI, Calls.VOICEMAIL_URI);
        sCallsProjectionMap.put(Calls.TRANSCRIPTION, Calls.TRANSCRIPTION);
        sCallsProjectionMap.put(Calls.TRANSCRIPTION_STATE, Calls.TRANSCRIPTION_STATE);
        sCallsProjectionMap.put(Calls.IS_READ, Calls.IS_READ);
        sCallsProjectionMap.put(Calls.CACHED_NAME, Calls.CACHED_NAME);
        sCallsProjectionMap.put(Calls.CACHED_NUMBER_TYPE, Calls.CACHED_NUMBER_TYPE);
        sCallsProjectionMap.put(Calls.CACHED_NUMBER_LABEL, Calls.CACHED_NUMBER_LABEL);
        sCallsProjectionMap.put(Calls.COUNTRY_ISO, Calls.COUNTRY_ISO);
        sCallsProjectionMap.put(Calls.GEOCODED_LOCATION, Calls.GEOCODED_LOCATION);
        sCallsProjectionMap.put(Calls.CACHED_LOOKUP_URI, Calls.CACHED_LOOKUP_URI);
        sCallsProjectionMap.put(Calls.CACHED_MATCHED_NUMBER, Calls.CACHED_MATCHED_NUMBER);
        sCallsProjectionMap.put(Calls.CACHED_NORMALIZED_NUMBER, Calls.CACHED_NORMALIZED_NUMBER);
        sCallsProjectionMap.put(Calls.CACHED_PHOTO_ID, Calls.CACHED_PHOTO_ID);
        sCallsProjectionMap.put(Calls.CACHED_PHOTO_URI, Calls.CACHED_PHOTO_URI);
        sCallsProjectionMap.put(Calls.CACHED_FORMATTED_NUMBER, Calls.CACHED_FORMATTED_NUMBER);
        sCallsProjectionMap.put(Calls.ADD_FOR_ALL_USERS, Calls.ADD_FOR_ALL_USERS);
        sCallsProjectionMap.put(Calls.LAST_MODIFIED, Calls.LAST_MODIFIED);
        sCallsProjectionMap
            .put(Calls.CALL_SCREENING_COMPONENT_NAME, Calls.CALL_SCREENING_COMPONENT_NAME);
        sCallsProjectionMap.put(Calls.CALL_SCREENING_APP_NAME, Calls.CALL_SCREENING_APP_NAME);
        sCallsProjectionMap.put(Calls.BLOCK_REASON, Calls.BLOCK_REASON);
        sCallsProjectionMap.put(Calls.MISSED_REASON, Calls.MISSED_REASON);
        sCallsProjectionMap.put(Calls.PRIORITY, Calls.PRIORITY);
        sCallsProjectionMap.put(Calls.COMPOSER_PHOTO_URI, Calls.COMPOSER_PHOTO_URI);
        sCallsProjectionMap.put(Calls.SUBJECT, Calls.SUBJECT);
        sCallsProjectionMap.put(Calls.LOCATION, Calls.LOCATION);
        sCallsProjectionMap.put(Calls.IS_PHONE_ACCOUNT_MIGRATION_PENDING,
                Calls.IS_PHONE_ACCOUNT_MIGRATION_PENDING);
    }

    /**
     * Subscription change will trigger ACTION_PHONE_ACCOUNT_REGISTERED that broadcasts new
     * PhoneAccountHandle that is created based on the new subscription. This receiver is used
     * for listening new subscription change and migrating phone account handle if any pending.
     *
     * It is then used by the call log to un-hide any entries which were previously hidden after
     * a backup-restore until its associated phone-account is registered with telecom. After a
     * restore, we hide call log entries until the user inserts the corresponding SIM, registers
     * the corresponding SIP account, or registers a corresponding alternative phone-account.
     */
    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (TelecomManager.ACTION_PHONE_ACCOUNT_REGISTERED.equals(intent.getAction())) {
                PhoneAccountHandle phoneAccountHandle =
                        (PhoneAccountHandle) intent.getParcelableExtra(
                                TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE);
                if (mDbHelper.getPhoneAccountHandleMigrationUtils()
                        .isPhoneAccountMigrationPending()
                        && TELEPHONY_COMPONENT_NAME.equals(
                                phoneAccountHandle.getComponentName().flattenToString())
                        && !mMigratedPhoneAccountHandles.contains(phoneAccountHandle)) {
                    mMigratedPhoneAccountHandles.add(phoneAccountHandle);
                    mTaskScheduler.scheduleTask(
                            BACKGROUND_TASK_MIGRATE_PHONE_ACCOUNT_HANDLES, phoneAccountHandle);
                } else {
                    mTaskScheduler.scheduleTask(BACKGROUND_TASK_ADJUST_PHONE_ACCOUNT,
                            phoneAccountHandle);
                }
            }
        }
    };

    private static final String ALLOWED_PACKAGE_FOR_TESTING = "com.android.providers.contacts";

    @VisibleForTesting
    static final String PARAM_KEY_QUERY_FOR_TESTING = "query_for_testing";

    /**
     * A long to override the clock used for timestamps, or "null" to reset to the system clock.
     */
    @VisibleForTesting
    static final String PARAM_KEY_SET_TIME_FOR_TESTING = "set_time_for_testing";

    private static Long sTimeForTestMillis;

    private ContactsTaskScheduler mTaskScheduler;

    @VisibleForTesting
    protected volatile CountDownLatch mReadAccessLatch;

    private CallLogDatabaseHelper mDbHelper;
    private DatabaseUtils.InsertHelper mCallsInserter;
    private boolean mUseStrictPhoneNumberComparation;
    private int mMinMatch;
    private VoicemailPermissions mVoicemailPermissions;
    private CallLogInsertionHelper mCallLogInsertionHelper;
    private SubscriptionManager mSubscriptionManager;
    private LocalLog mLocalLog = new LocalLog(20);

    private final ThreadLocal<Boolean> mApplyingBatch = new ThreadLocal<>();
    private final ThreadLocal<Integer> mCallingUid = new ThreadLocal<>();
    private final ProviderAccessStats mStats = new ProviderAccessStats();
    private final Set<PhoneAccountHandle> mMigratedPhoneAccountHandles = new HashSet<>();

    protected boolean isShadow() {
        return false;
    }

    protected final String getProviderName() {
        return this.getClass().getSimpleName();
    }

    @Override
    public boolean onCreate() {
        if (VERBOSE_LOGGING) {
            Log.v(TAG, "onCreate: " + this.getClass().getSimpleName()
                    + " user=" + android.os.Process.myUserHandle().getIdentifier());
        }

        setAppOps(AppOpsManager.OP_READ_CALL_LOG, AppOpsManager.OP_WRITE_CALL_LOG);
        if (Log.isLoggable(Constants.PERFORMANCE_TAG, Log.DEBUG)) {
            Log.d(Constants.PERFORMANCE_TAG, getProviderName() + ".onCreate start");
        }
        final Context context = getContext();
        mDbHelper = getDatabaseHelper(context);
        mUseStrictPhoneNumberComparation =
            context.getResources().getBoolean(
                    com.android.internal.R.bool.config_use_strict_phone_number_comparation);
        mMinMatch =
            context.getResources().getInteger(
                    com.android.internal.R.integer.config_phonenumber_compare_min_match);
        mVoicemailPermissions = new VoicemailPermissions(context);
        mCallLogInsertionHelper = createCallLogInsertionHelper(context);

        mReadAccessLatch = new CountDownLatch(1);

        mTaskScheduler = new ContactsTaskScheduler(getClass().getSimpleName()) {
            @Override
            public void onPerformTask(int taskId, Object arg) {
                performBackgroundTask(taskId, arg);
            }
        };

        mTaskScheduler.scheduleTask(BACKGROUND_TASK_INITIALIZE, null);

        mSubscriptionManager = context.getSystemService(SubscriptionManager.class);

        // Register a receiver to hear sim change event for migrating pending
        // PhoneAccountHandle ID or/and unhides restored call logs
        IntentFilter filter = new IntentFilter(TelecomManager.ACTION_PHONE_ACCOUNT_REGISTERED);
        context.registerReceiver(mBroadcastReceiver, filter);

        if (Log.isLoggable(Constants.PERFORMANCE_TAG, Log.DEBUG)) {
            Log.d(Constants.PERFORMANCE_TAG, getProviderName() + ".onCreate finish");
        }
        return true;
    }

    @VisibleForTesting
    protected CallLogInsertionHelper createCallLogInsertionHelper(final Context context) {
        return DefaultCallLogInsertionHelper.getInstance(context);
    }

    @VisibleForTesting
    public void setMinMatchForTest(int minMatch) {
        mMinMatch = minMatch;
    }

    @VisibleForTesting
    public int getMinMatchForTest() {
        return mMinMatch;
    }

    @NeededForTesting
    public CallLogDatabaseHelper getCallLogDatabaseHelperForTest() {
        return mDbHelper;
    }

    @NeededForTesting
    public void setCallLogDatabaseHelperForTest(CallLogDatabaseHelper callLogDatabaseHelper) {
        mDbHelper = callLogDatabaseHelper;
    }

    /**
     * @return the currently registered BroadcastReceiver for listening
     *         ACTION_PHONE_ACCOUNT_REGISTERED in the current process.
     */
    @NeededForTesting
    public BroadcastReceiver getBroadcastReceiverForTest() {
        return mBroadcastReceiver;
    }

    protected CallLogDatabaseHelper getDatabaseHelper(final Context context) {
        return CallLogDatabaseHelper.getInstance(context);
    }

    protected boolean applyingBatch() {
        final Boolean applying =  mApplyingBatch.get();
        return applying != null && applying;
    }

    @Override
    public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
            throws OperationApplicationException {
        final int callingUid = Binder.getCallingUid();
        mCallingUid.set(callingUid);

        mStats.incrementBatchStats(callingUid);
        mApplyingBatch.set(true);
        try {
            return super.applyBatch(operations);
        } finally {
            mApplyingBatch.set(false);
            mStats.finishOperation(callingUid);
        }
    }

    @Override
    public int bulkInsert(Uri uri, ContentValues[] values) {
        final int callingUid = Binder.getCallingUid();
        mCallingUid.set(callingUid);

        mStats.incrementBatchStats(callingUid);
        mApplyingBatch.set(true);
        try {
            return super.bulkInsert(uri, values);
        } finally {
            mApplyingBatch.set(false);
            mStats.finishOperation(callingUid);
        }
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
            String sortOrder) {
        // Note don't use mCallingUid here. That's only used by mutation functions.
        final int callingUid = Binder.getCallingUid();

        mStats.incrementQueryStats(callingUid);
        try {
            return queryInternal(uri, projection, selection, selectionArgs, sortOrder);
        } finally {
            mStats.finishOperation(callingUid);
        }
    }

    private Cursor queryInternal(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        if (VERBOSE_LOGGING) {
            Log.v(TAG, "query: uri=" + uri + "  projection=" + Arrays.toString(projection) +
                    "  selection=[" + selection + "]  args=" + Arrays.toString(selectionArgs) +
                    "  order=[" + sortOrder + "] CPID=" + Binder.getCallingPid() +
                    " CUID=" + Binder.getCallingUid() +
                    " User=" + UserUtils.getCurrentUserHandle(getContext()));
        }

        queryForTesting(uri);

        waitForAccess(mReadAccessLatch);
        final SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(Tables.CALLS);
        qb.setProjectionMap(sCallsProjectionMap);
        qb.setStrict(true);
        // If the caller doesn't have READ_VOICEMAIL, make sure they can't
        // do any SQL shenanigans to get access to the voicemails. If the caller does have the
        // READ_VOICEMAIL permission, then they have sufficient permissions to access any data in
        // the database, so the strict check is unnecessary.
        if (!mVoicemailPermissions.callerHasReadAccess(getCallingPackage())) {
            qb.setStrictGrammar(true);
        }

        final SelectionBuilder selectionBuilder = new SelectionBuilder(selection);
        checkVoicemailPermissionAndAddRestriction(uri, selectionBuilder, true /*isQuery*/);
        selectionBuilder.addClause(EXCLUDE_HIDDEN_SELECTION);

        final int match = sURIMatcher.match(uri);
        switch (match) {
            case CALLS:
                break;

            case CALLS_ID: {
                selectionBuilder.addClause(getEqualityClause(Calls._ID,
                        parseCallIdFromUri(uri)));
                break;
            }

            case CALLS_FILTER: {
                List<String> pathSegments = uri.getPathSegments();
                String phoneNumber = pathSegments.size() >= 2 ? pathSegments.get(2) : null;
                if (!TextUtils.isEmpty(phoneNumber)) {
                    qb.appendWhere("PHONE_NUMBERS_EQUAL(number, ?");
                    qb.appendWhere(mUseStrictPhoneNumberComparation ? ", 1)"
                            : ", 0, " + mMinMatch + ")");
                    selectionArgs = copyArrayAndAppendElement(selectionArgs,
                            "'" + phoneNumber + "'");
                } else {
                    qb.appendWhere(Calls.NUMBER_PRESENTATION + "!="
                            + Calls.PRESENTATION_ALLOWED);
                }
                break;
            }

            default:
                throw new IllegalArgumentException("Unknown URL " + uri);
        }

        final int limit = getIntParam(uri, Calls.LIMIT_PARAM_KEY, 0);
        final int offset = getIntParam(uri, Calls.OFFSET_PARAM_KEY, 0);
        String limitClause = null;
        if (limit > 0) {
            limitClause = offset + "," + limit;
        }

        final SQLiteDatabase db = mDbHelper.getReadableDatabase();
        final Cursor c = qb.query(db, projection, selectionBuilder.build(), selectionArgs, null,
                null, sortOrder, limitClause);

        if (match == CALLS_FILTER && selectionArgs.length > 0) {
            // throw SE if the user is sending requests that try to bypass voicemail permissions
            examineEmptyCursorCause(c, selectionArgs[selectionArgs.length - 1]);
        }

        if (c != null) {
            c.setNotificationUri(getContext().getContentResolver(), CallLog.CONTENT_URI);
        }
        return c;
    }

    /**
     * Helper method for queryInternal that appends an extra argument to the existing selection
     * arguments array.
     *
     * @param oldSelectionArguments the existing selection argument array in queryInternal
     * @param phoneNumber           the phoneNumber that was passed into queryInternal
     * @return the new selection argument array with the phoneNumber as the last argument
     */
    private String[] copyArrayAndAppendElement(String[] oldSelectionArguments, String phoneNumber) {
        if (oldSelectionArguments == null) {
            return new String[]{phoneNumber};
        }
        String[] newSelectionArguments = new String[oldSelectionArguments.length + 1];
        System.arraycopy(oldSelectionArguments, 0, newSelectionArguments, 0,
                oldSelectionArguments.length);
        newSelectionArguments[oldSelectionArguments.length] = phoneNumber;
        return newSelectionArguments;
    }

    /**
     * Helper that throws a Security Exception if the Cursor object is empty && the phoneNumber
     * appears to have SQL.
     *
     * @param cursor      returned from the query.
     * @param phoneNumber string to check for SQL.
     */
    private void examineEmptyCursorCause(Cursor cursor, String phoneNumber) {
        // checks if the cursor is empty
        if ((cursor == null) || !cursor.moveToFirst()) {
            try {
                // tokenize the phoneNumber and run each token through a checker
                SQLiteTokenizer.tokenize(phoneNumber, SQLiteTokenizer.OPTION_NONE,
                        this::enforceStrictPhoneNumber);
            } catch (IllegalArgumentException e) {
                EventLog.writeEvent(0x534e4554, "224771921", Binder.getCallingUid(),
                        ("invalid phoneNumber passed to queryInternal"));
                throw new SecurityException("invalid phoneNumber passed to queryInternal");
            }
        }
    }

    private void enforceStrictPhoneNumber(String token) {
        boolean isAllowedKeyword = SQLiteTokenizer.isKeyword(token);
        Set<String> lookupTable = Set.of("UNION", "SELECT", "FROM", "WHERE",
                "GROUP", "HAVING", "WINDOW", "VALUES", "ORDER", "LIMIT");
        if (!isAllowedKeyword || lookupTable.contains(token.toUpperCase(Locale.US))) {
            throw new IllegalArgumentException("Invalid token " + token);
        }
    }

    private void queryForTesting(Uri uri) {
        if (!uri.getBooleanQueryParameter(PARAM_KEY_QUERY_FOR_TESTING, false)) {
            return;
        }
        if (!getCallingPackage().equals(ALLOWED_PACKAGE_FOR_TESTING)) {
            throw new IllegalArgumentException("query_for_testing set from foreign package "
                    + getCallingPackage());
        }

        String timeString = uri.getQueryParameter(PARAM_KEY_SET_TIME_FOR_TESTING);
        if (timeString != null) {
            if (timeString.equals("null")) {
                sTimeForTestMillis = null;
            } else {
                sTimeForTestMillis = Long.parseLong(timeString);
            }
        }
    }

    @VisibleForTesting
    static Long getTimeForTestMillis() {
        return sTimeForTestMillis;
    }

    /**
     * Gets an integer query parameter from a given uri.
     *
     * @param uri The uri to extract the query parameter from.
     * @param key The query parameter key.
     * @param defaultValue A default value to return if the query parameter does not exist.
     * @return The value from the query parameter in the Uri.  Or the default value if the parameter
     * does not exist in the uri.
     * @throws IllegalArgumentException when the value in the query parameter is not an integer.
     */
    private int getIntParam(Uri uri, String key, int defaultValue) {
        String valueString = uri.getQueryParameter(key);
        if (valueString == null) {
            return defaultValue;
        }

        try {
            return Integer.parseInt(valueString);
        } catch (NumberFormatException e) {
            String msg = "Integer required for " + key + " parameter but value '" + valueString +
                    "' was found instead.";
            throw new IllegalArgumentException(msg, e);
        }
    }

    @Override
    public String getType(Uri uri) {
        int match = sURIMatcher.match(uri);
        switch (match) {
            case CALLS:
                return Calls.CONTENT_TYPE;
            case CALLS_ID:
                return Calls.CONTENT_ITEM_TYPE;
            case CALLS_FILTER:
                return Calls.CONTENT_TYPE;
            case CALL_COMPOSER_NEW_PICTURE:
                return null; // No type for newly created files
            case CALL_COMPOSER_PICTURE:
                // We don't know the exact image format, so this is as specific as we can be.
                return "application/octet-stream";
            default:
                throw new IllegalArgumentException("Unknown URI: " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        final int callingUid =
                applyingBatch() ? mCallingUid.get() : Binder.getCallingUid();

        mStats.incrementInsertStats(callingUid, applyingBatch());
        try {
            return insertInternal(uri, values);
        } finally {
            mStats.finishOperation(callingUid);
        }
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        final int callingUid =
                applyingBatch() ? mCallingUid.get() : Binder.getCallingUid();

        mStats.incrementUpdateStats(callingUid, applyingBatch());
        try {
            return updateInternal(uri, values, selection, selectionArgs);
        } finally {
            mStats.finishOperation(callingUid);
        }
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        final int callingUid =
                applyingBatch() ? mCallingUid.get() : Binder.getCallingUid();

        mStats.incrementDeleteStats(callingUid, applyingBatch());
        try {
            return deleteInternal(uri, selection, selectionArgs);
        } finally {
            mStats.finishOperation(callingUid);
        }
    }

    private Uri insertInternal(Uri uri, ContentValues values) {
        if (VERBOSE_LOGGING) {
            Log.v(TAG, "insert: uri=" + uri + "  values=[" + values + "]" +
                    " CPID=" + Binder.getCallingPid() +
                    " CUID=" + Binder.getCallingUid());
        }
        waitForAccess(mReadAccessLatch);
        int match = sURIMatcher.match(uri);
        switch (match) {
            case CALL_COMPOSER_PICTURE: {
                String fileName = uri.getLastPathSegment();
                try {
                    return allocateNewCallComposerPicture(values,
                            CallLog.SHADOW_AUTHORITY.equals(uri.getAuthority()),
                            fileName);
                } catch (IOException e) {
                    throw new ParcelableException(e);
                }
            }
            case CALL_COMPOSER_NEW_PICTURE: {
                try {
                    return allocateNewCallComposerPicture(values,
                            CallLog.SHADOW_AUTHORITY.equals(uri.getAuthority()));
                } catch (IOException e) {
                    throw new ParcelableException(e);
                }
            }
            default:
                // Fall through and execute the rest of the method for ordinary call log insertions.
        }

        checkForSupportedColumns(sCallsProjectionMap, values);
        // Inserting a voicemail record through call_log requires the voicemail
        // permission and also requires the additional voicemail param set.
        if (hasVoicemailValue(values)) {
            checkIsAllowVoicemailRequest(uri);
            mVoicemailPermissions.checkCallerHasWriteAccess(getCallingPackage());
        }
        if (mCallsInserter == null) {
            SQLiteDatabase db = mDbHelper.getWritableDatabase();
            mCallsInserter = new DatabaseUtils.InsertHelper(db, Tables.CALLS);
        }

        ContentValues copiedValues = new ContentValues(values);

        // Add the computed fields to the copied values.
        mCallLogInsertionHelper.addComputedValues(copiedValues);

        long rowId = createDatabaseModifier(mCallsInserter).insert(copiedValues);
        String insertLog = String.format(Locale.getDefault(),
                "insert uid/pid=%d/%d, uri=%s, rowId=%d",
                Binder.getCallingUid(), Binder.getCallingPid(), uri, rowId);
        Log.i(TAG, insertLog);
        mLocalLog.log(insertLog);
        if (rowId > 0) {
            return ContentUris.withAppendedId(uri, rowId);
        }
        return null;
    }

    @Override
    public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode)
            throws FileNotFoundException {
        int match = sURIMatcher.match(uri);
        if (match != CALL_COMPOSER_PICTURE) {
            throw new UnsupportedOperationException("The call log provider only supports opening"
                    + " call composer pictures.");
        }
        int modeInt;
        switch (mode) {
            case "r":
                modeInt = ParcelFileDescriptor.MODE_READ_ONLY;
                break;
            case "w":
                modeInt = ParcelFileDescriptor.MODE_WRITE_ONLY;
                break;
            default:
                throw new UnsupportedOperationException("The call log does not support opening"
                        + " a call composer picture with mode " + mode);
        }

        try {
            Path callComposerDir = getCallComposerPictureDirectory(getContext(), uri);
            Path pictureFile = callComposerDir.resolve(uri.getLastPathSegment());
            if (Files.notExists(pictureFile)) {
                throw new FileNotFoundException(uri.toString()
                        + " does not correspond to a valid file.");
            }
            enforceValidCallLogPath(callComposerDir, pictureFile,"openFile");
            return ParcelFileDescriptor.open(pictureFile.toFile(), modeInt);
        } catch (IOException e) {
            Log.e(TAG, "IOException while opening call composer file: " + e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public Bundle call(@NonNull String method, @Nullable String arg, @Nullable Bundle extras) {
        Log.i(TAG, "Fetching list of Uris to sync");
        if (!UserHandle.isSameApp(android.os.Process.myUid(), Binder.getCallingUid())) {
            throw new SecurityException("call() functionality reserved"
                    + " for internal use by the call log.");
        }
        if (!GET_CALL_COMPOSER_IMAGE_URIS.equals(method)) {
            throw new UnsupportedOperationException("Invalid method passed to call(): " + method);
        }
        if (!extras.containsKey(EXTRA_SINCE_DATE)) {
            throw new IllegalArgumentException("SINCE_DATE required");
        }
        if (!extras.containsKey(EXTRA_IS_SHADOW)) {
            throw new IllegalArgumentException("IS_SHADOW required");
        }
        if (!extras.containsKey(EXTRA_ALL_USERS_ONLY)) {
            throw new IllegalArgumentException("ALL_USERS_ONLY required");
        }
        boolean isShadow = extras.getBoolean(EXTRA_IS_SHADOW);
        boolean allUsers = extras.getBoolean(EXTRA_ALL_USERS_ONLY);
        long sinceDate = extras.getLong(EXTRA_SINCE_DATE);

        try {
            Path queryDir = allUsers
                    ? getCallComposerAllUsersPictureDirectory(getContext(), isShadow)
                    : getCallComposerPictureDirectory(getContext(), isShadow);
            List<Path> newestPics = new ArrayList<>();
            try (DirectoryStream<Path> dirStream =
                         Files.newDirectoryStream(queryDir, entry -> {
                             if (Files.isDirectory(entry)) {
                                 return false;
                             }
                             FileTime createdAt =
                                     (FileTime) Files.getAttribute(entry, "creationTime");
                             return createdAt.toMillis() > sinceDate;
                         })) {
                dirStream.forEach(newestPics::add);
            }
            List<Uri> fileUris = newestPics.stream().map((path) -> {
                String fileName = path.getFileName().toString();
                // We don't need to worry about if it's for all users -- anything that's for
                // all users is also stored in the regular location.
                Uri base = isShadow ? CallLog.SHADOW_CALL_COMPOSER_PICTURE_URI
                        : CallLog.CALL_COMPOSER_PICTURE_URI;
                return base.buildUpon().appendPath(fileName).build();
            }).collect(Collectors.toList());
            Bundle result = new Bundle();
            result.putParcelableList(EXTRA_RESULT_URIS, fileUris);
            Log.i(TAG, "Will sync following Uris:" + fileUris);
            return result;
        } catch (IOException e) {
            Log.e(TAG, "IOException while trying to fetch URI list: " + e);
            return null;
        }
    }

    private static @NonNull Path getCallComposerPictureDirectory(Context context, Uri uri)
            throws IOException {
        boolean isShadow = CallLog.SHADOW_AUTHORITY.equals(uri.getAuthority());
        return getCallComposerPictureDirectory(context, isShadow);
    }

    private static @NonNull Path getCallComposerPictureDirectory(Context context, boolean isShadow)
            throws IOException {
        if (isShadow) {
            context = context.createDeviceProtectedStorageContext();
        }
        Path path = context.getFilesDir().toPath().resolve(CALL_COMPOSER_PICTURE_DIRECTORY_NAME);
        if (!Files.isDirectory(path)) {
            Files.createDirectory(path);
        }
        return path;
    }

    private static @NonNull Path getCallComposerAllUsersPictureDirectory(
            Context context, boolean isShadow) throws IOException {
        Path pathToCallComposerDir = getCallComposerPictureDirectory(context, isShadow);
        Path path = pathToCallComposerDir.resolve(CALL_COMPOSER_ALL_USERS_DIRECTORY_NAME);
        if (!Files.isDirectory(path)) {
            Files.createDirectory(path);
        }
        return path;
    }

    private Uri allocateNewCallComposerPicture(ContentValues values, boolean isShadow)
            throws IOException {
        return allocateNewCallComposerPicture(values, isShadow, UUID.randomUUID().toString());
    }

    private Uri allocateNewCallComposerPicture(ContentValues values,
            boolean isShadow, String fileName) throws IOException {
        Uri baseUri = isShadow ?
                CallLog.CALL_COMPOSER_PICTURE_URI.buildUpon()
                        .authority(CallLog.SHADOW_AUTHORITY).build()
                : CallLog.CALL_COMPOSER_PICTURE_URI;

        boolean forAllUsers = values.containsKey(Calls.ADD_FOR_ALL_USERS)
                && (values.getAsInteger(Calls.ADD_FOR_ALL_USERS) == 1);
        Path pathToCallComposerDir = getCallComposerPictureDirectory(getContext(), isShadow);

        if (new StatFs(pathToCallComposerDir.toString()).getAvailableBytes()
                < TelephonyManager.getMaximumCallComposerPictureSize()) {
            return null;
        }
        Path pathToFile = pathToCallComposerDir.resolve(fileName);
        enforceValidCallLogPath(pathToCallComposerDir, pathToFile,
                "allocateNewCallComposerPicture");
        Files.createFile(pathToFile);

        if (forAllUsers) {
            // Create a symlink in a subdirectory for copying later.
            Path allUsersDir = getCallComposerAllUsersPictureDirectory(getContext(), isShadow);
            Files.createSymbolicLink(allUsersDir.resolve(fileName), pathToFile);
        }
        return baseUri.buildUpon().appendPath(fileName).build();
    }

    private int deleteCallComposerPicture(Uri uri) {
        try {
            Path pathToCallComposerDir = getCallComposerPictureDirectory(getContext(), uri);
            Path fileToDelete = pathToCallComposerDir.resolve(uri.getLastPathSegment());
            enforceValidCallLogPath(pathToCallComposerDir, fileToDelete,
                    "deleteCallComposerPicture");
            return Files.deleteIfExists(fileToDelete) ? 1 : 0;
        } catch (IOException e) {
            Log.e(TAG, "IOException encountered deleting the call composer pics dir " + e);
            return 0;
        }
    }

    private int updateInternal(Uri uri, ContentValues values,
            String selection, String[] selectionArgs) {
        if (VERBOSE_LOGGING) {
            Log.v(TAG, "update: uri=" + uri +
                    "  selection=[" + selection + "]  args=" + Arrays.toString(selectionArgs) +
                    "  values=[" + values + "] CPID=" + Binder.getCallingPid() +
                    " CUID=" + Binder.getCallingUid() +
                    " User=" + UserUtils.getCurrentUserHandle(getContext()));
        }
        waitForAccess(mReadAccessLatch);
        checkForSupportedColumns(sCallsProjectionMap, values);
        // Request that involves changing record type to voicemail requires the
        // voicemail param set in the uri.
        if (hasVoicemailValue(values)) {
            checkIsAllowVoicemailRequest(uri);
        }

        SelectionBuilder selectionBuilder = new SelectionBuilder(selection);
        checkVoicemailPermissionAndAddRestriction(uri, selectionBuilder, false /*isQuery*/);
        boolean hasReadVoicemailPermission = mVoicemailPermissions.callerHasReadAccess(
                getCallingPackage());
        final SQLiteDatabase db = mDbHelper.getWritableDatabase();
        final int matchedUriId = sURIMatcher.match(uri);
        switch (matchedUriId) {
            case CALLS:
                break;

            case CALLS_ID:
                selectionBuilder.addClause(getEqualityClause(Calls._ID, parseCallIdFromUri(uri)));
                break;

            default:
                throw new UnsupportedOperationException("Cannot update URL: " + uri);
        }

        int count = createDatabaseModifier(db, hasReadVoicemailPermission).update(uri, Tables.CALLS,
                values, selectionBuilder.build(), selectionArgs);

        String logStr = String.format(Locale. getDefault(),
                "update uid/pid=%d/%d, uri=%s, numChanged=%d",
                Binder.getCallingUid(), Binder.getCallingPid(), uri, count);
        Log.i(TAG, logStr);
        mLocalLog.log(logStr);

        return count;
    }

    private int deleteInternal(Uri uri, String selection, String[] selectionArgs) {
        if (VERBOSE_LOGGING) {
            Log.v(TAG, "delete: uri=" + uri +
                    "  selection=[" + selection + "]  args=" + Arrays.toString(selectionArgs) +
                    " CPID=" + Binder.getCallingPid() +
                    " CUID=" + Binder.getCallingUid() +
                    " User=" + UserUtils.getCurrentUserHandle(getContext()));
        }
        waitForAccess(mReadAccessLatch);
        SelectionBuilder selectionBuilder = new SelectionBuilder(selection);
        checkVoicemailPermissionAndAddRestriction(uri, selectionBuilder, false /*isQuery*/);

        boolean hasReadVoicemailPermission =
                mVoicemailPermissions.callerHasReadAccess(getCallingPackage());
        final SQLiteDatabase db = mDbHelper.getWritableDatabase();
        final int matchedUriId = sURIMatcher.match(uri);
        switch (matchedUriId) {
            case CALLS:
                int count =  createDatabaseModifier(db, hasReadVoicemailPermission).delete(
                        Tables.CALLS, selectionBuilder.build(), selectionArgs);
                String logStr = String.format(Locale. getDefault(),
                        "delete uid/pid=%d/%d, uri=%s, numChanged=%d",
                        Binder.getCallingUid(), Binder.getCallingPid(), uri, count);
                Log.i(TAG, logStr);
                mLocalLog.log(logStr);
                return count;
            case CALL_COMPOSER_PICTURE:
                // TODO(hallliu): implement deletion of file when the corresponding calllog entry
                // gets deleted as well.
                return deleteCallComposerPicture(uri);
            default:
                throw new UnsupportedOperationException("Cannot delete that URL: " + uri);
        }
    }

    /**
     * Returns a {@link DatabaseModifier} that takes care of sending necessary notifications
     * after the operation is performed.
     */
    private DatabaseModifier createDatabaseModifier(SQLiteDatabase db, boolean hasReadVoicemail) {
        return new DbModifierWithNotification(Tables.CALLS, db, null, hasReadVoicemail,
                getContext());
    }

    /**
     * Same as {@link #createDatabaseModifier(SQLiteDatabase)} but used for insert helper operations
     * only.
     */
    private DatabaseModifier createDatabaseModifier(DatabaseUtils.InsertHelper insertHelper) {
        return new DbModifierWithNotification(Tables.CALLS, insertHelper, getContext());
    }

    private static final Integer VOICEMAIL_TYPE = new Integer(Calls.VOICEMAIL_TYPE);
    private boolean hasVoicemailValue(ContentValues values) {
        return VOICEMAIL_TYPE.equals(values.getAsInteger(Calls.TYPE));
    }

    /**
     * Checks if the supplied uri requests to include voicemails and take appropriate
     * action.
     * <p> If voicemail is requested, then check for voicemail permissions. Otherwise
     * modify the selection to restrict to non-voicemail entries only.
     */
    private void checkVoicemailPermissionAndAddRestriction(Uri uri,
            SelectionBuilder selectionBuilder, boolean isQuery) {
        if (isAllowVoicemailRequest(uri)) {
            if (isQuery) {
                mVoicemailPermissions.checkCallerHasReadAccess(getCallingPackage());
            } else {
                mVoicemailPermissions.checkCallerHasWriteAccess(getCallingPackage());
            }
        } else {
            selectionBuilder.addClause(EXCLUDE_VOICEMAIL_SELECTION);
        }
    }

    /**
     * Determines if the supplied uri has the request to allow voicemails to be
     * included.
     */
    private boolean isAllowVoicemailRequest(Uri uri) {
        return uri.getBooleanQueryParameter(Calls.ALLOW_VOICEMAILS_PARAM_KEY, false);
    }

    /**
     * Checks to ensure that the given uri has allow_voicemail set. Used by
     * insert and update operations to check that ContentValues with voicemail
     * call type must use the voicemail uri.
     * @throws IllegalArgumentException if allow_voicemail is not set.
     */
    private void checkIsAllowVoicemailRequest(Uri uri) {
        if (!isAllowVoicemailRequest(uri)) {
            throw new IllegalArgumentException(
                    String.format("Uri %s cannot be used for voicemail record." +
                            " Please set '%s=true' in the uri.", uri,
                            Calls.ALLOW_VOICEMAILS_PARAM_KEY));
        }
    }

   /**
    * Parses the call Id from the given uri, assuming that this is a uri that
    * matches CALLS_ID. For other uri types the behaviour is undefined.
    * @throws IllegalArgumentException if the id included in the Uri is not a valid long value.
    */
    private long parseCallIdFromUri(Uri uri) {
        try {
            return Long.parseLong(uri.getPathSegments().get(1));
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Invalid call id in uri: " + uri, e);
        }
    }

    /**
     * Sync all calllog entries that were inserted
     */
    private void syncEntries() {
        if (isShadow()) {
            return; // It's the shadow provider itself.  No copying.
        }

        final UserManager userManager = UserUtils.getUserManager(getContext());
        final int myUserId = userManager.getProcessUserId();

        // TODO: http://b/24944959
        if (!Calls.shouldHaveSharedCallLogEntries(getContext(), userManager, myUserId)) {
            return;
        }

        // See the comment in Calls.addCall() for the logic.

        if (userManager.isSystemUser()) {
            // If it's the system user, just copy from shadow.
            syncEntriesFrom(UserHandle.USER_SYSTEM, /* sourceIsShadow = */ true,
                    /* forAllUsersOnly =*/ false);
        } else {
            // Otherwise, copy from system's real provider, as well as self's shadow.
            syncEntriesFrom(UserHandle.USER_SYSTEM, /* sourceIsShadow = */ false,
                    /* forAllUsersOnly =*/ true);
            syncEntriesFrom(myUserId, /* sourceIsShadow = */ true,
                    /* forAllUsersOnly =*/ false);
        }
    }

    private void syncEntriesFrom(int sourceUserId, boolean sourceIsShadow,
            boolean forAllUsersOnly) {

        final Uri sourceUri = sourceIsShadow ? Calls.SHADOW_CONTENT_URI : Calls.CONTENT_URI;

        final long lastSyncTime = getLastSyncTime(sourceIsShadow);

        final Uri uri = ContentProvider.maybeAddUserId(sourceUri, sourceUserId);
        final long newestTimeStamp;
        final ContentResolver cr = getContext().getContentResolver();

        final StringBuilder selection = new StringBuilder();

        selection.append(
                "(" + EXCLUDE_VOICEMAIL_SELECTION + ") AND (" + MORE_RECENT_THAN_SELECTION + ")");

        if (forAllUsersOnly) {
            selection.append(" AND (" + Calls.ADD_FOR_ALL_USERS + "=1)");
        }

        final Cursor cursor = cr.query(
                uri,
                CALL_LOG_SYNC_PROJECTION,
                selection.toString(),
                new String[] {String.valueOf(lastSyncTime)},
                Calls.DATE + " ASC");
        if (cursor == null) {
            Log.i(TAG, String.format(Locale.getDefault(),
                    "syncEntriesFrom: fromUserId=%d, srcIsShadow=%b, forAllUsers=%b; nothing to "
                            + "sync",
                    sourceUserId, sourceIsShadow, forAllUsersOnly));
            return;
        }
        try {
            newestTimeStamp = copyEntriesFromCursor(cursor, lastSyncTime, sourceIsShadow);
            Log.i(TAG,
                    String.format(Locale.getDefault(),
                            "syncEntriesFrom: fromUserId=%d, srcIsShadow=%b, forAllUsers=%b; "
                                    + "previousTimeStamp=%d, newTimeStamp=%d, entries=%d",
                            sourceUserId, sourceIsShadow, forAllUsersOnly, lastSyncTime,
                            newestTimeStamp,
                            cursor.getCount()));
        } finally {
            cursor.close();
        }
        if (sourceIsShadow) {
            // delete all entries in shadow.
            cr.delete(uri, Calls.DATE + "<= ?", new String[] {String.valueOf(newestTimeStamp)});
        }

        try {
            syncCallComposerPics(sourceUserId, sourceIsShadow, forAllUsersOnly, lastSyncTime);
        } catch (Exception e) {
            // Catch any exceptions to make sure we don't bring down the entire process if something
            // goes wrong
            StringWriter w = new StringWriter();
            PrintWriter pw = new PrintWriter(w);
            e.printStackTrace(pw);
            Log.e(TAG, "Caught exception syncing call composer pics: " + e
                    + "\n" + pw.toString());
        }
    }

    private void syncCallComposerPics(int sourceUserId, boolean sourceIsShadow,
            boolean forAllUsersOnly, long lastSyncTime) {
        Log.i(TAG, "Syncing call composer pics -- source user=" + sourceUserId + ","
                + " isShadow=" + sourceIsShadow + ", forAllUser=" + forAllUsersOnly);
        ContentResolver contentResolver = getContext().getContentResolver();
        Bundle args = new Bundle();
        args.putLong(EXTRA_SINCE_DATE, lastSyncTime);
        args.putBoolean(EXTRA_ALL_USERS_ONLY, forAllUsersOnly);
        args.putBoolean(EXTRA_IS_SHADOW, sourceIsShadow);
        Uri queryUri = ContentProvider.maybeAddUserId(
                sourceIsShadow
                        ? CallLog.SHADOW_CALL_COMPOSER_PICTURE_URI
                        : CallLog.CALL_COMPOSER_PICTURE_URI,
                sourceUserId);
        Bundle result = contentResolver.call(queryUri, GET_CALL_COMPOSER_IMAGE_URIS, null, args);
        if (result == null || !result.containsKey(EXTRA_RESULT_URIS)) {
            Log.e(TAG, "Failed to sync call composer pics -- invalid return from call()");
            return;
        }
        List<Uri> urisToCopy = result.getParcelableArrayList(EXTRA_RESULT_URIS);
        Log.i(TAG, "Syncing call composer pics -- got " + urisToCopy);
        for (Uri uri : urisToCopy) {
            try {
                Uri uriWithUser = ContentProvider.maybeAddUserId(uri, sourceUserId);
                Path callComposerDir = getCallComposerPictureDirectory(getContext(), false);
                Path newFilePath = callComposerDir.resolve(uri.getLastPathSegment());
                enforceValidCallLogPath(callComposerDir, newFilePath,"syncCallComposerPics");
                try (ParcelFileDescriptor remoteFile = contentResolver.openFile(uriWithUser,
                        "r", null);
                     OutputStream localOut =
                             Files.newOutputStream(newFilePath, StandardOpenOption.CREATE_NEW)) {
                    FileInputStream input = new FileInputStream(remoteFile.getFileDescriptor());
                    byte[] buffer = new byte[1 << 14]; // 16kb
                    while (true) {
                        int numRead = input.read(buffer);
                        if (numRead < 0) {
                            break;
                        }
                        localOut.write(buffer, 0, numRead);
                    }
                }
                contentResolver.delete(uriWithUser, null);
            } catch (IOException e) {
                Log.e(TAG, "IOException while syncing call composer pics: " + e);
                // Keep going and get as many as we can.
            }
        }
    }
    /**
     * Un-hides any hidden call log entries that are associated with the specified handle.
     *
     * @param handle The handle to the newly registered {@link android.telecom.PhoneAccount}.
     */
    private void adjustForNewPhoneAccountInternal(PhoneAccountHandle handle) {
        String[] handleArgs =
                new String[] { handle.getComponentName().flattenToString(), handle.getId() };

        // Check to see if any entries exist for this handle. If so (not empty), run the un-hiding
        // update. If not, then try to identify the call from the phone number.
        Cursor cursor = query(Calls.CONTENT_URI, MINIMAL_PROJECTION,
                Calls.PHONE_ACCOUNT_COMPONENT_NAME + " =? AND " + Calls.PHONE_ACCOUNT_ID + " =?",
                handleArgs, null);

        if (cursor != null) {
            try {
                if (cursor.getCount() >= 1) {
                    // run un-hiding process based on phone account
                    mDbHelper.getWritableDatabase().execSQL(
                            UNHIDE_BY_PHONE_ACCOUNT_QUERY, handleArgs);
                } else {
                    TelecomManager tm = getContext().getSystemService(TelecomManager.class);
                    if (tm != null) {
                        PhoneAccount account = tm.getPhoneAccount(handle);
                        if (account != null && account.getAddress() != null) {
                            // We did not find any items for the specific phone account, so run the
                            // query based on the phone number instead.
                            mDbHelper.getWritableDatabase().execSQL(UNHIDE_BY_ADDRESS_QUERY,
                                    new String[] { account.getAddress().toString() });
                        }

                    }
                }
            } finally {
                cursor.close();
            }
        }
    }

    /**
     * @param cursor to copy call log entries from
     */
    @VisibleForTesting
    long copyEntriesFromCursor(Cursor cursor, long lastSyncTime, boolean forShadow) {
        long latestTimestamp = 0;
        final ContentValues values = new ContentValues();
        final SQLiteDatabase db = mDbHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            final String[] args = new String[2];
            cursor.moveToPosition(-1);
            while (cursor.moveToNext()) {
                values.clear();
                DatabaseUtils.cursorRowToContentValues(cursor, values);

                final String startTime = values.getAsString(Calls.DATE);
                final String number = values.getAsString(Calls.NUMBER);

                if (startTime == null || number == null) {
                    continue;
                }

                if (cursor.isLast()) {
                    try {
                        latestTimestamp = Long.valueOf(startTime);
                    } catch (NumberFormatException e) {
                        Log.e(TAG, "Call log entry does not contain valid start time: "
                                + startTime);
                    }
                }

                // Avoid duplicating an already existing entry (which is uniquely identified by
                // the number, and the start time)
                args[0] = startTime;
                args[1] = number;
                if (DatabaseUtils.queryNumEntries(db, Tables.CALLS,
                        Calls.DATE + " = ? AND " + Calls.NUMBER + " = ?", args) > 0) {
                    continue;
                }

                db.insert(Tables.CALLS, null, values);
            }

            if (latestTimestamp > lastSyncTime) {
                setLastTimeSynced(latestTimestamp, forShadow);
            }

            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
        return latestTimestamp;
    }

    private static String getLastSyncTimePropertyName(boolean forShadow) {
        return forShadow
                ? DbProperties.CALL_LOG_LAST_SYNCED_FOR_SHADOW
                : DbProperties.CALL_LOG_LAST_SYNCED;
    }

    @VisibleForTesting
    long getLastSyncTime(boolean forShadow) {
        try {
            return Long.valueOf(mDbHelper.getProperty(getLastSyncTimePropertyName(forShadow), "0"));
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    private void setLastTimeSynced(long time, boolean forShadow) {
        mDbHelper.setProperty(getLastSyncTimePropertyName(forShadow), String.valueOf(time));
    }

    private static void waitForAccess(CountDownLatch latch) {
        if (latch == null) {
            return;
        }

        while (true) {
            try {
                latch.await();
                return;
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    @VisibleForTesting
    protected void performBackgroundTask(int task, Object arg) {
        if (task == BACKGROUND_TASK_INITIALIZE) {
            try {
                mDbHelper.updatePhoneAccountHandleMigrationPendingStatus();
                if (mDbHelper.getPhoneAccountHandleMigrationUtils()
                        .isPhoneAccountMigrationPending()) {
                    Log.i(TAG, "performBackgroundTask for pending PhoneAccountHandle migration");
                    mDbHelper.migrateIccIdToSubId();
                }
                syncEntries();
            } finally {
                mReadAccessLatch.countDown();
            }
        } else if (task == BACKGROUND_TASK_ADJUST_PHONE_ACCOUNT) {
            Log.i(TAG, "performBackgroundTask for unhide PhoneAccountHandles");
            adjustForNewPhoneAccountInternal((PhoneAccountHandle) arg);
        } else if (task == BACKGROUND_TASK_MIGRATE_PHONE_ACCOUNT_HANDLES) {
            PhoneAccountHandle phoneAccountHandle = (PhoneAccountHandle) arg;
            String iccId = null;
            try {
                SubscriptionInfo info = mSubscriptionManager.getActiveSubscriptionInfo(
                        Integer.parseInt(phoneAccountHandle.getId()));
                if (info != null) {
                    iccId = info.getIccId();
                }
            } catch (NumberFormatException nfe) {
                // Ignore the exception, iccId will remain null and be handled below.
            }
            if (iccId == null) {
                Log.i(TAG, "ACTION_PHONE_ACCOUNT_REGISTERED received null IccId.");
            } else {
                Log.i(TAG, "ACTION_PHONE_ACCOUNT_REGISTERED received for migrating phone"
                        + " account handle SubId: " + phoneAccountHandle.getId());
                mDbHelper.migratePendingPhoneAccountHandles(iccId, phoneAccountHandle.getId());
            }
        }
    }

    @Override
    public void shutdown() {
        mTaskScheduler.shutdownForTest();
    }

    @Override
    public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
        mStats.dump(writer, "  ");
        writer.println();
        writer.println("Latest call log activity:");
        mLocalLog.dump(writer);
    }

    /**
     *  Enforces a stricter check on what files the CallLogProvider can perform file operations on.
     * @param rootPath where all valid new/existing paths should pass through.
     * @param pathToCheck newly created path that is requesting a file op. (open, delete, etc.)
     * @param callingMethod the calling method.  Used only for debugging purposes.
     */
    private void enforceValidCallLogPath(Path rootPath, Path pathToCheck, String callingMethod){
        if (!FileUtilities.isSameOrSubDirectory(rootPath.toFile(), pathToCheck.toFile())) {
            EventLog.writeEvent(0x534e4554, "219015884", Binder.getCallingUid(),
                    (callingMethod + ": invalid uri passed"));
            throw new SecurityException(
                    FileUtilities.INVALID_CALL_LOG_PATH_EXCEPTION_MESSAGE + pathToCheck);
        }
    }
}