This file is indexed.

/usr/lib/thunderbird-addons/extensions/{e2fda1a4-762b-4020-b5ad-a41df1933103}/calendar-js/calCalendarManager.js is in xul-ext-lightning 1:24.4.0+build1-0ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

Components.utils.import("resource://gre/modules/AddonManager.jsm");
Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://calendar/modules/calUtils.jsm");
Components.utils.import("resource://calendar/modules/calProviderUtils.jsm");

const REGISTRY_BRANCH = "calendar.registry.";
const DB_SCHEMA_VERSION = 10;

function calCalendarManager() {
    this.wrappedJSObject = this;
    this.mObservers = new calListenerBag(Components.interfaces.calICalendarManagerObserver);
    this.mCalendarObservers = new calListenerBag(Components.interfaces.calIObserver);
}

const calCalendarManagerClassID = Components.ID("{f42585e7-e736-4600-985d-9624c1c51992}");
const calCalendarManagerInterfaces = [
    Components.interfaces.calICalendarManager,
    Components.interfaces.calIStartupService,
    Components.interfaces.nsIObserver,
];
calCalendarManager.prototype = {
    classID: calCalendarManagerClassID,
    QueryInterface: XPCOMUtils.generateQI(calCalendarManagerInterfaces),
    classInfo: XPCOMUtils.generateCI({
        classID: calCalendarManagerClassID,
        contractID: "@mozilla.org/calendar/manager;1",
        classDescription: "Calendar Manager",
        interfaces: calCalendarManagerInterfaces,
        flags: Components.interfaces.nsIClassInfo.SINGLETON
    }),

    get networkCalendarCount() this.mNetworkCalendarCount,
    get readOnlyCalendarCount() this.mReadonlyCalendarCount,
    get calendarCount() this.mCalendarCount,

    // calIStartupService:
    startup: function ccm_startup(aCompleteListener) {
        AddonManager.addAddonListener(gCalendarManagerAddonListener);
        this.checkAndMigrateDB();
        this.mCache = null;
        this.mCalObservers = null;
        this.mRefreshTimer = {};
        this.setupOfflineObservers();
        if (cal.isSunbird()) {
            this.loginMasterPassword();
        }
        this.mNetworkCalendarCount = 0;
        this.mReadonlyCalendarCount = 0;
        this.mCalendarCount = 0;

        Services.obs.addObserver(this, "http-on-modify-request", false);

        // We only add the observer if the pref is set and only check for the
        // pref on startup to avoid checking for every http request
        if (cal.getPrefSafe("calendar.network.multirealm", false)) {
            Services.obs.addObserver(this, "http-on-examine-response", false);
        }

        aCompleteListener.onResult(null, Components.results.NS_OK);
    },

    shutdown: function ccm_shutdown(aCompleteListener) {
        for each (var calendar in this.mCache) {
            calendar.removeObserver(this.mCalObservers[calendar.id]);
        }

        this.cleanupOfflineObservers();

        Services.obs.removeObserver(this, "http-on-modify-request");

        AddonManager.removeAddonListener(gCalendarManagerAddonListener);

        // Remove the observer if the pref is set. This might fail when the
        // user flips the pref, but we assume he is going to restart anyway
        // afterwards.
        if (cal.getPrefSafe("calendar.network.multirealm", false)) {
            Services.obs.removeObserver(this, "http-on-examine-response");
        }

        aCompleteListener.onResult(null, Components.results.NS_OK);
    },


    setupOfflineObservers: function ccm_setupOfflineObservers() {
        Services.obs.addObserver(this, "network:offline-status-changed", false);
    },

    cleanupOfflineObservers: function ccm_cleanupOfflineObservers() {
        Services.obs.removeObserver(this, "network:offline-status-changed");
    },

    loginMasterPassword: function ccm_loginMasterPassword() {
        // Try to avoid the multiple master password prompts on startup scenario
        // by prompting for the master password upfront.
        let token = Components.classes["@mozilla.org/security/pk11tokendb;1"]
                              .getService(Components.interfaces.nsIPK11TokenDB)
                              .getInternalKeyToken();

        // Only log in to the internal token if it is already initialized,
        // otherwise we get a "Change Master Password" dialog.
        try {
            if (!token.needsUserInit) {
                token.login(false);
            }
        } catch (ex) {
            // If user cancels an exception is expected.
        }
    },

    observe: function ccm_observe(aSubject, aTopic, aData) {
        switch (aTopic) {
            case "timer-callback":
                // Refresh all the calendars that can be refreshed.
                var cals = this.getCalendars({});
                for each (var calendar in cals) {
                    if (!calendar.getProperty("disabled") && calendar.canRefresh) {
                        calendar.refresh();
                    }
                }
                break;
            case "network:offline-status-changed":
                for each (var calendar in this.mCache) {
                    if (calendar instanceof calCachedCalendar) {
                        calendar.onOfflineStatusChanged(aData == "offline");
                    }
                }
                break;
            case "http-on-examine-response":
                try {
                    let channel = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);
                    if (channel.notificationCallbacks) {
                        // We use the notification callbacks to get the calendar interface,
                        // which likely works for our requests since getInterface is called
                        // from the calendar provider context.
                        let authHeader = channel.getResponseHeader("WWW-Authenticate");
                        let calendar = channel.notificationCallbacks
                                              .getInterface(Components.interfaces.calICalendar);
                        if (calendar && !calendar.getProperty("capabilities.realmrewrite.disabled")) {
                            // The provider may choose to explicitly disable the
                            // rewriting, for example if all calendars on a
                            // domain have the same credentials
                            let escapedName = calendar.name.replace('\\', '\\\\', 'g')
                                                           .replace('"','\\"', 'g');
                            authHeader = appendToRealm(authHeader, "(" + escapedName + ")");
                            channel.setResponseHeader("WWW-Authenticate", authHeader, false);
                        }
                    }
                } catch (e if e.result == Components.results.NS_NOINTERFACE ||
                              e.result == Components.results.NS_ERROR_NOT_AVAILABLE) {
                    // Possible reasons we got here:
                    // - Its not a http channel (wtf? Oh well)
                    // - The owner is not a calICalendar (looks like its not our deal)
                    // - The WWW-Authenticate header is missing (thats ok)
                }
                break;
            case "http-on-modify-request":
                // Unfortunately, the ability to do this with a general pref has
                // been removed. Calendar servers might still want to know what
                // client is used for access, so add our UA String to each
                // request.
                let httpChannel = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);
                try {
                    // NOTE: For some reason, this observer call doesn't have
                    // the "cal" namespace defined
                    let ua = httpChannel.getRequestHeader("User-Agent");
                    let calUAString = getPrefSafe("calendar.useragent.extra");
                    if (calUAString && ua.indexOf(calUAString) < 0) {
                        // User-Agent is not a mergeable header. We need to
                        // merge the user agent ourselves.
                        httpChannel.setRequestHeader("User-Agent",
                                                     ua + " " + calUAString,
                                                     false);
                    }
                } catch (e if e.result == Components.results.NS_ERROR_NOT_AVAILABLE) {
                    // We swallow this error since it means the User Agent
                    // header is not set. We don't want to force it to be set.
                }
                break;
        }
    },

    //
    // DB migration code begins here
    //

    upgradeDB: function(oldVersion, db) {
        // some common helpers
        function addColumn(db_, tableName, colName, colType) {
            db_.executeSimpleSQL("ALTER TABLE " + tableName + " ADD COLUMN " + colName + " " + colType);
        }

        if (oldVersion < 6) {
            dump ("**** Upgrading calCalendarManager schema to 6\n");

            // Schema changes in v6:
            //
            // - Change all STRING columns to TEXT to avoid SQLite's
            //   "feature" where it will automatically convert strings to
            //   numbers (ex: 10e4 -> 10000). See bug 333688.

            // Create the new tables.

            try {
                db.executeSimpleSQL("DROP TABLE cal_calendars_v6; DROP TABLE cal_calendars_prefs_v6;");
            } catch (e) {
                // We should get exceptions for trying to drop tables
                // that don't (shouldn't) exist.
            }

            db.executeSimpleSQL("CREATE TABLE cal_calendars_v6 " +
                                "(id   INTEGER PRIMARY KEY," +
                                " type TEXT," +
                                " uri  TEXT);");

            db.executeSimpleSQL("CREATE TABLE cal_calendars_prefs_v6 " +
                                "(id       INTEGER PRIMARY KEY," +
                                " calendar INTEGER," +
                                " name     TEXT," +
                                " value    TEXT);");

            // Copy in the data.
            var calendarCols = ["id", "type", "uri"];
            var calendarPrefsCols = ["id", "calendar", "name", "value"];

            db.executeSimpleSQL("INSERT INTO cal_calendars_v6(" + calendarCols.join(",") + ") " +
                                "     SELECT " + calendarCols.join(",") +
                                "       FROM cal_calendars");

            db.executeSimpleSQL("INSERT INTO cal_calendars_prefs_v6(" + calendarPrefsCols.join(",") + ") " +
                                "     SELECT " + calendarPrefsCols.join(",") +
                                "       FROM cal_calendars_prefs");

            // Delete each old table and rename the new ones to use the
            // old tables' names.
            var tableNames = ["cal_calendars", "cal_calendars_prefs"];

            for (var i in tableNames) {
                db.executeSimpleSQL("DROP TABLE " + tableNames[i] + ";" +
                                    "ALTER TABLE " + tableNames[i] + "_v6 " +
                                    "  RENAME TO " + tableNames[i] + ";");
            }

            oldVersion = 8;
        }

        if (oldVersion < DB_SCHEMA_VERSION) {
            dump ("**** Upgrading calCalendarManager schema to 9/10\n");

            if (db.tableExists("cal_calmgr_schema_version")) {
                // Set only once the last time to v10, so the version check works in calendar 0.8.
                // In calendar 0.9 and following, the provider itself will check its version
                // on initialization and notify the calendar whether it's usable or not.
                db.executeSimpleSQL("UPDATE cal_calmgr_schema_version SET version = " + DB_SCHEMA_VERSION + ";");
            } else {
                // Schema changes in v9:
                //
                // - Decouple schema version from storage calendar
                // Create the new tables.
                db.executeSimpleSQL("CREATE TABLE cal_calmgr_schema_version (version INTEGER);");
                db.executeSimpleSQL("INSERT INTO cal_calmgr_schema_version VALUES(" + DB_SCHEMA_VERSION + ")");
            }
        }
    },

    migrateDB: function calmgr_migrateDB(db) {
        let selectCalendars = db.createStatement("SELECT * FROM cal_calendars");
        let selectPrefs = db.createStatement("SELECT name, value FROM cal_calendars_prefs WHERE calendar = :calendar");
        try {
            let sortOrder = {};

            while (selectCalendars.executeStep()) {
                let id = cal.getUUID(); // use fresh uuids
                cal.setPref(getPrefBranchFor(id) + "type", selectCalendars.row.type);
                cal.setPref(getPrefBranchFor(id) + "uri", selectCalendars.row.uri);
                // the former id served as sort position:
                sortOrder[selectCalendars.row.id] = id;
                // move over prefs:
                selectPrefs.params.calendar = selectCalendars.row.id;
                while (selectPrefs.executeStep()) {
                    let name = selectPrefs.row.name.toLowerCase(); // may come lower case, so force it to be
                    let value = selectPrefs.row.value;
                    switch (name) {
                        case "readonly":
                            cal.setPref(getPrefBranchFor(id) + "readOnly", value == "true");
                            break;
                        case "relaxedmode":
                            cal.setPref(getPrefBranchFor(id) + "relaxedMode", value == "true");
                            break;
                        case "suppressalarms":
                            cal.setPref(getPrefBranchFor(id) + "suppressAlarms", value == "true");
                            break;
                        case "disabled":
                        case "cache.supported":
                        case "auto-enabled":
                        case "cache.enabled":
                        case "lightning-main-in-composite":
                        case "calendar-main-in-composite":
                        case "lightning-main-default":
                        case "calendar-main-default":
                            cal.setPref(getPrefBranchFor(id) + name, value == "true");
                            break;
                        case "backup-time":
                        case "uniquenum":
                            cal.setPref(getPrefBranchFor(id) + name, Number(value));
                            break;
                        case "name":
                            cal.setLocalizedPref(getPrefBranchFor(id) + name, value);
                            break;
                        default: // keep as string
                            cal.setPref(getPrefBranchFor(id) + name, value);
                            break;
                    }
                }
                selectPrefs.reset();
            }

            let sortOrderAr = [];
            for each (let s in sortOrder) {
                sortOrderAr.push(s);
            }
            cal.setPref("calendar.list.sortOrder", sortOrderAr.join(" "));
            flushPrefs();

        } finally {
            selectPrefs.reset();
            selectCalendars.reset();
        }
    },

    checkAndMigrateDB: function calmgr_checkAndMigrateDB() {
        let storageSdb = Services.dirsvc.get("ProfD", Components.interfaces.nsILocalFile);
        storageSdb.append("storage.sdb");
        let db = Services.storage.openDatabase(storageSdb);

        db.beginTransactionAs(Components.interfaces.mozIStorageConnection.TRANSACTION_EXCLUSIVE);
        try {
            if (db.tableExists("cal_calendars_prefs")) {
                // Check if we need to upgrade:
                let version = this.getSchemaVersion(db);
                //cal.LOG("*** Calendar schema version is: " + version);
                if (version < DB_SCHEMA_VERSION) {
                    this.upgradeDB(version, db);
                }

                this.migrateDB(db);

                db.executeSimpleSQL("DROP TABLE cal_calendars; " +
                                    "DROP TABLE cal_calendars_prefs; " +
                                    "DROP TABLE cal_calmgr_schema_version;");
            }

            if (!db.tableExists("cal_calendars")) {
                // create dummy cal_calendars, so previous versions (pre 1.0pre) run into the schema check:
                db.createTable("cal_calendars", "id INTEGER");
                // let schema checks always fail, we cannot take the shared cal_calendar_schema_version:
                db.createTable("cal_calmgr_schema_version", "version INTEGER");
                db.executeSimpleSQL("INSERT INTO cal_calmgr_schema_version VALUES(" + (DB_SCHEMA_VERSION + 1) + ")");
                db.commitTransaction();
            } else {
                db.rollbackTransaction();
            }
        } catch (exc) {
            db.rollbackTransaction();
            throw exc;
        } finally {
            db.close();
        }
    },

    /**
     * @return      db schema version
     * @exception   various, depending on error
     */
    getSchemaVersion: function calMgrGetSchemaVersion(db) {
        var stmt;
        var version = null;

        var table;
        if (db.tableExists("cal_calmgr_schema_version")) {
            table = "cal_calmgr_schema_version";
        } else {
            // Fall back to the old schema table
            table = "cal_calendar_schema_version";
        }

        try {
            stmt = db.createStatement("SELECT version FROM " + table + " LIMIT 1");
            if (stmt.executeStep()) {
                version = stmt.row.version;
            }
            stmt.reset();

            if (version !== null) {
                // This is the only place to leave this function gracefully.
                return version;
            }
        } catch (e) {
            if (stmt) {
                stmt.reset();
            }
            cal.ERROR("++++++++++++ calMgrGetSchemaVersion() error: " + db.lastErrorString);
            Components.utils.reportError("Error getting calendar schema version! DB Error: " + db.lastErrorString);
            throw e;
        }

        throw table + " SELECT returned no results";
    },

    //
    // / DB migration code ends here
    //

    alertAndQuit: function cmgr_alertAndQuit() {
        // If we're Lightning, we want to include the extension name
        // in the error message rather than blaming Thunderbird.
        var errorBoxTitle;
        var errorBoxText;
        var errorBoxButtonLabel;
        var hostAppName = calGetString("brand", "brandShortName", null, "branding");
        if (isSunbird()) {
            errorBoxTitle = calGetString("calendar", "tooNewSchemaErrorBoxTitle", [hostAppName]);
            errorBoxText = calGetString("calendar", "tooNewSchemaErrorBoxTextSunbird", [hostAppName]);
            errorBoxButtonLabel = calGetString("calendar", "tooNewSchemaButtonQuit", [hostAppName]);
        } else {
            var calAppName = calGetString("lightning", "brandShortName", null, "lightning");
            errorBoxTitle = calGetString("calendar", "tooNewSchemaErrorBoxTitle", [calAppName]);
            errorBoxText = calGetString("calendar", "tooNewSchemaErrorBoxTextLightning", [calAppName, hostAppName]);
            errorBoxButtonLabel = calGetString("calendar", "tooNewSchemaButtonRestart", [hostAppName]);
        }

        var promptSvc = Services.prompt;

        var errorBoxButtonFlags = (promptSvc.BUTTON_POS_0 *
                                   promptSvc.BUTTON_TITLE_IS_STRING +
                                   promptSvc.BUTTON_POS_0_DEFAULT);

        var choice = promptSvc.confirmEx(null,
                                         errorBoxTitle,
                                         errorBoxText,
                                         errorBoxButtonFlags,
                                         errorBoxButtonLabel,
                                         null, // No second button text
                                         null, // No third button text
                                         null, // No checkbox
                                         { value: false }); // Unnecessary checkbox state

        if (isSunbird()) {
            Services.startup.quit(Components.interfaces.nsIAppStartup.eForceQuit);
        } else {
            // Disable Lightning
            AddonManager.getAddonByID("{e2fda1a4-762b-4020-b5ad-a41df1933103}", function getLightningExt(aAddon) {
                aAddon.userDisabled = true;
                Services.startup.quit(Components.interfaces.nsIAppStartup.eRestart |
                    Components.interfaces.nsIAppStartup.eForceQuit);
            });
        }
    },

    /**
     * calICalendarManager interface
     */
    createCalendar: function cmgr_createCalendar(type, uri) {
        try {
            if (!Components.classes["@mozilla.org/calendar/calendar;1?type=" + type]) {
                // Don't notify the user with an extra dialog if the provider
                // interface is missing.
                return null;
            }
            let calendar = Components.classes["@mozilla.org/calendar/calendar;1?type=" + type]
                                     .createInstance(Components.interfaces.calICalendar);
            calendar.uri = uri;
            return calendar;
        } catch (ex) {
            let rc = ex;
            let uiMessage = ex;
            if (ex instanceof Components.interfaces.nsIException) {
                rc = ex.result;
                uiMessage = ex.message;
            }
            switch (rc) {
                case Components.interfaces.calIErrors.STORAGE_UNKNOWN_SCHEMA_ERROR:
                    // For now we alert and quit on schema errors like we've done before:
                    this.alertAndQuit();
                    return;
                case Components.interfaces.calIErrors.STORAGE_UNKNOWN_TIMEZONES_ERROR:
                    uiMessage = calGetString("calendar", "unknownTimezonesError", [uri.spec]);
                    break;
                default:
                    uiMessage = calGetString("calendar", "unableToCreateProvider", [uri.spec]);
                    break;
            }
            // Log the original exception via error console to provide more debug info
            cal.ERROR(ex);

            // Log the possibly translated message via the UI.
            let paramBlock = Components.classes["@mozilla.org/embedcomp/dialogparam;1"]
                                       .createInstance(Components.interfaces.nsIDialogParamBlock);
            paramBlock.SetNumberStrings(3);
            paramBlock.SetString(0, uiMessage);
            paramBlock.SetString(1, "0x" + rc.toString(0x10));
            paramBlock.SetString(2, ex);
            Services.ww.openWindow(null,
                                   "chrome://calendar/content/calendar-error-prompt.xul",
                                   "_blank",
                                   "chrome,dialog=yes,alwaysRaised=yes",
                                   paramBlock);
            return null;
        }
    },

    registerCalendar: function(calendar) {
        this.assureCache();

        // If the calendar is already registered, bail out
        cal.ASSERT(!calendar.id || !(calendar.id in this.mCache),
                   "[calCalendarManager::registerCalendar] calendar already registered!",
                   true);

        if (!calendar.id) {
            calendar.id = cal.getUUID();
        }

        cal.setPref(getPrefBranchFor(calendar.id) + "type", calendar.type);
        cal.setPref(getPrefBranchFor(calendar.id) + "uri", calendar.uri.spec);

        if ((calendar.getProperty("cache.supported") !== false) &&
            (calendar.getProperty("cache.enabled") ||
             calendar.getProperty("cache.always"))) {
            calendar = new calCachedCalendar(calendar);
        }

        this.setupCalendar(calendar);
        flushPrefs();

        if (!calendar.getProperty("disabled") && calendar.canRefresh) {
            calendar.refresh();
        }

        this.notifyObservers("onCalendarRegistered", [calendar]);
    },

    setupCalendar: function cmgr_setupCalendar(calendar) {
        this.mCache[calendar.id] = calendar;

        // Add an observer to track readonly-mode triggers
        var newObserver = new calMgrCalendarObserver(calendar, this);
        calendar.addObserver(newObserver);
        this.mCalObservers[calendar.id] = newObserver;

        // Set up statistics
        if (calendar.getProperty("requiresNetwork") !== false) {
            this.mNetworkCalendarCount++;
        }
        if (calendar.readOnly) {
            this.mReadonlyCalendarCount++;
        }
        this.mCalendarCount++;

        // Set up the refresh timer
        this.setupRefreshTimer(calendar);
    },

    setupRefreshTimer: function setupRefreshTimer(aCalendar) {
        // Add the refresh timer for this calendar
        let refreshInterval = aCalendar.getProperty("refreshInterval");
        if (refreshInterval === null) {
            // Default to 30 minutes, in case the value is missing
            refreshInterval = 30;
        }

        this.clearRefreshTimer(aCalendar);

        if (refreshInterval > 0) {
            this.mRefreshTimer[aCalendar.id] =
                Components.classes["@mozilla.org/timer;1"]
                          .createInstance(Components.interfaces.nsITimer);

            this.mRefreshTimer[aCalendar.id]
                .initWithCallback(new timerCallback(aCalendar),
                                  refreshInterval * 60000,
                                  Components.interfaces.nsITimer.TYPE_REPEATING_SLACK);
        }
    },

    clearRefreshTimer: function clearRefreshTimer(aCalendar) {
        if (aCalendar.id in this.mRefreshTimer &&
            this.mRefreshTimer[aCalendar.id]) {
            this.mRefreshTimer[aCalendar.id].cancel();
            delete this.mRefreshTimer[aCalendar.id]
        }
    },

    unregisterCalendar: function(calendar) {
        this.notifyObservers("onCalendarUnregistering", [calendar]);

        // calendar may be a calICalendar wrapper:
        if (calendar.wrappedJSObject instanceof calCachedCalendar) {
            calendar.wrappedJSObject.onCalendarUnregistering();
        }

        calendar.removeObserver(this.mCalObservers[calendar.id]);
        Services.prefs.deleteBranch(getPrefBranchFor(calendar.id));
        flushPrefs();

        if (this.mCache) {
            delete this.mCache[calendar.id];
        }

        if (calendar.readOnly) {
            this.mReadonlyCalendarCount--;
        }

        if (calendar.getProperty("requiresNetwork") !== false) {
            this.mNetworkCalendarCount--;
        }
        this.mCalendarCount--;

        this.clearRefreshTimer(calendar);
    },

    deleteCalendar: function(calendar) {
        /* check to see if calendar is unregistered first... */
        /* delete the calendar for good */
        if (this.mCache && (calendar.id in this.mCache)) {
            throw "Can't delete a registered calendar";
        }
        this.notifyObservers("onCalendarDeleting", [calendar]);

        // XXX This is a workaround for bug 351499. We should remove it once
        // we sort out the whole "delete" vs. "unsubscribe" UI thing.
        //
        // We only want to delete the contents of calendars from local
        // providers (storage and memory). Otherwise we may nuke someone's
        // calendar stored on a server when all they really wanted to do was
        // unsubscribe.
        let wrappedCalendar = cal.wrapInstance(calendar, Components.interfaces.calICalendarProvider);
        if (wrappedCalendar &&
            (wrappedCalendar.type == "storage" || wrappedCalendar.type == "memory")) {
            try {
                wrappedCalendar.deleteCalendar(calendar, null);
            } catch (e) {
                Components.utils.reportError("error purging calendar: " + e);
            }
        }
    },

    getCalendarById: function cmgr_getCalendarById(aId) {
        if (aId in this.mCache) {
            return this.mCache[aId];
        } else {
            return null;
        }
    },

    getCalendars: function cmgr_getCalendars(count) {
        this.assureCache();
        var calendars = [];
        for each (var calendar in this.mCache) {
            calendars.push(calendar);
        }
        count.value = calendars.length;
        return calendars;
    },

    assureCache: function cmgr_assureCache() {
        if (!this.mCache) {
            this.mCache = {};
            this.mCalObservers = {};

            let allCals = {};
            for each (let key in Services.prefs.getChildList(REGISTRY_BRANCH)) { // merge down all keys
                allCals[key.substring(0, key.indexOf(".", REGISTRY_BRANCH.length))] = true;
            }

            for (let calBranch in allCals) {
                let id = calBranch.substring(REGISTRY_BRANCH.length);
                let ctype = cal.getPrefSafe(calBranch + ".type", null);
                let curi = cal.getPrefSafe(calBranch + ".uri", null);

                try {
                    if (!ctype || !curi) { // sanity check
                        Services.prefs.deleteBranch(calBranch + ".");
                        continue;
                    }

                    let uri = cal.makeURL(curi);
                    let calendar = this.createCalendar(ctype, uri);
                    if (calendar) {
                        calendar.id = id;
                        if (calendar.getProperty("auto-enabled")) {
                            calendar.deleteProperty("disabled");
                            calendar.deleteProperty("auto-enabled");
                        }

                        if ((calendar.getProperty("cache.supported") !== false) &&
                            (calendar.getProperty("cache.enabled") ||
                             calendar.getProperty("cache.always"))) {
                            calendar = new calCachedCalendar(calendar);
                        }
                    } else { // create dummy calendar that stays disabled for this run:
                        calendar = new calDummyCalendar(ctype);
                        calendar.id = id;
                        calendar.uri = uri;
                        // try to enable on next startup if calendar has been enabled:
                        if (!calendar.getProperty("disabled")) {
                            calendar.setProperty("auto-enabled", true);
                        }
                        calendar.setProperty("disabled", true);
                    }

                    this.setupCalendar(calendar);
                } catch (exc) {
                    cal.ERROR("Can't create calendar for " + id + " (" + ctype + ", " + curi + "): " + exc);
                }
            }

            // do refreshing in a second step, when *all* calendars are already available
            // via getCalendars():
            for each (let calendar in this.mCache) {
                if (!calendar.getProperty("disabled") && calendar.canRefresh) {
                    calendar.refresh();
                }
            }
        }
    },

    getCalendarPref_: function(calendar, name) {
        cal.ASSERT(calendar, "Invalid Calendar!");
        cal.ASSERT(calendar.id !== null, "Calendar id needs to be set!");
        cal.ASSERT(name && name.length > 0, "Pref Name must be non-empty!");

        let branch = (getPrefBranchFor(calendar.id) + name);

        if ( name === "name" ) {
            return cal.getLocalizedPref(branch, null);
        }
        return cal.getPrefSafe(branch, null);
    },

    setCalendarPref_: function(calendar, name, value) {
        cal.ASSERT(calendar, "Invalid Calendar!");
        cal.ASSERT(calendar.id !== null, "Calendar id needs to be set!");
        cal.ASSERT(name && name.length > 0, "Pref Name must be non-empty!");

        let branch = (getPrefBranchFor(calendar.id) + name);
        // Delete before to allow pref-type changes:
        Services.prefs.deleteBranch(branch);

        if ( name === "name" ) {
            cal.setLocalizedPref(branch, value);
        } else {
            cal.setPref(branch, value);
        }
    },

    deleteCalendarPref_: function(calendar, name) {
        cal.ASSERT(calendar, "Invalid Calendar!");
        cal.ASSERT(calendar.id !== null, "Calendar id needs to be set!");
        cal.ASSERT(name && name.length > 0, "Pref Name must be non-empty!");
        Services.prefs.deleteBranch(getPrefBranchFor(calendar.id) + name);
    },

    mObservers: null,
    addObserver: function(aObserver) this.mObservers.add(aObserver),
    removeObserver: function(aObserver) this.mObservers.remove(aObserver),
    notifyObservers: function(functionName, args) this.mObservers.notify(functionName, args),

    mCalendarObservers: null,
    addCalendarObserver: function(aObserver) this.mCalendarObservers.add(aObserver),
    removeCalendarObserver: function(aObserver) this.mCalendarObservers.remove(aObserver),
    notifyCalendarObservers: function(functionName, args) this.mCalendarObservers.notify(functionName, args)
};

function equalMessage(msg1, msg2) {
    if (msg1.GetString(0) == msg2.GetString(0) &&
        msg1.GetString(1) == msg2.GetString(1) &&
        msg1.GetString(2) == msg2.GetString(2)) {
        return true;
    }
    return false;
}

function calMgrCalendarObserver(calendar, calMgr) {
    this.calendar = calendar;
    // We compare this to determine if the state actually changed.
    this.storedReadOnly = calendar.readOnly;
    this.announcedMessages = [];
    this.calMgr = calMgr;
}

calMgrCalendarObserver.prototype = {
    calendar: null,
    storedReadOnly: null,
    calMgr: null,

    QueryInterface: XPCOMUtils.generateQI([
        Components.interfaces.nsIWindowMediatorListener,
        Components.interfaces.calIObserver
    ]),

    // calIObserver:
    onStartBatch: function() this.calMgr.notifyCalendarObservers("onStartBatch", arguments),
    onEndBatch: function() this.calMgr.notifyCalendarObservers("onEndBatch", arguments),
    onLoad: function(calendar) this.calMgr.notifyCalendarObservers("onLoad", arguments),
    onAddItem: function(aItem) this.calMgr.notifyCalendarObservers("onAddItem", arguments),
    onModifyItem: function(aNewItem, aOldItem) this.calMgr.notifyCalendarObservers("onModifyItem", arguments),
    onDeleteItem: function(aDeletedItem) this.calMgr.notifyCalendarObservers("onDeleteItem", arguments),
    onError: function(aCalendar, aErrNo, aMessage) {
        this.calMgr.notifyCalendarObservers("onError", arguments);
        this.announceError(aCalendar, aErrNo, aMessage);
    },

    onPropertyChanged: function(aCalendar, aName, aValue, aOldValue) {
        this.calMgr.notifyCalendarObservers("onPropertyChanged", arguments);
        switch (aName) {
            case "requiresNetwork":
                this.calMgr.mNetworkCalendarCount += (aValue ? 1 : -1);
                break;
            case "readOnly":
                this.calMgr.mReadonlyCalendarCount += (aValue ? 1 : -1);
                break;
            case "refreshInterval":
                this.calMgr.setupRefreshTimer(aCalendar);
                break;
            case "cache.enabled":
                this.changeCalendarCache.apply(this, arguments);
                break;
            case "disabled":
                if (!aValue && aCalendar.canRefresh) {
                    aCalendar.refresh();
                }
                break;
        }
    },

    changeCalendarCache: function(aCalendar, aName, aValue, aOldValue) {
        aOldValue = aOldValue || false;
        aValue = aValue || false;

        if (aOldValue != aValue) {
            // Try to find the current sort order
            let sortOrderPref = cal.getPrefSafe("calendar.list.sortOrder", "").split(" ");
            let initialSortOrderPos = null;
            for (let i = 0; i < sortOrderPref.length; ++i) {
                if (sortOrderPref[i] == aCalendar.id) {
                    initialSortOrderPos = i;
                }
            }
            // Enabling or disabling cache on a calendar re-creates
            // it so the registerCalendar call can wrap/unwrap the
            // calCachedCalendar facade saving the user the need to
            // restart Thunderbird and making sure a new Id is used.
            this.calMgr.unregisterCalendar(aCalendar);
            this.calMgr.deleteCalendar(aCalendar);
            var newCal = this.calMgr.createCalendar(aCalendar.type,aCalendar.uri);
            newCal.name = aCalendar.name;

            // TODO: if properties get added this list will need to be adjusted,
            // ideally we should add a "getProperties" method to calICalendar.idl
            // to retrieve all non-transient properties for a calendar.
            let propsToCopy = [ "color",
                                "disabled",
                                "auto-enabled",
                                "cache.enabled",
                                "refreshInterval",
                                "suppressAlarms",
                                "calendar-main-in-composite",
                                "calendar-main-default",
                                "readOnly",
                                "imip.identity.key"];
            for each (let prop in propsToCopy ) {
              newCal.setProperty(prop,
                                 aCalendar.getProperty(prop));
            }

            if (initialSortOrderPos != null) {
                newCal.setProperty("initialSortOrderPos",
                                   initialSortOrderPos);
            }
            this.calMgr.registerCalendar(newCal);
        } else {
            if (aCalendar.wrappedJSObject instanceof calCachedCalendar) {
                // any attempt to switch this flag will reset the cached calendar;
                // could be useful for users in case the cache may be corrupted.
                aCalendar.wrappedJSObject.setupCachedCalendar();
            }
        }
    },

    onPropertyDeleting: function(aCalendar, aName) {
        this.onPropertyChanged(aCalendar, aName, false, true);
    },

    // Error announcer specific functions
    announceError: function(aCalendar, aErrNo, aMessage) {

        var paramBlock = Components.classes["@mozilla.org/embedcomp/dialogparam;1"]
                                   .createInstance(Components.interfaces.nsIDialogParamBlock);
        var props = Services.strings.createBundle("chrome://calendar/locale/calendar.properties");
        var errMsg;
        paramBlock.SetNumberStrings(3);
        if (!this.storedReadOnly && this.calendar.readOnly) {
            // Major errors change the calendar to readOnly
            errMsg = props.formatStringFromName("readOnlyMode", [this.calendar.name], 1);
        } else if (!this.storedReadOnly && !this.calendar.readOnly) {
            // Minor errors don't, but still tell the user something went wrong
            errMsg = props.formatStringFromName("minorError", [this.calendar.name], 1);
        } else {
            // The calendar was already in readOnly mode, but still tell the user
            errMsg = props.formatStringFromName("stillReadOnlyError", [this.calendar.name], 1);
        }

        // When possible, change the error number into its name, to
        // make it slightly more readable.
        var errCode = "0x"+aErrNo.toString(16);
        const calIErrors = Components.interfaces.calIErrors;
        // Check if it is worth enumerating all the error codes.
        if (aErrNo & calIErrors.ERROR_BASE) {
            for (var err in calIErrors) {
                if (calIErrors[err] == aErrNo) {
                    errCode = err;
                }
            }
        }

        var message;
        switch (aErrNo) {
            case calIErrors.CAL_UTF8_DECODING_FAILED:
                message = props.GetStringFromName("utf8DecodeError");
                break;
            case calIErrors.ICS_MALFORMEDDATA:
                message = props.GetStringFromName("icsMalformedError");
                break;
            case calIErrors.MODIFICATION_FAILED:
                errMsg = calGetString("calendar", "errorWriting", [aCalendar.name]);
             default:
                message = aMessage;
         }


        paramBlock.SetString(0, errMsg);
        paramBlock.SetString(1, errCode);
        paramBlock.SetString(2, message);

        this.storedReadOnly = this.calendar.readOnly;
        var errorCode = calGetString("calendar","errorCode", [errCode]);
        var errorDescription = calGetString("calendar","errorDescription", [message]);
        var summary = errMsg + " " + errorCode + ". " + errorDescription;

        // Log warnings in error console.
        // Report serious errors in both error console and in prompt window.
        var isSerious = (aErrNo == calIErrors.MODIFICATION_FAILED);
        if (!isSerious) {
            WARN(summary);
        } else {
            // Write error to console.
            Components.utils.reportError(summary);

            // silently don't do anything if this message already has
            // been announced without being acknowledged.
            if (this.announcedMessages.some(
                function(element, index, array) {
                    return equalMessage(paramBlock, element);
                })) {
                return;
            }

            // this message hasn't been announced recently, remember the
            // details of the message for future reference.
            this.announcedMessages.push(paramBlock);

            // Display in prompt window.
            var promptWindow =
                Services.ww.openWindow
                    (null, "chrome://calendar/content/calendar-error-prompt.xul",
                     "_blank", "chrome,dialog=yes,alwaysRaised=yes",
                     paramBlock);
            // Will remove paramBlock from announced messages when
            // promptWindow is closed.  (Closing fires unloaded event, but
            // promptWindow is also unloaded [to clean it?] before loading,
            // so wait for detected load event before detecting unload event
            // that signifies user closed this prompt window.)
            var observer = this;
            function awaitLoad(event) {
                // #2 loaded, remove load listener
                promptWindow.removeEventListener("load", awaitLoad, false);
                function awaitUnload(event) {
                    // #4 unloaded (user closed prompt window),
                    // remove paramBlock and unload listener.
                    try {
                        // remove the message that has been shown from
                        // the list of all announced messages.
                        observer.announcedMessages =
                            observer.announcedMessages.filter(function(msg) {
                                return !equalMessage(msg, paramBlock);
                            });
                        promptWindow.removeEventListener("unload", awaitUnload,
                                                         false);
                    } catch (e) {
                        Components.utils.reportError(e);
                    }
                }
                // #3 add unload listener (wait for user to close promptWindow)
                promptWindow.addEventListener("unload", awaitUnload, false);
            }
            // #1 add load listener
            promptWindow.addEventListener("load", awaitLoad, false);
        }
    }
};

function calDummyCalendar(type) {
    this.initProviderBase();
    this.type = type;
}
calDummyCalendar.prototype = {
    __proto__: cal.ProviderBase.prototype,

    getProperty: function calDummyCalendar_getProperty(aName) {
        switch (aName) {
            case "force-disabled":
                return true;
            default:
                return this.__proto__.__proto__.getProperty.apply(this, arguments);
        }
    }
};

function getPrefBranchFor(id) {
    return (REGISTRY_BRANCH + id + ".");
}

/**
 * Helper function to flush the preferences file. If the application crashes
 * after a calendar has been created using the prefs registry, then the calendar
 * won't show up. Writing the prefs helps counteract.
 */
function flushPrefs() {
    Services.prefs.savePrefFile(null);
}

/**
 * Callback object for the refresh timer. Should be called as an object, i.e
 * let foo = new timerCallback(calendar);
 *
 * @param aCalendar     The calendar to refresh on notification
 */
function timerCallback(aCalendar) {
    this.notify = function refreshNotify(aTimer) {
        if (!aCalendar.getProperty("disabled") && aCalendar.canRefresh) {
            aCalendar.refresh();
        }
    }
}

var gCalendarManagerAddonListener = {
    onDisabling: function(aAddon, aNeedsRestart) {
        if (!this.queryUninstallProvider(aAddon)) {
            // If the addon should not be disabled, then re-enable it.
            aAddon.userDisabled = false;
        }
    },

    onUninstalling: function(aAddon, aNeedsRestart) {
        if (!this.queryUninstallProvider(aAddon)) {
            // If the addon should not be uninstalled, then cancel the uninstall.
            aAddon.cancelUninstall();
        }
    },

    queryUninstallProvider: function(aAddon) {
        const uri = "chrome://calendar/content/calendar-providerUninstall-dialog.xul";
        const features = "chrome,titlebar,resizable,modal";
        let calMgr = cal.getCalendarManager();
        let affectedCalendars =
            [ calendar for each (calendar in calMgr.getCalendars({}))
              if (calendar.providerID == aAddon.id) ];
        if (!affectedCalendars.length) {
            // If no calendars are affected, then everything is fine.
            return true;
        }

        let args = { shouldUninstall: false, extension: aAddon };

        // Now find a window. The best choice would be the most recent
        // addons window, otherwise the most recent calendar window, or we
        // create a new toplevel window.
        let win = Services.wm.getMostRecentWindow("Extension:Manager") ||
                  cal.getCalendarWindow();
        if (win) {
            win.openDialog(uri, "CalendarProviderUninstallDialog", features, args);
        } else {
            // Use the window watcher to open a parentless window.
            Services.ww.openWindow(null, uri, "CalendarProviderUninstallWindow", features, args);
        }

        // Now that we are done, check if the dialog was accepted or canceled.
        return args.shouldUninstall;
    }
};

function appendToRealm(authHeader, appendStr) {
    let isEscaped = false;
    let idx = authHeader.search(/realm="(.*?)(\\*)"/);
    if (idx > -1) {
        let remain = authHeader.substr(idx + 7); idx += 7;
        while (remain.length && !isEscaped) {
            let m = remain.match(/(.*?)(\\*)"/);
            idx += m[0].length;

            isEscaped = ((m[2].length % 2) == 0);
            if (!isEscaped) {
                remain = remain.substr(m[0].length);
            }
        }
        return authHeader.substr(0, idx - 1) + " " +
                appendStr + authHeader.substr(idx - 1);
    } else {
        return authHeader;
    }
}