-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathpluginsPermissions.js
More file actions
1127 lines (1060 loc) · 42.2 KB
/
Copy pathpluginsPermissions.js
File metadata and controls
1127 lines (1060 loc) · 42.2 KB
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
// http://infocatcher.ucoz.net/js/cb/pluginsPermissions.js
// https://forum.mozilla-russia.org/viewtopic.php?id=57303
// https://github.com/Infocatcher/Custom_Buttons/tree/master/Plugins_Permissions
// Plugins Permissions button for Custom Buttons
// (code for "initialization" section)
// (c) Infocatcher 2012-2020
// version 0.1.2pre3 - 2020-02-12
// Based on Cookies Permissions button
// https://github.com/Infocatcher/Custom_Buttons/tree/master/Cookies_Permissions
// Note: plugins.click_to_play in about:config ("Block plugins" checkbox) should be enabled
// Unfortunately since Firefox 20 (Gecko 20) global exclusions doesn't work, only on per-plugin basis.
// So you should change "Flash", "Shockwave Flash" and "plugin:flash" in the source (and create copy
// of this button) to menage other plugins, see "// Rename to use button for another plugin" comments.
var options = {
showTempPermissions: true, // Show items about temporary permissions (only Gecko 2.0+)
tempExpire: -1, // Type of temporary permissions
// -1 - session, otherwise - expire after given time (in milliseconds)
useBaseDomain: {
// 0 - use full domain name: addons.mozilla.org, www.google.com
// 1 - strip "www." prefix from full domain name: addons.mozilla.org, google.com
// 2 - use top-level domains (TLDs): mozilla.org, google.com
addPermission: 1, // Add (and toggle) permission action
openPermissions: 0, // Filter in "Show Exceptions" window
},
showDefaultPolicy: true, // Show default policy
toggleMode: Components.interfaces.nsIPermissionManager.ALLOW_ACTION,
// ALLOW_ACTION or DENY_ACTION
reusePermissionsWindow: false, // Use any already opened permissions window
// E.g. "Show Exceptions" may convert "Exceptions - Cookies" to "Exceptions — Plugins"
prefillMode: 1, // 0 - move caret to start, 1 - select all, 2 - move caret to end
moveToStatusBar: {
// Move button to Status Bar, only for SeaMonkey or Firefox < 4.0
// Be careful, has some side-effects and button can't be edited w/o restart
enabled: false,
insertAfter: "custombuttons-cookiesPermissionsSBPanel,download-monitor,popupIcon,statusbar-progresspanel"
// Like https://developer.mozilla.org/en-US/docs/XUL/Attribute/insertafter
// Also looks for nodes with "cb_id" attribute
}
};
function _localize(sid) {
var strings = {
// Note: %p will be replaced with "Plugins" (Firefox < 20) or plugin name (Firefox >= 20)
en: {
plugins: "Plugins",
pluginName: "Flash", // Rename to use button for another plugin
defaultTooltiptext: "%p: Default",
denyTooltiptext: "%p: Block",
allowTooltiptext: "%p: Allow",
notAvailableTooltiptext: "%p: n/a",
unknownTooltiptext: "%p: ???",
errorTooltiptext: "%p: Error!",
defaultDenyTooltiptext: "%p: Block (Default)",
defaultAllowTooltiptext: "%p: Allow (Default)",
defaultLabel: "Default",
defaultAccesskey: "D",
denyLabel: "Block",
denyAccesskey: "B",
denyTempLabel: "Temporarily Block",
denyTempAccesskey: "k",
allowLabel: "Allow",
allowAccesskey: "A",
allowTempLabel: "Temporarily Allow",
allowTempAccesskey: "w",
blockPluginsLabel: "Block plugins",
blockPluginsAccesskey: "c",
removeTempPermissionsLabel: "Remove Temporary Permissions",
removeTempPermissionsAccesskey: "T",
showPermissionsLabel: "Show Exceptions…",
showPermissionsAccesskey: "x",
buttonMenu: "Button Menu",
buttonMenuAccesskey: "M",
exceptionsTitle: "Exceptions - %p",
exceptionsDesc: "You can specify which websites are always or never allowed to \
play plugins. Type the exact address of the site you want to manage and \
then click Block or Allow."
},
ru: {
plugins: "Плагины",
pluginName: "Flash", // Rename to use button for another plugin
defaultTooltiptext: "%p: По умолчанию",
denyTooltiptext: "%p: Блокировать",
allowTooltiptext: "%p: Разрешить",
notAvailableTooltiptext: "%p: н/д",
unknownTooltiptext: "%p: ???",
errorTooltiptext: "%p: Ошибка!",
defaultDenyTooltiptext: "%p: Блокировать (по умолчанию)",
defaultAllowTooltiptext: "%p: Разрешить (по умолчанию)",
defaultLabel: "По умолчанию",
defaultAccesskey: "у",
denyLabel: "Блокировать",
denyAccesskey: "Б",
denyTempLabel: "Временно блокировать",
denyTempAccesskey: "л",
allowLabel: "Разрешить",
allowAccesskey: "Р",
allowTempLabel: "Временно разрешить",
allowTempAccesskey: "ш",
blockPluginsLabel: "Блокировать плагины",
blockPluginsAccesskey: "к",
removeTempPermissionsLabel: "Удалить временные исключения",
removeTempPermissionsAccesskey: "ы",
showPermissionsLabel: "Показать исключения…",
showPermissionsAccesskey: "и",
buttonMenu: "Меню кнопки",
buttonMenuAccesskey: "М",
exceptionsTitle: "Исключения — %p",
exceptionsDesc: "Вы можете указать, каким веб-сайтам разрешено или запрещено \
автоматически проигрывать плагины. Введите точный адрес сайта и нажмите \
кнопку «Блокировать» или «Разрешить»."
}
};
var locale = (function() {
if("Services" in window && "locale" in Services) {
var locales = Services.locale.requestedLocales // Firefox 64+
|| Services.locale.getRequestedLocales && Services.locale.getRequestedLocales();
if(locales)
return locales[0];
}
var prefs = "Services" in window && Services.prefs
|| Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefBranch);
function pref(name, type) {
return prefs.getPrefType(name) != prefs.PREF_INVALID ? prefs["get" + type + "Pref"](name) : undefined;
}
if(!pref("intl.locale.matchOS", "Bool")) { // Also see https://bugzilla.mozilla.org/show_bug.cgi?id=1414390
var locale = pref("general.useragent.locale", "Char");
if(locale && locale.substr(0, 9) != "chrome://")
return locale;
}
return Components.classes["@mozilla.org/chrome/chrome-registry;1"]
.getService(Components.interfaces.nsIXULChromeRegistry)
.getSelectedLocale("global");
})().match(/^[a-z]*/)[0];
_localize = function(sid) {
return strings[locale] && strings[locale][sid] || strings.en[sid] || sid;
};
return _localize.apply(this, arguments);
}
this.onclick = function(e) {
if(e.target != this)
return;
var btn = e.button;
if(btn == 1 || btn == 0 && this.permissions.hasModifier(e))
this.permissions.openPermissions();
else if(btn == 0) {
this.permissions.togglePermission(this.permissions.options.toggleMode);
// Prevent "command" event to use "command" section only from hotkey
e.preventDefault();
e.stopPropagation();
}
};
if(!this.hasOwnProperty("defaultContextId"))
this.defaultContextId = this.getAttribute("context") || "custombuttons-contextpopup";
this.oncontextmenu = function(e) {
if(e.target != this)
return;
this.permissions.initContextOnce();
this.setAttribute(
"context",
this.permissions.hasModifier(e)
? this.defaultContextId
: this.permissions.mpId
);
};
this.permissions = {
//permissionType: "plugins",
get permissionType() {
var permissionType = "plugins";
if(this.perPluginPermissions) try {
// Rename to use button for another plugin
let pluginName = "Shockwave Flash";
permissionType = "plugin:flash"; // Fallback value
// Based on code from chrome://browser/content/pageinfo/permissions.js
let pluginHost = Components.classes["@mozilla.org/plugin/host;1"]
.getService(Components.interfaces.nsIPluginHost);
let tags = pluginHost.getPluginTags();
for(let i = 0, l = tags.length; i < l; ++i) {
let tag = tags[i];
if(tag.name == pluginName) {
let mimeType = tag.getMimeTypes()[0]; // This is string since Firefox 24
let mimeTypeString = mimeType.type || mimeType;
permissionType = pluginHost.getPermissionStringForType(mimeTypeString);
break;
}
}
}
catch(e) {
Components.utils.reportError(e);
}
delete this.permissionType;
return this.permissionType = permissionType;
},
get pluginName() {
var name = this.perPluginPermissions
? _localize("pluginName")
: _localize("plugins");
delete this.pluginName;
return this.pluginName = name;
},
get perPluginPermissions() {
delete this.perPluginPermissions;
return this.perPluginPermissions = this.platformVersion >= 20;
},
popupClass: "cbPluginsPermissionsPopup",
button: this,
options: options,
PERMISSIONS_NOT_SUPPORTED: -1,
PERMISSIONS_ERROR: -2,
errPrefix: "[Custom Buttons :: Plugins Permissions] ",
get pm() {
delete this.pm;
return this.pm = Components.classes["@mozilla.org/permissionmanager;1"]
.getService(Components.interfaces.nsIPermissionManager);
},
get io() {
delete this.io;
return this.io = Components.classes["@mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
},
get oSvc() {
return Components.classes["@mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
},
get wm() {
delete this.wm;
return this.wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
},
get tld() {
delete this.tld;
return this.tld = Components.classes["@mozilla.org/network/effective-tld-service;1"]
.getService(Components.interfaces.nsIEffectiveTLDService);
},
initialized: false,
mp: null,
init: function() {
if(this.initialized)
return;
this.initialized = true;
if(this.options.moveToStatusBar.enabled)
this.moveToStatusBar();
var dummy = function() {};
this.progressListener = {
context: this,
onStateChange: dummy,
onProgressChange: dummy,
onLocationChange: function(aWebProgress, aRequest, aLocation) {
setTimeout(function(_this) {
_this.context.updButtonState();
}, 0, this);
},
onStatusChange: dummy,
onSecurityChange: dummy
};
gBrowser.addProgressListener(this.progressListener/*, Components.interfaces.nsIWebProgress.NOTIFY_LOCATION*/);
this.permissionsObserver = {
context: this,
observe: function(subject, topic, data) {
if(topic != "perm-changed")
return;
var permission = subject.QueryInterface(Components.interfaces.nsIPermission);
var type = this.context.permissionType;
if(permission.type != type)
return;
this.context.updButtonState();
if(data == "deleted") {
// See chrome://browser/content/preferences/permissions.js
// observe: function (aSubject, aTopic, aData)
let win = this.context.wm.getMostRecentWindow("Browser:Permissions");
if(win && "gPermissionManager" in win && win.gPermissionManager._type == type) {
let pm = win.gPermissionManager;
let perms = pm._permissions;
for(let i = 0, l = perms.length; i < l; ++i) {
if(this.context.getPermissionHost(perms[i]) == this.context.getPermissionHost(permission)) {
perms.splice(i, 1);
--pm._view._rowCount;
pm._tree.treeBoxObject.rowCountChanged(i, -1);
pm._tree.treeBoxObject.invalidate();
break;
}
}
}
}
/*
if(this.context.getBaseDomain(permission.host) == this.context.currentBaseDomain) {
// See chrome://browser/content/browser.js
var pm = this.context.pm;
switch(this.context.getPermission()) {
case pm.DENY_ACTION:
let notification = PopupNotifications.getNotification("click-to-play-plugins", gBrowser.selectedBrowser);
if (notification)
notification.remove();
gPluginHandler._removeClickToPlayOverlays(content);
break;
case pm.ALLOW_ACTION:
gPluginHandler.activatePlugins(content);
}
}
*/
}
};
this.oSvc.addObserver(this.permissionsObserver, "perm-changed", false);
var ps = this.prefs = {
context: this,
get branch() {
delete this.branch;
return this.branch = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService)
.getBranch("plugins.click_to_play")
.QueryInterface(Components.interfaces.nsIPrefBranch2 || Components.interfaces.nsIPrefBranch);
},
get: function(name) {
var dv = false;
try {
return this.branch.getBoolPref(name || "", dv);
}
catch(e) {
Components.utils.reportError(e);
}
return dv;
},
set: function(val, name) {
try {
this.branch.setBoolPref(name || "", val);
}
catch(e) {
Components.utils.reportError(e);
}
},
observe: function(subject, topic, data) {
if(topic != "nsPref:changed" || data != "")
return;
var ctx = this.context;
ctx.defaultDeny = this.get();
ctx.updButtonState();
ctx.updToggleBlockItem();
}
};
if(this.options.showDefaultPolicy) {
this.defaultDeny = ps.get();
ps.branch.addObserver("", ps, false);
}
this.updButtonState();
},
destroy: function() {
if(!this.initialized)
return;
this.initialized = false;
gBrowser.removeProgressListener(this.progressListener);
this.oSvc.removeObserver(this.permissionsObserver, "perm-changed");
if(this.options.showDefaultPolicy)
this.prefs.branch.removeObserver("", this.prefs);
this.progressListener = this.permissionsObserver = this.prefs = null;
},
initContextOnce: function() {
this.initContextOnce = function() {};
this.mpId = this.button.id + "-context";
var pm = this.pm;
var noTempPermissions = !this.options.showTempPermissions || !this.hasTempPermissions;
var mp = this.mp = this.button.appendChild(this.parseXULFromString('\
<menupopup xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"\
id="' + this.mpId + '"\
class="' + this.popupClass + '"\
onpopupshowing="\
if(event.target != this)\
return true;\
document.popupNode = this.parentNode;\
return this.parentNode.permissions.updMenu();"\
onpopuphidden="if(event.target == this) document.popupNode = null;">\
<menuitem type="radio" cb_permission="' + pm.UNKNOWN_ACTION + '"\
oncommand="this.parentNode.parentNode.permissions.removePermission();"\
label="' + _localize("defaultLabel") + '"\
accesskey="' + _localize("defaultAccesskey") + '" />\
<menuseparator />\
<menuitem type="radio" cb_permission="' + pm.DENY_ACTION + '"\
oncommand="this.parentNode.parentNode.permissions.addPermission(Components.interfaces.nsIPermissionManager.DENY_ACTION);"\
label="' + _localize("denyLabel") + '"\
accesskey="' + _localize("denyAccesskey") + '" />\
<menuitem type="radio" cb_permission="' + pm.DENY_ACTION + '-temp"\
collapsed="' + noTempPermissions + '"\
class="cbTempPermission"\
oncommand="this.parentNode.parentNode.permissions.addPermission(Components.interfaces.nsIPermissionManager.DENY_ACTION, true);"\
label="' + _localize("denyTempLabel") + '"\
accesskey="' + _localize("denyTempAccesskey") + '" />\
<menuitem type="radio" cb_permission="' + pm.ALLOW_ACTION + '"\
oncommand="this.parentNode.parentNode.permissions.addPermission(Components.interfaces.nsIPermissionManager.ALLOW_ACTION);"\
label="' + _localize("allowLabel") + '"\
accesskey="' + _localize("allowAccesskey") + '" />\
<menuitem type="radio" cb_permission="' + pm.ALLOW_ACTION + '-temp"\
collapsed="' + noTempPermissions + '"\
class="cbTempPermission"\
oncommand="this.parentNode.parentNode.permissions.addPermission(Components.interfaces.nsIPermissionManager.ALLOW_ACTION, true);"\
label="' + _localize("allowTempLabel") + '"\
accesskey="' + _localize("allowTempAccesskey") + '" />\
<menuseparator />\
<menuitem\
cb_id="toggleBlock"\
type="checkbox"\
oncommand="this.parentNode.parentNode.permissions.toggleBlock(this.getAttribute(\'checked\') == \'true\');"\
label="' + _localize("blockPluginsLabel") + '"\
accesskey="' + _localize("blockPluginsAccesskey") + '" />\
<menuitem\
cb_id="removeTempPermissions"\
hidden="' + noTempPermissions + '"\
oncommand="this.parentNode.parentNode.permissions.removeTempPermissions();"\
label="' + _localize("removeTempPermissionsLabel") + '"\
accesskey="' + _localize("removeTempPermissionsAccesskey") + '" />\
<menuseparator />\
<menuitem\
cb_id="openPermissions"\
oncommand="this.parentNode.parentNode.permissions.openPermissions();"\
label="' + _localize("showPermissionsLabel") + '"\
accesskey="' + _localize("showPermissionsAccesskey") + '" />\
<menuseparator />\
<menu\
label="' + _localize("buttonMenu") + '"\
accesskey="' + _localize("buttonMenuAccesskey") + '" />\
</menupopup>'
));
var cbPopup = document.getElementById(this.button.defaultContextId);
if(!cbPopup)
Components.utils.reportError(this.errPrefix + "cb menu not found");
else {
cbPopup = cbPopup.cloneNode(true);
let id = "-" + this.button.id.match(/\d*$/)[0] + "-cloned";
cbPopup.id += id;
Array.prototype.slice.call(cbPopup.getElementsByAttribute("id", "*")).forEach(function(node) {
node.id += id;
});
cbPopup.setAttribute(
"onpopupshowing",
'\
var btn = document.popupNode = this.parentNode.parentNode.parentNode;\n\
custombutton.setContextMenuVisibility(btn);'
);
let menu = mp.lastChild;
menu.appendChild(cbPopup);
}
},
moveToStatusBar: function() {
var insPoint;
this.options.moveToStatusBar.insertAfter
.split(/,\s*/)
.some(function(id) {
insPoint = document.getElementsByAttribute("cb_id", id)[0]
|| document.getElementById(id);
return insPoint;
});
if(!insPoint)
return;
var btn = this.button;
// Make <toolbarbutton> looks like <image>, see CSS
btn.className += " custombuttons-insideStatusbarpanel";
// And insert it into <statusbarpanel>
var spId = btn.id + "-statusbarpanel";
var sp = document.getElementById(spId);
sp && sp.parentNode.removeChild(sp);
sp = document.createElement("statusbarpanel");
sp.id = spId;
sp.setAttribute("cb_id", "custombuttons-pluginsPermissionsSBPanel");
sp.appendChild(btn);
insPoint.parentNode.insertBefore(sp, insPoint.nextSibling);
},
get currentHost() {
return this.getHostFromBrowser(gBrowser);
},
getHostFromBrowser: function(browser) {
try {
var uri = browser.currentURI;
if(["chrome", "resource"].indexOf(uri.scheme) != -1)
return "";
return uri.host;
}
catch(e) {
}
return "";
},
get currentBaseDomain() {
return this.getBaseDomain(this.currentHost);
},
get currentProtocol() {
var scheme = gBrowser.currentURI.scheme;
if(scheme == "https")
return scheme;
return "http";
},
get app() {
delete this.app;
return this.app = Components.classes["@mozilla.org/xre/app-info;1"]
.getService(Components.interfaces.nsIXULAppInfo);
},
get platformVersion() {
var pv = parseFloat(this.app.platformVersion);
if(this.app.name == "Pale Moon" || this.app.name == "Basilisk")
pv = pv >= 4.1 ? 56 : 28;
delete this.platformVersion;
return this.platformVersion = pv;
},
get isSeaMonkey() {
delete this.isSeaMonkey;
return this.isSeaMonkey = this.app.name == "SeaMonkey";
},
getHost: function(useBaseDomain, host) {
if(host === undefined)
host = this.currentHost;
switch(useBaseDomain) {
case 1: return this.stripWww(host);
case 2: return this.getBaseDomain(host);
}
return host;
},
getURI: function(host) {
if(host.indexOf(":") != -1 && /^[:\da-f.]+$/.test(host)) // IPv6
host = "[" + host + "]";
host = host.replace(/^\./, "");
try {
return this.io.newURI(this.currentProtocol + "://" + host, null, null);
}
catch(e) {
Components.utils.reportError(this.errPrefix + "Invalid host: \"" + host + "\"");
throw e;
}
},
stripWww: function(host) {
return host && host.replace(/^www\./i, "");
},
getBaseDomain: function(host) {
if(host) try {
return this.tld.getBaseDomainFromHost(host);
}
catch(e) {
}
return host;
},
showMenu: function(e, isContext, mp) {
document.popupNode = this.button.ownerDocument.popupNode = this.button;
if(!mp) {
this.initContextOnce();
mp = this.mp;
}
if("openPopupAtScreen" in mp)
mp.openPopupAtScreen(e.screenX, e.screenY, isContext);
else
mp.showPopup(this, e.screenX, e.screenY, isContext ? "context" : "popup", null, null);
},
updMenu: function() {
var permission = this.options.showTempPermissions
? this.getPermissionEx()
: this.getPermission();
var noPermissions = permission == this.PERMISSIONS_NOT_SUPPORTED;
Array.prototype.forEach.call(
this.mp.getElementsByAttribute("cb_permission", "*"),
function(mi) {
mi.hidden = noPermissions;
var ns = mi.nextSibling;
if(ns && ns.localName == "menuseparator")
ns.hidden = noPermissions;
}
);
if(!noPermissions) {
let cbPermission = permission.capability || permission;
if(
this.options.showTempPermissions
&& permission instanceof Components.interfaces.nsIPermission
&& "expireType" in permission
&& permission.expireType != this.pm.EXPIRE_NEVER
)
cbPermission += "-temp";
let mi = this.mp.getElementsByAttribute("cb_permission", cbPermission);
mi.length && mi[0].setAttribute("checked", "true");
}
if(this.hasTempPermissions) {
let maxItems = 10;
let removeItem = this.mp.getElementsByAttribute("cb_id", "removeTempPermissions")[0];
let tempPermissions = this.tempPermissions;
removeItem.disabled = !tempPermissions.length;
if(tempPermissions.length > maxItems)
tempPermissions.splice(maxItems - 2, tempPermissions.length - maxItems + 1, "…");
let pm = this.pm;
removeItem.tooltipText = tempPermissions.map(function(permission) {
if(typeof permission == "string")
return permission;
var action = "???";
switch(permission.capability) {
case pm.ALLOW_ACTION: action = "allowLabel"; break;
case pm.DENY_ACTION: action = "denyLabel";
}
return (permission.host || permission.principal.URI.spec.replace(/\/$/, ""))
+ ": " + _localize(action).toLowerCase();
}, this).join(", \n");
}
this.updToggleBlockItem();
return true;
},
updToggleBlockItem: function() {
if(!this.mp) // Context menu not yet created
return;
this.mp.getElementsByAttribute("cb_id", "toggleBlock")[0]
.setAttribute(
"checked",
this.options.showDefaultPolicy
? this.defaultDeny
: this.prefs.get()
);
},
toggleBlock: function(block) {
this.prefs.set(block);
},
openPermissions: function() {
if(this.isSeaMonkey) {
this.openPermissionsSM();
return;
}
var host = this.getHost(this.options.useBaseDomain.openPermissions);
if(host && this.platformVersion >= 42)
host = this.currentProtocol + "://" + host;
// chrome://browser/content/preferences/privacy.js
// Like gPrivacyPane.showCookieExceptions()
var params = { blockVisible : true,
sessionVisible : false,
allowVisible : true,
prefilledHost : host,
permissionType : this.permissionType,
windowTitle : _localize("exceptionsTitle").replace("%p", this.pluginName),
introText : _localize("exceptionsDesc") };
var win;
var ws = this.wm.getEnumerator("Browser:Permissions");
while(ws.hasMoreElements()) {
win = ws.getNext();
if(
this.options.reusePermissionsWindow
|| "gPermissionManager" in win && win.gPermissionManager._type == this.permissionType
)
break;
win = null;
}
var _this = this;
var setFilter = function setFilter(e) {
e && win.removeEventListener("load", setFilter, false);
setTimeout(function() {
_this.setTextboxValue(win.document.getElementById("url"), host, !!e);
}, 0);
};
if(win) {
// See <method name="openWindow"> in chrome://global/content/bindings/preferences.xml#prefwindow
if("initWithParams" in win)
win.initWithParams(params);
win.focus();
host && setFilter();
}
else {
var ext = this.platformVersion >= 72 ? ".xhtml" : ".xul";
var sub = this.platformVersion >= 77 ? "dialogs/" : "";
win = window.openDialog("chrome://browser/content/preferences/" + sub + "permissions" + ext, "_blank", "", params);
host && win.addEventListener("load", setFilter, false);
}
this.tweakWindow(win);
},
openPermissionsSM: function() {
var host = this.getBaseDomain(this.currentHost); // Only TLDs are displayed in the list
//gBrowser.selectedTab = gBrowser.addTab("about:data");
//toDataManager("|permissions");
// See chrome://communicator/content/tasksOverlay.js
var _this = this;
switchToTabHavingURI("about:data", true, function(browser) {
var win = browser.contentWindow;
var content = win.wrappedJSObject || win;
function selectDomain() {
var gDomains = content.gDomains;
var domains = gDomains.displayedDomains;
for(var i = 0, l = domains.length; i < l; ++i) {
var domain = domains[i];
if(domain.title == host) {
gDomains.tree.view.selection.select(i);
// For SeaMonkey 2.20a1
var tab = content.document.getElementById("permissionsTab");
if(tab && !tab.disabled)
tab.parentNode.selectedItem = tab;
break;
}
}
}
var smVersion = parseFloat(_this.app.version);
if(smVersion >= 2.20 && smVersion <= 2.22) {
var ml = content.document.getElementById("typeSelect");
ml.value = "Permissions";
ml.doCommand();
var gDomains = content.gDomains;
var oldDomainsCount = gDomains.displayedDomains.length;
var stopWait = Date.now() + 5e3;
var waitTimer = setTimeout(function wait() {
var newDomainsCount = gDomains.displayedDomains.length;
if(
newDomainsCount > 1 && newDomainsCount == oldDomainsCount
|| Date.now() > stopWait
) {
selectDomain();
return;
}
oldDomainsCount = newDomainsCount;
waitTimer = setTimeout(wait, 20);
}, 20);
return;
}
_this.oSvc.addObserver(function observer(subject, topic, data) {
if(subject != win && subject != content)
return;
_this.oSvc.removeObserver(observer, topic);
selectDomain();
}, "dataman-loaded", false);
content.gDataman.loadView("|permissions");
});
},
tweakWindow: function(win) {
if("__cbPermissionsTweaked" in win)
return;
win.__cbPermissionsTweaked = true;
function keypressHandler(e) {
if(e.keyCode == e.DOM_VK_ESCAPE)
win.close();
}
win.addEventListener("keypress", keypressHandler, false);
win.addEventListener("unload", function destroy(e) {
var win = e.target.defaultView;
if(win != e.currentTarget)
return;
win.removeEventListener(e.type, destroy, false);
win.removeEventListener("keypress", keypressHandler, false);
}, false);
},
setTextboxValue: function(tb, val, onlySelect) {
if(!tb)
return;
if(!onlySelect)
tb.value = val;
tb.focus();
if(val && "inputField" in tb) {
let ifi = tb.inputField;
switch(this.options.prefillMode) {
case 0: ifi.selectionStart = ifi.selectionEnd = 0; break;
case 2: ifi.selectionStart = ifi.selectionEnd = val.length; break;
default: tb.select();
}
}
if(onlySelect)
return;
setTimeout(function() { // For Browser:Cookies in Firefox 14
tb.doCommand(); // Should be faster than "input" emulation
}, 0);
var evt = document.createEvent("UIEvents");
evt.initUIEvent("input", true, true, tb.ownerDocument.defaultView, 0);
tb.dispatchEvent(evt);
},
get hasTempPermissions() {
delete this.hasTempPermissions;
return this.hasTempPermissions = "EXPIRE_SESSION" in this.pm
&& (!("add" in this.pm) || this.pm.add.length > 3);
},
get pmw() {
delete this.pmw;
var pm = this.pm;
if("testPermission" in pm) {
return this.pmw = {
testPermission: pm.testPermission.bind(pm),
add: pm.add .bind(pm),
remove: pm.remove .bind(pm),
__proto__: pm
};
}
// Firefox 71+
var make = function(fn) {
return function(uri, permission) {
var principal = Services.scriptSecurityManager.createContentPrincipal(uri, {});
var args = Array.from(arguments);
args[0] = principal;
return fn.apply(pm, args);
};
};
return this.pmw = {
_context: this,
testPermission: make(pm.testPermissionFromPrincipal),
add: make(pm.addFromPrincipal),
remove: make(pm.removeFromPrincipal),
get enumerator() { // Firefox 72+
return pm.enumerator || this._context.arrayToEnumerator(pm.all);
}
};
},
arrayToEnumerator: function(arr) {
var i = 0, l = arr.length;
return {
hasMoreElements: function() {
return i < l;
},
getNext: function() {
return arr[i++];
}
}
},
addPermission: function(capability, temporary) {
// capability:
// this.pm.ALLOW_ACTION
// this.pm.DENY_ACTION
var host = this.getHost(this.options.useBaseDomain.addPermission);
if(!host)
return;
if(temporary && !this.hasTempPermissions)
temporary = false;
this.updButtonState(capability); // Faster than ProgressListener (70-80 ms for me)
if(this.hasTempPermissions)
this.removePermissionForHost(host);
var pm = this.pm;
var args = [this.getURI(host), this.permissionType, capability];
if(temporary) {
let expire = this.options.tempExpire;
if(expire < 0)
args.push(pm.EXPIRE_SESSION);
else
args.push(pm.EXPIRE_TIME, expire + Date.now());
}
this.pmw.add.apply(this.pmw, args);
},
removePermission: function() {
var host = this.currentHost;
if(!host)
return;
this.updButtonState(this.pm.UNKNOWN_ACTION); // Faster than ProgressListener (70-80 ms for me)
var uri = this.getURI(host);
var permission = this.pmw.testPermission(uri, this.permissionType);
this.removePermissionForHost(host);
while(this.pmw.testPermission(uri, this.permissionType) == permission) {
let parentHost = host.replace(/^[^.]*\./, "");
if(parentHost == host)
break;
host = parentHost;
this.removePermissionForHost(host);
}
},
togglePermission: function(capability) {
var permission = this.getPermission();
if(permission == this.PERMISSIONS_NOT_SUPPORTED)
return;
if(permission == capability)
this.removePermission();
else
this.addPermission(capability);
},
get tempPermissions() {
var out = [];
if(!this.hasTempPermissions)
return out;
var pm = this.pm;
var enumerator = this.pmw.enumerator;
while(enumerator.hasMoreElements()) {
let permission = enumerator.getNext()
.QueryInterface(Components.interfaces.nsIPermission);
if(
permission.type == this.permissionType
&& permission.expireType != pm.EXPIRE_NEVER
)
out.push(permission);
}
return out;
},
removeTempPermissions: function() {
this.tempPermissions.forEach(this.removeRawPermission, this);
},
getPermission: function() {
var host = this.currentHost;
return host
? this.pmw.testPermission(this.getURI(host), this.permissionType)
: this.PERMISSIONS_NOT_SUPPORTED;
},
getPermissionEx: function() {
// Unfortunately no API like nsIPermissionManager.testPermission()
// for temporary permissions
var host = this.currentHost;
if(!host)
return this.PERMISSIONS_NOT_SUPPORTED;
var pm = this.pm;
var matchedPermission = pm.UNKNOWN_ACTION;
var protocol = this.currentProtocol;
var maxHostLen = -1;
var enumerator = this.pmw.enumerator;
while(enumerator.hasMoreElements()) {
let permission = enumerator.getNext()
.QueryInterface(Components.interfaces.nsIPermission);
if(permission.type != this.permissionType)
continue;
if("principal" in permission && permission.principal.URI.scheme != protocol) // Firefox 42+
continue;
var permissionHost = this.getPermissionHost(permission);
if(permissionHost == host)
return permission;
var hostLen = permissionHost.length;
if(
hostLen > maxHostLen
&& host.substr(-hostLen - 1) == "." + permissionHost
) {
matchedPermission = permission;
maxHostLen = hostLen;
}
}
return matchedPermission;
},
removePermissionForHost: function(host) {
try {
this.pmw.remove(host, this.permissionType);
}
catch(e) {
// See https://bugzilla.mozilla.org/show_bug.cgi?id=1170200
if("Services" in window) try { // Firefox 42+
let uri = Services.io.newURI(this.currentProtocol + "://" + host, null, null);
this.pmw.remove(uri, this.permissionType);
return;
}
catch(e2) {
Components.utils.reportError(e2);
}
Components.utils.reportError(e);
}
},
removeRawPermission: function(permission) {
if("principal" in permission) // Firefox 42+
this.pmw.remove(permission.principal.URI, this.permissionType);
else
this.removePermissionForHost(permission.host);
},
getPermissionHost: function(permission) {
if("host" in permission)
return permission.host;
// See https://bugzilla.mozilla.org/show_bug.cgi?id=1173523
return permission.principal.URI.host; // Firefox 42+
},
get defaultPermission() {
return this.defaultDeny
? this.pm.DENY_ACTION
: this.pm.ALLOW_ACTION;
},