How to use stripFragmentFromUrl method in Playwright Internal

Best JavaScript code snippet using playwright-internal

adblockplus.js

Source:adblockplus.js Github

copy

Full Screen

1/*2 * This file is part of Adblock Plus <http://adblockplus.org/>,3 * Copyright (C) 2006-2013 Eyeo GmbH4 *5 * Adblock Plus is free software: you can redistribute it and/or modify6 * it under the terms of the GNU General Public License version 3 as7 * published by the Free Software Foundation.8 *9 * Adblock Plus is distributed in the hope that it will be useful,10 * but WITHOUT ANY WARRANTY; without even the implied warranty of11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12 * GNU General Public License for more details.13 *14 * You should have received a copy of the GNU General Public License15 * along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.16 */17//18// This file has been generated automatically, relevant repositories:19// * https://hg.adblockplus.org/adblockplus/20// * https://hg.adblockplus.org/jshydra/21//22require.scopes["prefs"] = (function()23{24 var exports = {};25 var defaults =26 {27 __proto__: null,28 enabled: true,29 data_directory: "",30 patternsbackups: 5,31 patternsbackupinterval: 24,32 savestats: false,33 privateBrowsing: false,34 subscriptions_fallbackerrors: 5,35 subscriptions_fallbackurl: "https://adblockplus.org/getSubscription?version=%VERSION%&url=%SUBSCRIPTION%&downloadURL=%URL%&error=%ERROR%&channelStatus=%CHANNELSTATUS%&responseStatus=%RESPONSESTATUS%",36 subscriptions_autoupdate: true,37 subscriptions_exceptionsurl: "https://easylist-downloads.adblockplus.org/exceptionrules.txt",38 documentation_link: "https://adblockplus.org/redirect?link=%LINK%&lang=%LANG%",39 notificationdata: {},40 notificationurl: "https://notification.adblockplus.org/notification.json",41 stats_total: {},42 show_statsinicon: true,43 show_statsinpopup: true,44 shouldShowBlockElementMenu: true,45 hidePlaceholders: true46 };47 var listeners = [];48 function defineProperty(key)49 {50 var value = null;51 Prefs.__defineGetter__(key, function()52 {53 if (value === null)54 {55 if (key in localStorage)56 {57 try58 {59 value = JSON.parse(localStorage[key]);60 }61 catch (e)62 {63 Cu.reportError(e);64 }65 }66 if (value === null)67 {68 value = JSON.parse(JSON.stringify(defaults[key]));69 }70 }71 return value;72 });73 Prefs.__defineSetter__(key, function(newValue)74 {75 if (typeof newValue != typeof defaults[key])76 {77 throw new Error("Attempt to change preference type");78 }79 var stringified = JSON.stringify(newValue);80 if (stringified != JSON.stringify(defaults[key]))81 {82 localStorage[key] = stringified;83 }84 else85 {86 delete localStorage[key];87 }88 value = newValue;89 for (var _loopIndex0 = 0; _loopIndex0 < listeners.length; ++_loopIndex0)90 {91 var listener = listeners[_loopIndex0];92 listener(key);93 }94 return value;95 });96 }97 var Prefs = exports.Prefs =98 {99 addListener: function(listener)100 {101 if (listeners.indexOf(listener) < 0)102 {103 listeners.push(listener);104 }105 },106 removeListener: function(listener)107 {108 var index = listeners.indexOf(listener);109 if (index >= 0)110 {111 listeners.splice(index, 1);112 }113 }114 };115 for (var key in defaults)116 {117 defineProperty(key);118 }119 return exports;120})();121require.scopes["utils"] = (function()122{123 var exports = {};124 var runAsyncQueue;125 var Utils = exports.Utils =126 {127 systemPrincipal: null,128 getString: function(id)129 {130 return id;131 },132 runAsync: function(callback)133 {134 callback = callback.bind.apply(callback, Array.prototype.slice.call(arguments, 1));135 if (typeof runAsyncQueue == "undefined")136 {137 runAsyncQueue = document.readyState == "loading" ? [] : null;138 if (runAsyncQueue)139 {140 var loadHandler = function()141 {142 document.removeEventListener("DOMContentLoaded", loadHandler, false);143 var queue = runAsyncQueue;144 runAsyncQueue = null;145 for (var _loopIndex1 = 0; _loopIndex1 < queue.length; ++_loopIndex1)146 {147 var callback = queue[_loopIndex1];148 try149 {150 callback();151 }152 catch (e)153 {154 Cu.reportError(e);155 }156 }157 };158 document.addEventListener("DOMContentLoaded", loadHandler, false);159 }160 }161 if (runAsyncQueue)162 {163 runAsyncQueue.push(callback);164 }165 else166 {167 window.setTimeout(callback, 0);168 }169 },170 get appLocale()171 {172 var locale = ext.i18n.getMessage("@@ui_locale").replace(/_/g, "-");173 this.__defineGetter__("appLocale", function()174 {175 return locale;176 });177 return this.appLocale;178 },179 generateChecksum: function(lines)180 {181 return null;182 },183 makeURI: function(url)184 {185 return Services.io.newURI(url);186 },187 checkLocalePrefixMatch: function(prefixes)188 {189 if (!prefixes)190 {191 return null;192 }193 var list = prefixes.split(",");194 for (var i = 0; i < list.length; i++)195 {196 if ((new RegExp("^" + list[i] + "\\b")).test(this.appLocale))197 {198 return list[i];199 }200 }201 return null;202 },203 chooseFilterSubscription: function(subscriptions)204 {205 var selectedItem = null;206 var selectedPrefix = null;207 var matchCount = 0;208 for (var i = 0; i < subscriptions.length; i++)209 {210 var subscription = subscriptions[i];211 if (!selectedItem)212 {213 selectedItem = subscription;214 }215 var prefix = require("utils").Utils.checkLocalePrefixMatch(subscription.getAttribute("prefixes"));216 if (prefix)217 {218 if (!selectedPrefix || selectedPrefix.length < prefix.length)219 {220 selectedItem = subscription;221 selectedPrefix = prefix;222 matchCount = 1;223 }224 else if (selectedPrefix && selectedPrefix.length == prefix.length)225 {226 matchCount++;227 if (Math.random() * matchCount < 1)228 {229 selectedItem = subscription;230 selectedPrefix = prefix;231 }232 }233 }234 }235 return selectedItem;236 },237 getDocLink: function(linkID)238 {239 var Prefs = require("prefs").Prefs;240 var docLink = Prefs.documentation_link;241 return docLink.replace(/%LINK%/g, linkID).replace(/%LANG%/g, Utils.appLocale);242 }243 };244 return exports;245})();246require.scopes["elemHideHitRegistration"] = (function()247{248 var exports = {};249 var AboutHandler = exports.AboutHandler = {};250 return exports;251})();252require.scopes["downloader"] = (function()253{254 var exports = {};255 var Utils = require("utils").Utils;256 var MILLIS_IN_SECOND = exports.MILLIS_IN_SECOND = 1000;257 var MILLIS_IN_MINUTE = exports.MILLIS_IN_MINUTE = 60 * MILLIS_IN_SECOND;258 var MILLIS_IN_HOUR = exports.MILLIS_IN_HOUR = 60 * MILLIS_IN_MINUTE;259 var MILLIS_IN_DAY = exports.MILLIS_IN_DAY = 24 * MILLIS_IN_HOUR;260 var Downloader = exports.Downloader = function Downloader(dataSource, initialDelay, checkInterval)261 {262 this.dataSource = dataSource;263 this._timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);264 this._timer.initWithCallback(function()265 {266 this._timer.delay = checkInterval;267 this._doCheck();268 }.bind(this), initialDelay, Ci.nsITimer.TYPE_REPEATING_SLACK);269 this._downloading = Object.create(null);270 };271 Downloader.prototype =272 {273 _timer: null,274 _downloading: null,275 dataSource: null,276 maxAbsenceInterval: 1 * MILLIS_IN_DAY,277 minRetryInterval: 1 * MILLIS_IN_DAY,278 maxExpirationInterval: 14 * MILLIS_IN_DAY,279 maxRedirects: 5,280 onExpirationChange: null,281 onDownloadStarted: null,282 onDownloadSuccess: null,283 onDownloadError: null,284 _doCheck: function()285 {286 var now = Date.now();287 for (var _loopIndex2 = 0; _loopIndex2 < this.dataSource().length; ++_loopIndex2)288 {289 var downloadable = this.dataSource()[_loopIndex2];290 if (downloadable.lastCheck && now - downloadable.lastCheck > this.maxAbsenceInterval)291 {292 downloadable.softExpiration += now - downloadable.lastCheck;293 }294 downloadable.lastCheck = now;295 if (downloadable.hardExpiration - now > this.maxExpirationInterval)296 {297 downloadable.hardExpiration = now + this.maxExpirationInterval;298 }299 if (downloadable.softExpiration - now > this.maxExpirationInterval)300 {301 downloadable.softExpiration = now + this.maxExpirationInterval;302 }303 if (this.onExpirationChange)304 {305 this.onExpirationChange(downloadable);306 }307 if (downloadable.softExpiration > now && downloadable.hardExpiration > now)308 {309 continue;310 }311 if (downloadable.lastError && now - downloadable.lastError < this.minRetryInterval)312 {313 continue;314 }315 this._download(downloadable, 0);316 }317 },318 cancel: function()319 {320 this._timer.cancel();321 },322 isDownloading: function(url)323 {324 return url in this._downloading;325 },326 download: function(downloadable)327 {328 Utils.runAsync(this._download.bind(this, downloadable, 0));329 },330 getDownloadUrl: function(downloadable)331 {332 var _tempVar3 = require("info");333 var addonName = _tempVar3.addonName;334 var addonVersion = _tempVar3.addonVersion;335 var application = _tempVar3.application;336 var applicationVersion = _tempVar3.applicationVersion;337 var platform = _tempVar3.platform;338 var platformVersion = _tempVar3.platformVersion;339 var url = downloadable.redirectURL || downloadable.url;340 if (url.indexOf("?") >= 0)341 {342 url += "&";343 }344 else345 {346 url += "?";347 }348 url += "addonName=" + encodeURIComponent(addonName) + "&addonVersion=" + encodeURIComponent(addonVersion) + "&application=" + encodeURIComponent(application) + "&applicationVersion=" + encodeURIComponent(applicationVersion) + "&platform=" + encodeURIComponent(platform) + "&platformVersion=" + encodeURIComponent(platformVersion) + "&lastVersion=" + encodeURIComponent(downloadable.lastVersion);349 return url;350 },351 _download: function(downloadable, redirects)352 {353 if (this.isDownloading(downloadable.url))354 {355 return;356 }357 var downloadUrl = this.getDownloadUrl(downloadable);358 var request = null;359 var errorCallback = function errorCallback(error)360 {361 var channelStatus = -1;362 try363 {364 channelStatus = request.channel.status;365 }366 catch (e){}367 var responseStatus = request.status;368 Cu.reportError("Adblock Plus: Downloading URL " + downloadable.url + " failed (" + error + ")\n" + "Download address: " + downloadUrl + "\n" + "Channel status: " + channelStatus + "\n" + "Server response: " + responseStatus);369 if (this.onDownloadError)370 {371 var redirectCallback = null;372 if (redirects <= this.maxRedirects)373 {374 redirectCallback = function redirectCallback(url)375 {376 downloadable.redirectURL = url;377 this._download(downloadable, redirects + 1);378 }.bind(this);379 }380 this.onDownloadError(downloadable, downloadUrl, error, channelStatus, responseStatus, redirectCallback);381 }382 }.bind(this);383 try384 {385 request = new XMLHttpRequest();386 request.mozBackgroundRequest = true;387 request.open("GET", downloadUrl);388 }389 catch (e)390 {391 errorCallback("synchronize_invalid_url");392 return;393 }394 try395 {396 request.overrideMimeType("text/plain");397 request.channel.loadFlags = request.channel.loadFlags | request.channel.INHIBIT_CACHING | request.channel.VALIDATE_ALWAYS;398 if (request.channel instanceof Ci.nsIHttpChannel)399 {400 request.channel.redirectionLimit = this.maxRedirects;401 }402 }403 catch (e)404 {405 Cu.reportError(e);406 }407 request.addEventListener("error", function(event)408 {409 if (onShutdown.done)410 {411 return;412 }413 delete this._downloading[downloadable.url];414 errorCallback("synchronize_connection_error");415 }.bind(this), false);416 request.addEventListener("load", function(event)417 {418 if (onShutdown.done)419 {420 return;421 }422 delete this._downloading[downloadable.url];423 if (request.status && request.status != 200)424 {425 errorCallback("synchronize_connection_error");426 return;427 }428 this.onDownloadSuccess(downloadable, request.responseText, errorCallback, function redirectCallback(url)429 {430 if (redirects >= this.maxRedirects)431 {432 errorCallback("synchronize_connection_error");433 }434 else435 {436 downloadable.redirectURL = url;437 this._download(downloadable, redirects + 1);438 }439 }.bind(this));440 }.bind(this), false);441 request.send(null);442 this._downloading[downloadable.url] = true;443 if (this.onDownloadStarted)444 {445 this.onDownloadStarted(downloadable);446 }447 },448 processExpirationInterval: function(interval)449 {450 interval = Math.min(Math.max(interval, 0), this.maxExpirationInterval);451 var soft = Math.round(interval * (Math.random() * 0.4 + 0.8));452 var hard = interval * 2;453 var now = Date.now();454 return [now + soft, now + hard];455 }456 };457 var Downloadable = exports.Downloadable = function Downloadable(url)458 {459 this.url = url;460 };461 Downloadable.prototype =462 {463 url: null,464 redirectURL: null,465 lastError: 0,466 lastCheck: 0,467 lastVersion: 0,468 softExpiration: 0,469 hardExpiration: 0470 };471 return exports;472})();473require.scopes["filterNotifier"] = (function()474{475 var exports = {};476 var listeners = [];477 var FilterNotifier = exports.FilterNotifier =478 {479 addListener: function(listener)480 {481 if (listeners.indexOf(listener) >= 0)482 {483 return;484 }485 listeners.push(listener);486 },487 removeListener: function(listener)488 {489 var index = listeners.indexOf(listener);490 if (index >= 0)491 {492 listeners.splice(index, 1);493 }494 },495 triggerListeners: function(action, item, param1, param2, param3)496 {497 for (var _loopIndex4 = 0; _loopIndex4 < listeners.length; ++_loopIndex4)498 {499 var listener = listeners[_loopIndex4];500 listener(action, item, param1, param2, param3);501 }502 }503 };504 return exports;505})();506require.scopes["filterClasses"] = (function()507{508 var exports = {};509 var FilterNotifier = require("filterNotifier").FilterNotifier;510 function Filter(text)511 {512 this.text = text;513 this.subscriptions = [];514 }515 exports.Filter = Filter;516 Filter.prototype =517 {518 text: null,519 subscriptions: null,520 serialize: function(buffer)521 {522 buffer.push("[Filter]");523 buffer.push("text=" + this.text);524 },525 toString: function()526 {527 return this.text;528 }529 };530 Filter.knownFilters =531 {532 __proto__: null533 };534 Filter.elemhideRegExp = /^([^\/\*\|\@"!]*?)#(\@)?(?:([\w\-]+|\*)((?:\([\w\-]+(?:[$^*]?=[^\(\)"]*)?\))*)|#([^{}]+))$/;535 Filter.regexpRegExp = /^(@@)?\/.*\/(?:\$~?[\w\-]+(?:=[^,\s]+)?(?:,~?[\w\-]+(?:=[^,\s]+)?)*)?$/;536 Filter.optionsRegExp = /\$(~?[\w\-]+(?:=[^,\s]+)?(?:,~?[\w\-]+(?:=[^,\s]+)?)*)$/;537 Filter.fromText = function(text)538 {539 if (text in Filter.knownFilters)540 {541 return Filter.knownFilters[text];542 }543 var ret;544 var match = text.indexOf("#") >= 0 ? Filter.elemhideRegExp.exec(text) : null;545 if (match)546 {547 ret = ElemHideBase.fromText(text, match[1], match[2], match[3], match[4], match[5]);548 }549 else if (text[0] == "!")550 {551 ret = new CommentFilter(text);552 }553 else554 {555 ret = RegExpFilter.fromText(text);556 }557 Filter.knownFilters[ret.text] = ret;558 return ret;559 };560 Filter.fromObject = function(obj)561 {562 var ret = Filter.fromText(obj.text);563 if (ret instanceof ActiveFilter)564 {565 if ("disabled" in obj)566 {567 ret._disabled = obj.disabled == "true";568 }569 if ("hitCount" in obj)570 {571 ret._hitCount = parseInt(obj.hitCount) || 0;572 }573 if ("lastHit" in obj)574 {575 ret._lastHit = parseInt(obj.lastHit) || 0;576 }577 }578 return ret;579 };580 Filter.normalize = function(text)581 {582 if (!text)583 {584 return text;585 }586 text = text.replace(/[^\S ]/g, "");587 if (/^\s*!/.test(text))588 {589 return text.replace(/^\s+/, "").replace(/\s+$/, "");590 }591 else if (Filter.elemhideRegExp.test(text))592 {593 var _tempVar5 = /^(.*?)(#\@?#?)(.*)$/.exec(text);594 var domain = _tempVar5[1];595 var separator = _tempVar5[2];596 var selector = _tempVar5[3];597 return domain.replace(/\s/g, "") + separator + selector.replace(/^\s+/, "").replace(/\s+$/, "");598 }599 else600 {601 return text.replace(/\s/g, "");602 }603 };604 function InvalidFilter(text, reason)605 {606 Filter.call(this, text);607 this.reason = reason;608 }609 exports.InvalidFilter = InvalidFilter;610 InvalidFilter.prototype =611 {612 __proto__: Filter.prototype,613 reason: null,614 serialize: function(buffer){}615 };616 function CommentFilter(text)617 {618 Filter.call(this, text);619 }620 exports.CommentFilter = CommentFilter;621 CommentFilter.prototype =622 {623 __proto__: Filter.prototype,624 serialize: function(buffer){}625 };626 function ActiveFilter(text, domains)627 {628 Filter.call(this, text);629 this.domainSource = domains;630 }631 exports.ActiveFilter = ActiveFilter;632 ActiveFilter.prototype =633 {634 __proto__: Filter.prototype,635 _disabled: false,636 _hitCount: 0,637 _lastHit: 0,638 get disabled()639 {640 return this._disabled;641 },642 set disabled(value)643 {644 if (value != this._disabled)645 {646 var oldValue = this._disabled;647 this._disabled = value;648 FilterNotifier.triggerListeners("filter.disabled", this, value, oldValue);649 }650 return this._disabled;651 },652 get hitCount()653 {654 return this._hitCount;655 },656 set hitCount(value)657 {658 if (value != this._hitCount)659 {660 var oldValue = this._hitCount;661 this._hitCount = value;662 FilterNotifier.triggerListeners("filter.hitCount", this, value, oldValue);663 }664 return this._hitCount;665 },666 get lastHit()667 {668 return this._lastHit;669 },670 set lastHit(value)671 {672 if (value != this._lastHit)673 {674 var oldValue = this._lastHit;675 this._lastHit = value;676 FilterNotifier.triggerListeners("filter.lastHit", this, value, oldValue);677 }678 return this._lastHit;679 },680 domainSource: null,681 domainSeparator: null,682 ignoreTrailingDot: true,683 get domains()684 {685 var domains = null;686 if (this.domainSource)687 {688 var list = this.domainSource.split(this.domainSeparator);689 if (list.length == 1 && list[0][0] != "~")690 {691 domains =692 {693 __proto__: null,694 "": false695 };696 if (this.ignoreTrailingDot)697 {698 list[0] = list[0].replace(/\.+$/, "");699 }700 domains[list[0]] = true;701 }702 else703 {704 var hasIncludes = false;705 for (var i = 0; i < list.length; i++)706 {707 var domain = list[i];708 if (this.ignoreTrailingDot)709 {710 domain = domain.replace(/\.+$/, "");711 }712 if (domain == "")713 {714 continue;715 }716 var include;717 if (domain[0] == "~")718 {719 include = false;720 domain = domain.substr(1);721 }722 else723 {724 include = true;725 hasIncludes = true;726 }727 if (!domains)728 {729 domains =730 {731 __proto__: null732 };733 }734 domains[domain] = include;735 }736 domains[""] = !hasIncludes;737 }738 delete this.domainSource;739 }740 this.__defineGetter__("domains", function()741 {742 return domains;743 });744 return this.domains;745 },746 isActiveOnDomain: function(docDomain)747 {748 if (!this.domains)749 {750 return true;751 }752 if (!docDomain)753 {754 return this.domains[""];755 }756 if (this.ignoreTrailingDot)757 {758 docDomain = docDomain.replace(/\.+$/, "");759 }760 docDomain = docDomain.toUpperCase();761 while (true)762 {763 if (docDomain in this.domains)764 {765 return this.domains[docDomain];766 }767 var nextDot = docDomain.indexOf(".");768 if (nextDot < 0)769 {770 break;771 }772 docDomain = docDomain.substr(nextDot + 1);773 }774 return this.domains[""];775 },776 isActiveOnlyOnDomain: function(docDomain)777 {778 if (!docDomain || !this.domains || this.domains[""])779 {780 return false;781 }782 if (this.ignoreTrailingDot)783 {784 docDomain = docDomain.replace(/\.+$/, "");785 }786 docDomain = docDomain.toUpperCase();787 for (var domain in this.domains)788 {789 if (this.domains[domain] && domain != docDomain && (domain.length <= docDomain.length || domain.indexOf("." + docDomain) != domain.length - docDomain.length - 1))790 {791 return false;792 }793 }794 return true;795 },796 serialize: function(buffer)797 {798 if (this._disabled || this._hitCount || this._lastHit)799 {800 Filter.prototype.serialize.call(this, buffer);801 if (this._disabled)802 {803 buffer.push("disabled=true");804 }805 if (this._hitCount)806 {807 buffer.push("hitCount=" + this._hitCount);808 }809 if (this._lastHit)810 {811 buffer.push("lastHit=" + this._lastHit);812 }813 }814 }815 };816 function RegExpFilter(text, regexpSource, contentType, matchCase, domains, thirdParty)817 {818 ActiveFilter.call(this, text, domains);819 if (contentType != null)820 {821 this.contentType = contentType;822 }823 if (matchCase)824 {825 this.matchCase = matchCase;826 }827 if (thirdParty != null)828 {829 this.thirdParty = thirdParty;830 }831 if (regexpSource.length >= 2 && regexpSource[0] == "/" && regexpSource[regexpSource.length - 1] == "/")832 {833 var regexp = new RegExp(regexpSource.substr(1, regexpSource.length - 2), this.matchCase ? "" : "i");834 this.__defineGetter__("regexp", function()835 {836 return regexp;837 });838 }839 else840 {841 this.regexpSource = regexpSource;842 }843 }844 exports.RegExpFilter = RegExpFilter;845 RegExpFilter.prototype =846 {847 __proto__: ActiveFilter.prototype,848 length: 1,849 domainSeparator: "|",850 regexpSource: null,851 get regexp()852 {853 var source = this.regexpSource.replace(/\*+/g, "*").replace(/\^\|$/, "^").replace(/\W/g, "\\$&").replace(/\\\*/g, ".*").replace(/\\\^/g, "(?:[\\x00-\\x24\\x26-\\x2C\\x2F\\x3A-\\x40\\x5B-\\x5E\\x60\\x7B-\\x7F]|$)").replace(/^\\\|\\\|/, "^[\\w\\-]+:\\/+(?!\\/)(?:[^\\/]+\\.)?").replace(/^\\\|/, "^").replace(/\\\|$/, "$").replace(/^(\.\*)/, "").replace(/(\.\*)$/, "");854 var regexp = new RegExp(source, this.matchCase ? "" : "i");855 delete this.regexpSource;856 this.__defineGetter__("regexp", function()857 {858 return regexp;859 });860 return this.regexp;861 },862 contentType: 2147483647,863 matchCase: false,864 thirdParty: null,865 matches: function(location, contentType, docDomain, thirdParty)866 {867 if (this.regexp.test(location) && (RegExpFilter.typeMap[contentType] & this.contentType) != 0 && (this.thirdParty == null || this.thirdParty == thirdParty) && this.isActiveOnDomain(docDomain))868 {869 return true;870 }871 return false;872 }873 };874 RegExpFilter.prototype.__defineGetter__("0", function()875 {876 return this;877 });878 RegExpFilter.fromText = function(text)879 {880 var blocking = true;881 var origText = text;882 if (text.indexOf("@@") == 0)883 {884 blocking = false;885 text = text.substr(2);886 }887 var contentType = null;888 var matchCase = null;889 var domains = null;890 var siteKeys = null;891 var thirdParty = null;892 var collapse = null;893 var options;894 var match = text.indexOf("$") >= 0 ? Filter.optionsRegExp.exec(text) : null;895 if (match)896 {897 options = match[1].toUpperCase().split(",");898 text = match.input.substr(0, match.index);899 for (var _loopIndex6 = 0; _loopIndex6 < options.length; ++_loopIndex6)900 {901 var option = options[_loopIndex6];902 var value = null;903 var separatorIndex = option.indexOf("=");904 if (separatorIndex >= 0)905 {906 value = option.substr(separatorIndex + 1);907 option = option.substr(0, separatorIndex);908 }909 option = option.replace(/-/, "_");910 if (option in RegExpFilter.typeMap)911 {912 if (contentType == null)913 {914 contentType = 0;915 }916 contentType |= RegExpFilter.typeMap[option];917 }918 else if (option[0] == "~" && option.substr(1) in RegExpFilter.typeMap)919 {920 if (contentType == null)921 {922 contentType = RegExpFilter.prototype.contentType;923 }924 contentType &= ~RegExpFilter.typeMap[option.substr(1)];925 }926 else if (option == "MATCH_CASE")927 {928 matchCase = true;929 }930 else if (option == "~MATCH_CASE")931 {932 matchCase = false;933 }934 else if (option == "DOMAIN" && typeof value != "undefined")935 {936 domains = value;937 }938 else if (option == "THIRD_PARTY")939 {940 thirdParty = true;941 }942 else if (option == "~THIRD_PARTY")943 {944 thirdParty = false;945 }946 else if (option == "COLLAPSE")947 {948 collapse = true;949 }950 else if (option == "~COLLAPSE")951 {952 collapse = false;953 }954 else if (option == "SITEKEY" && typeof value != "undefined")955 {956 siteKeys = value.split(/\|/);957 }958 else959 {960 return new InvalidFilter(origText, "Unknown option " + option.toLowerCase());961 }962 }963 }964 if (!blocking && (contentType == null || contentType & RegExpFilter.typeMap.DOCUMENT) && (!options || options.indexOf("DOCUMENT") < 0) && !/^\|?[\w\-]+:/.test(text))965 {966 if (contentType == null)967 {968 contentType = RegExpFilter.prototype.contentType;969 }970 contentType &= ~RegExpFilter.typeMap.DOCUMENT;971 }972 if (!blocking && siteKeys)973 {974 contentType = RegExpFilter.typeMap.DOCUMENT;975 }976 try977 {978 if (blocking)979 {980 return new BlockingFilter(origText, text, contentType, matchCase, domains, thirdParty, collapse);981 }982 else983 {984 return new WhitelistFilter(origText, text, contentType, matchCase, domains, thirdParty, siteKeys);985 }986 }987 catch (e)988 {989 return new InvalidFilter(origText, e);990 }991 };992 RegExpFilter.typeMap =993 {994 OTHER: 1,995 SCRIPT: 2,996 IMAGE: 4,997 STYLESHEET: 8,998 OBJECT: 16,999 SUBDOCUMENT: 32,1000 DOCUMENT: 64,1001 XBL: 1,1002 PING: 1,1003 XMLHTTPREQUEST: 2048,1004 OBJECT_SUBREQUEST: 4096,1005 DTD: 1,1006 MEDIA: 16384,1007 FONT: 32768,1008 BACKGROUND: 4,1009 POPUP: 268435456,1010 ELEMHIDE: 10737418241011 };1012 RegExpFilter.prototype.contentType &= ~ (RegExpFilter.typeMap.ELEMHIDE | RegExpFilter.typeMap.POPUP);1013 function BlockingFilter(text, regexpSource, contentType, matchCase, domains, thirdParty, collapse)1014 {1015 RegExpFilter.call(this, text, regexpSource, contentType, matchCase, domains, thirdParty);1016 this.collapse = collapse;1017 }1018 exports.BlockingFilter = BlockingFilter;1019 BlockingFilter.prototype =1020 {1021 __proto__: RegExpFilter.prototype,1022 collapse: null1023 };1024 function WhitelistFilter(text, regexpSource, contentType, matchCase, domains, thirdParty, siteKeys)1025 {1026 RegExpFilter.call(this, text, regexpSource, contentType, matchCase, domains, thirdParty);1027 if (siteKeys != null)1028 {1029 this.siteKeys = siteKeys;1030 }1031 }1032 exports.WhitelistFilter = WhitelistFilter;1033 WhitelistFilter.prototype =1034 {1035 __proto__: RegExpFilter.prototype,1036 siteKeys: null1037 };1038 function ElemHideBase(text, domains, selector)1039 {1040 ActiveFilter.call(this, text, domains ? domains.toUpperCase() : null);1041 if (domains)1042 {1043 this.selectorDomain = domains.replace(/,~[^,]+/g, "").replace(/^~[^,]+,?/, "").toLowerCase();1044 }1045 this.selector = selector;1046 }1047 exports.ElemHideBase = ElemHideBase;1048 ElemHideBase.prototype =1049 {1050 __proto__: ActiveFilter.prototype,1051 domainSeparator: ",",1052 ignoreTrailingDot: false,1053 selectorDomain: null,1054 selector: null1055 };1056 ElemHideBase.fromText = function(text, domain, isException, tagName, attrRules, selector)1057 {1058 if (!selector)1059 {1060 if (tagName == "*")1061 {1062 tagName = "";1063 }1064 var id = null;1065 var additional = "";1066 if (attrRules)1067 {1068 attrRules = attrRules.match(/\([\w\-]+(?:[$^*]?=[^\(\)"]*)?\)/g);1069 for (var _loopIndex7 = 0; _loopIndex7 < attrRules.length; ++_loopIndex7)1070 {1071 var rule = attrRules[_loopIndex7];1072 rule = rule.substr(1, rule.length - 2);1073 var separatorPos = rule.indexOf("=");1074 if (separatorPos > 0)1075 {1076 rule = rule.replace(/=/, "=\"") + "\"";1077 additional += "[" + rule + "]";1078 }1079 else1080 {1081 if (id)1082 {1083 var Utils = require("utils").Utils;1084 return new InvalidFilter(text, Utils.getString("filter_elemhide_duplicate_id"));1085 }1086 else1087 {1088 id = rule;1089 }1090 }1091 }1092 }1093 if (id)1094 {1095 selector = tagName + "." + id + additional + "," + tagName + "#" + id + additional;1096 }1097 else if (tagName || additional)1098 {1099 selector = tagName + additional;1100 }1101 else1102 {1103 var Utils = require("utils").Utils;1104 return new InvalidFilter(text, Utils.getString("filter_elemhide_nocriteria"));1105 }1106 }1107 if (isException)1108 {1109 return new ElemHideException(text, domain, selector);1110 }1111 else1112 {1113 return new ElemHideFilter(text, domain, selector);1114 }1115 };1116 function ElemHideFilter(text, domains, selector)1117 {1118 ElemHideBase.call(this, text, domains, selector);1119 }1120 exports.ElemHideFilter = ElemHideFilter;1121 ElemHideFilter.prototype =1122 {1123 __proto__: ElemHideBase.prototype1124 };1125 function ElemHideException(text, domains, selector)1126 {1127 ElemHideBase.call(this, text, domains, selector);1128 }1129 exports.ElemHideException = ElemHideException;1130 ElemHideException.prototype =1131 {1132 __proto__: ElemHideBase.prototype1133 };1134 return exports;1135})();1136require.scopes["subscriptionClasses"] = (function()1137{1138 var exports = {};1139 var _tempVar8 = require("filterClasses");1140 var ActiveFilter = _tempVar8.ActiveFilter;1141 var BlockingFilter = _tempVar8.BlockingFilter;1142 var WhitelistFilter = _tempVar8.WhitelistFilter;1143 var ElemHideBase = _tempVar8.ElemHideBase;1144 var FilterNotifier = require("filterNotifier").FilterNotifier;1145 function Subscription(url, title)1146 {1147 this.url = url;1148 this.filters = [];1149 if (title)1150 {1151 this._title = title;1152 }1153 else1154 {1155 var Utils = require("utils").Utils;1156 this._title = Utils.getString("newGroup_title");1157 }1158 Subscription.knownSubscriptions[url] = this;1159 }1160 exports.Subscription = Subscription;1161 Subscription.prototype =1162 {1163 url: null,1164 filters: null,1165 _title: null,1166 _fixedTitle: false,1167 _disabled: false,1168 get title()1169 {1170 return this._title;1171 },1172 set title(value)1173 {1174 if (value != this._title)1175 {1176 var oldValue = this._title;1177 this._title = value;1178 FilterNotifier.triggerListeners("subscription.title", this, value, oldValue);1179 }1180 return this._title;1181 },1182 get fixedTitle()1183 {1184 return this._fixedTitle;1185 },1186 set fixedTitle(value)1187 {1188 if (value != this._fixedTitle)1189 {1190 var oldValue = this._fixedTitle;1191 this._fixedTitle = value;1192 FilterNotifier.triggerListeners("subscription.fixedTitle", this, value, oldValue);1193 }1194 return this._fixedTitle;1195 },1196 get disabled()1197 {1198 return this._disabled;1199 },1200 set disabled(value)1201 {1202 if (value != this._disabled)1203 {1204 var oldValue = this._disabled;1205 this._disabled = value;1206 FilterNotifier.triggerListeners("subscription.disabled", this, value, oldValue);1207 }1208 return this._disabled;1209 },1210 serialize: function(buffer)1211 {1212 buffer.push("[Subscription]");1213 buffer.push("url=" + this.url);1214 buffer.push("title=" + this._title);1215 if (this._fixedTitle)1216 {1217 buffer.push("fixedTitle=true");1218 }1219 if (this._disabled)1220 {1221 buffer.push("disabled=true");1222 }1223 },1224 serializeFilters: function(buffer)1225 {1226 for (var _loopIndex9 = 0; _loopIndex9 < this.filters.length; ++_loopIndex9)1227 {1228 var filter = this.filters[_loopIndex9];1229 buffer.push(filter.text.replace(/\[/g, "\\["));1230 }1231 },1232 toString: function()1233 {1234 var buffer = [];1235 this.serialize(buffer);1236 return buffer.join("\n");1237 }1238 };1239 Subscription.knownSubscriptions =1240 {1241 __proto__: null1242 };1243 Subscription.fromURL = function(url)1244 {1245 if (url in Subscription.knownSubscriptions)1246 {1247 return Subscription.knownSubscriptions[url];1248 }1249 try1250 {1251 url = Services.io.newURI(url, null, null).spec;1252 return new DownloadableSubscription(url, null);1253 }1254 catch (e)1255 {1256 return new SpecialSubscription(url);1257 }1258 };1259 Subscription.fromObject = function(obj)1260 {1261 var result;1262 try1263 {1264 obj.url = Services.io.newURI(obj.url, null, null).spec;1265 result = new DownloadableSubscription(obj.url, obj.title);1266 if ("downloadStatus" in obj)1267 {1268 result._downloadStatus = obj.downloadStatus;1269 }1270 if ("lastSuccess" in obj)1271 {1272 result.lastSuccess = parseInt(obj.lastSuccess) || 0;1273 }1274 if ("lastCheck" in obj)1275 {1276 result._lastCheck = parseInt(obj.lastCheck) || 0;1277 }1278 if ("expires" in obj)1279 {1280 result.expires = parseInt(obj.expires) || 0;1281 }1282 if ("softExpiration" in obj)1283 {1284 result.softExpiration = parseInt(obj.softExpiration) || 0;1285 }1286 if ("errors" in obj)1287 {1288 result._errors = parseInt(obj.errors) || 0;1289 }1290 if ("version" in obj)1291 {1292 result.version = parseInt(obj.version) || 0;1293 }1294 if ("requiredVersion" in obj)1295 {1296 var addonVersion = require("info").addonVersion;1297 result.requiredVersion = obj.requiredVersion;1298 if (Services.vc.compare(result.requiredVersion, addonVersion) > 0)1299 {1300 result.upgradeRequired = true;1301 }1302 }1303 if ("homepage" in obj)1304 {1305 result._homepage = obj.homepage;1306 }1307 if ("lastDownload" in obj)1308 {1309 result._lastDownload = parseInt(obj.lastDownload) || 0;1310 }1311 }1312 catch (e)1313 {1314 if (!("title" in obj))1315 {1316 if (obj.url == "~wl~")1317 {1318 obj.defaults = "whitelist";1319 }1320 else if (obj.url == "~fl~")1321 {1322 obj.defaults = "blocking";1323 }1324 else if (obj.url == "~eh~")1325 {1326 obj.defaults = "elemhide";1327 }1328 if ("defaults" in obj)1329 {1330 var Utils = require("utils").Utils;1331 obj.title = Utils.getString(obj.defaults + "Group_title");1332 }1333 }1334 result = new SpecialSubscription(obj.url, obj.title);1335 if ("defaults" in obj)1336 {1337 result.defaults = obj.defaults.split(" ");1338 }1339 }1340 if ("fixedTitle" in obj)1341 {1342 result._fixedTitle = obj.fixedTitle == "true";1343 }1344 if ("disabled" in obj)1345 {1346 result._disabled = obj.disabled == "true";1347 }1348 return result;1349 };1350 function SpecialSubscription(url, title)1351 {1352 Subscription.call(this, url, title);1353 }1354 exports.SpecialSubscription = SpecialSubscription;1355 SpecialSubscription.prototype =1356 {1357 __proto__: Subscription.prototype,1358 defaults: null,1359 isDefaultFor: function(filter)1360 {1361 if (this.defaults && this.defaults.length)1362 {1363 for (var _loopIndex10 = 0; _loopIndex10 < this.defaults.length; ++_loopIndex10)1364 {1365 var type = this.defaults[_loopIndex10];1366 if (filter instanceof SpecialSubscription.defaultsMap[type])1367 {1368 return true;1369 }1370 if (!(filter instanceof ActiveFilter) && type == "blacklist")1371 {1372 return true;1373 }1374 }1375 }1376 return false;1377 },1378 serialize: function(buffer)1379 {1380 Subscription.prototype.serialize.call(this, buffer);1381 if (this.defaults && this.defaults.length)1382 {1383 buffer.push("defaults=" + this.defaults.filter(function(type)1384 {1385 return type in SpecialSubscription.defaultsMap;1386 }).join(" "));1387 }1388 if (this._lastDownload)1389 {1390 buffer.push("lastDownload=" + this._lastDownload);1391 }1392 }1393 };1394 SpecialSubscription.defaultsMap =1395 {1396 __proto__: null,1397 "whitelist": WhitelistFilter,1398 "blocking": BlockingFilter,1399 "elemhide": ElemHideBase1400 };1401 SpecialSubscription.create = function(title)1402 {1403 var url;1404 do1405 {1406 url = "~user~" + Math.round(Math.random() * 1000000);1407 }1408 while (url in Subscription.knownSubscriptions);1409 return new SpecialSubscription(url, title);1410 };1411 SpecialSubscription.createForFilter = function(filter)1412 {1413 var subscription = SpecialSubscription.create();1414 subscription.filters.push(filter);1415 for (var type in SpecialSubscription.defaultsMap)1416 {1417 if (filter instanceof SpecialSubscription.defaultsMap[type])1418 {1419 subscription.defaults = [type];1420 }1421 }1422 if (!subscription.defaults)1423 {1424 subscription.defaults = ["blocking"];1425 }1426 var Utils = require("utils").Utils;1427 subscription.title = Utils.getString(subscription.defaults[0] + "Group_title");1428 return subscription;1429 };1430 function RegularSubscription(url, title)1431 {1432 Subscription.call(this, url, title || url);1433 }1434 exports.RegularSubscription = RegularSubscription;1435 RegularSubscription.prototype =1436 {1437 __proto__: Subscription.prototype,1438 _homepage: null,1439 _lastDownload: 0,1440 get homepage()1441 {1442 return this._homepage;1443 },1444 set homepage(value)1445 {1446 if (value != this._homepage)1447 {1448 var oldValue = this._homepage;1449 this._homepage = value;1450 FilterNotifier.triggerListeners("subscription.homepage", this, value, oldValue);1451 }1452 return this._homepage;1453 },1454 get lastDownload()1455 {1456 return this._lastDownload;1457 },1458 set lastDownload(value)1459 {1460 if (value != this._lastDownload)1461 {1462 var oldValue = this._lastDownload;1463 this._lastDownload = value;1464 FilterNotifier.triggerListeners("subscription.lastDownload", this, value, oldValue);1465 }1466 return this._lastDownload;1467 },1468 serialize: function(buffer)1469 {1470 Subscription.prototype.serialize.call(this, buffer);1471 if (this._homepage)1472 {1473 buffer.push("homepage=" + this._homepage);1474 }1475 if (this._lastDownload)1476 {1477 buffer.push("lastDownload=" + this._lastDownload);1478 }1479 }1480 };1481 function ExternalSubscription(url, title)1482 {1483 RegularSubscription.call(this, url, title);1484 }1485 exports.ExternalSubscription = ExternalSubscription;1486 ExternalSubscription.prototype =1487 {1488 __proto__: RegularSubscription.prototype,1489 serialize: function(buffer)1490 {1491 throw new Error("Unexpected call, external subscriptions should not be serialized");1492 }1493 };1494 function DownloadableSubscription(url, title)1495 {1496 RegularSubscription.call(this, url, title);1497 }1498 exports.DownloadableSubscription = DownloadableSubscription;1499 DownloadableSubscription.prototype =1500 {1501 __proto__: RegularSubscription.prototype,1502 _downloadStatus: null,1503 _lastCheck: 0,1504 _errors: 0,1505 get downloadStatus()1506 {1507 return this._downloadStatus;1508 },1509 set downloadStatus(value)1510 {1511 var oldValue = this._downloadStatus;1512 this._downloadStatus = value;1513 FilterNotifier.triggerListeners("subscription.downloadStatus", this, value, oldValue);1514 return this._downloadStatus;1515 },1516 lastSuccess: 0,1517 get lastCheck()1518 {1519 return this._lastCheck;1520 },1521 set lastCheck(value)1522 {1523 if (value != this._lastCheck)1524 {1525 var oldValue = this._lastCheck;1526 this._lastCheck = value;1527 FilterNotifier.triggerListeners("subscription.lastCheck", this, value, oldValue);1528 }1529 return this._lastCheck;1530 },1531 expires: 0,1532 softExpiration: 0,1533 get errors()1534 {1535 return this._errors;1536 },1537 set errors(value)1538 {1539 if (value != this._errors)1540 {1541 var oldValue = this._errors;1542 this._errors = value;1543 FilterNotifier.triggerListeners("subscription.errors", this, value, oldValue);1544 }1545 return this._errors;1546 },1547 version: 0,1548 requiredVersion: null,1549 upgradeRequired: false,1550 serialize: function(buffer)1551 {1552 RegularSubscription.prototype.serialize.call(this, buffer);1553 if (this.downloadStatus)1554 {1555 buffer.push("downloadStatus=" + this.downloadStatus);1556 }1557 if (this.lastSuccess)1558 {1559 buffer.push("lastSuccess=" + this.lastSuccess);1560 }1561 if (this.lastCheck)1562 {1563 buffer.push("lastCheck=" + this.lastCheck);1564 }1565 if (this.expires)1566 {1567 buffer.push("expires=" + this.expires);1568 }1569 if (this.softExpiration)1570 {1571 buffer.push("softExpiration=" + this.softExpiration);1572 }1573 if (this.errors)1574 {1575 buffer.push("errors=" + this.errors);1576 }1577 if (this.version)1578 {1579 buffer.push("version=" + this.version);1580 }1581 if (this.requiredVersion)1582 {1583 buffer.push("requiredVersion=" + this.requiredVersion);1584 }1585 }1586 };1587 return exports;1588})();1589require.scopes["filterStorage"] = (function()1590{1591 var exports = {};1592 var IO = require("io").IO;1593 var Prefs = require("prefs").Prefs;1594 var _tempVar11 = require("filterClasses");1595 var Filter = _tempVar11.Filter;1596 var ActiveFilter = _tempVar11.ActiveFilter;1597 var _tempVar12 = require("subscriptionClasses");1598 var Subscription = _tempVar12.Subscription;1599 var SpecialSubscription = _tempVar12.SpecialSubscription;1600 var ExternalSubscription = _tempVar12.ExternalSubscription;1601 var FilterNotifier = require("filterNotifier").FilterNotifier;1602 var formatVersion = 4;1603 var FilterStorage = exports.FilterStorage =1604 {1605 get formatVersion()1606 {1607 return formatVersion;1608 },1609 get sourceFile()1610 {1611 var file = null;1612 if (Prefs.patternsfile)1613 {1614 file = IO.resolveFilePath(Prefs.patternsfile);1615 }1616 if (!file)1617 {1618 file = IO.resolveFilePath(Prefs.data_directory);1619 if (file)1620 {1621 file.append("patterns.ini");1622 }1623 }1624 if (!file)1625 {1626 try1627 {1628 file = IO.resolveFilePath(Services.prefs.getDefaultBranch("extensions.adblockplus.").getCharPref("data_directory"));1629 if (file)1630 {1631 file.append("patterns.ini");1632 }1633 }1634 catch (e){}1635 }1636 if (!file)1637 {1638 Cu.reportError("Adblock Plus: Failed to resolve filter file location from extensions.adblockplus.patternsfile preference");1639 }1640 this.__defineGetter__("sourceFile", function()1641 {1642 return file;1643 });1644 return this.sourceFile;1645 },1646 fileProperties:1647 {1648 __proto__: null1649 },1650 subscriptions: [],1651 knownSubscriptions:1652 {1653 __proto__: null1654 },1655 getGroupForFilter: function(filter)1656 {1657 var generalSubscription = null;1658 for (var _loopIndex13 = 0; _loopIndex13 < FilterStorage.subscriptions.length; ++_loopIndex13)1659 {1660 var subscription = FilterStorage.subscriptions[_loopIndex13];1661 if (subscription instanceof SpecialSubscription && !subscription.disabled)1662 {1663 if (subscription.isDefaultFor(filter))1664 {1665 return subscription;1666 }1667 if (!generalSubscription && (!subscription.defaults || !subscription.defaults.length))1668 {1669 generalSubscription = subscription;1670 }1671 }1672 }1673 return generalSubscription;1674 },1675 addSubscription: function(subscription, silent)1676 {1677 if (subscription.url in FilterStorage.knownSubscriptions)1678 {1679 return;1680 }1681 FilterStorage.subscriptions.push(subscription);1682 FilterStorage.knownSubscriptions[subscription.url] = subscription;1683 addSubscriptionFilters(subscription);1684 if (!silent)1685 {1686 FilterNotifier.triggerListeners("subscription.added", subscription);1687 }1688 },1689 removeSubscription: function(subscription, silent)1690 {1691 for (var i = 0; i < FilterStorage.subscriptions.length; i++)1692 {1693 if (FilterStorage.subscriptions[i].url == subscription.url)1694 {1695 removeSubscriptionFilters(subscription);1696 FilterStorage.subscriptions.splice(i--, 1);1697 delete FilterStorage.knownSubscriptions[subscription.url];1698 if (!silent)1699 {1700 FilterNotifier.triggerListeners("subscription.removed", subscription);1701 }1702 return;1703 }1704 }1705 },1706 moveSubscription: function(subscription, insertBefore)1707 {1708 var currentPos = FilterStorage.subscriptions.indexOf(subscription);1709 if (currentPos < 0)1710 {1711 return;1712 }1713 var newPos = insertBefore ? FilterStorage.subscriptions.indexOf(insertBefore) : -1;1714 if (newPos < 0)1715 {1716 newPos = FilterStorage.subscriptions.length;1717 }1718 if (currentPos < newPos)1719 {1720 newPos--;1721 }1722 if (currentPos == newPos)1723 {1724 return;1725 }1726 FilterStorage.subscriptions.splice(currentPos, 1);1727 FilterStorage.subscriptions.splice(newPos, 0, subscription);1728 FilterNotifier.triggerListeners("subscription.moved", subscription);1729 },1730 updateSubscriptionFilters: function(subscription, filters)1731 {1732 removeSubscriptionFilters(subscription);1733 subscription.oldFilters = subscription.filters;1734 subscription.filters = filters;1735 addSubscriptionFilters(subscription);1736 FilterNotifier.triggerListeners("subscription.updated", subscription);1737 delete subscription.oldFilters;1738 },1739 addFilter: function(filter, subscription, position, silent)1740 {1741 if (!subscription)1742 {1743 if (filter.subscriptions.some(function(s)1744 {1745 return s instanceof SpecialSubscription && !s.disabled;1746 }))1747 {1748 return;1749 }1750 subscription = FilterStorage.getGroupForFilter(filter);1751 }1752 if (!subscription)1753 {1754 subscription = SpecialSubscription.createForFilter(filter);1755 this.addSubscription(subscription);1756 return;1757 }1758 if (typeof position == "undefined")1759 {1760 position = subscription.filters.length;1761 }1762 if (filter.subscriptions.indexOf(subscription) < 0)1763 {1764 filter.subscriptions.push(subscription);1765 }1766 subscription.filters.splice(position, 0, filter);1767 if (!silent)1768 {1769 FilterNotifier.triggerListeners("filter.added", filter, subscription, position);1770 }1771 },1772 removeFilter: function(filter, subscription, position)1773 {1774 var subscriptions = subscription ? [subscription] : filter.subscriptions.slice();1775 for (var i = 0; i < subscriptions.length; i++)1776 {1777 var subscription = subscriptions[i];1778 if (subscription instanceof SpecialSubscription)1779 {1780 var positions = [];1781 if (typeof position == "undefined")1782 {1783 var index = -1;1784 do1785 {1786 index = subscription.filters.indexOf(filter, index + 1);1787 if (index >= 0)1788 {1789 positions.push(index);1790 }1791 }1792 while (index >= 0);1793 }1794 else1795 {1796 positions.push(position);1797 }1798 for (var j = positions.length - 1; j >= 0; j--)1799 {1800 var position = positions[j];1801 if (subscription.filters[position] == filter)1802 {1803 subscription.filters.splice(position, 1);1804 if (subscription.filters.indexOf(filter) < 0)1805 {1806 var index = filter.subscriptions.indexOf(subscription);1807 if (index >= 0)1808 {1809 filter.subscriptions.splice(index, 1);1810 }1811 }1812 FilterNotifier.triggerListeners("filter.removed", filter, subscription, position);1813 }1814 }1815 }1816 }1817 },1818 moveFilter: function(filter, subscription, oldPosition, newPosition)1819 {1820 if (!(subscription instanceof SpecialSubscription) || subscription.filters[oldPosition] != filter)1821 {1822 return;1823 }1824 newPosition = Math.min(Math.max(newPosition, 0), subscription.filters.length - 1);1825 if (oldPosition == newPosition)1826 {1827 return;1828 }1829 subscription.filters.splice(oldPosition, 1);1830 subscription.filters.splice(newPosition, 0, filter);1831 FilterNotifier.triggerListeners("filter.moved", filter, subscription, oldPosition, newPosition);1832 },1833 increaseHitCount: function(filter, wnd)1834 {1835 if (!Prefs.savestats || PrivateBrowsing.enabledForWindow(wnd) || PrivateBrowsing.enabled || !(filter instanceof ActiveFilter))1836 {1837 return;1838 }1839 filter.hitCount++;1840 filter.lastHit = Date.now();1841 },1842 resetHitCounts: function(filters)1843 {1844 if (!filters)1845 {1846 filters = [];1847 for (var text in Filter.knownFilters)1848 {1849 filters.push(Filter.knownFilters[text]);1850 }1851 }1852 for (var _loopIndex14 = 0; _loopIndex14 < filters.length; ++_loopIndex14)1853 {1854 var filter = filters[_loopIndex14];1855 filter.hitCount = 0;1856 filter.lastHit = 0;1857 }1858 },1859 _loading: false,1860 loadFromDisk: function(sourceFile)1861 {1862 if (this._loading)1863 {1864 return;1865 }1866 var readFile = function(sourceFile, backupIndex)1867 {1868 var parser = new INIParser();1869 IO.readFromFile(sourceFile, true, parser, function(e)1870 {1871 if (!e && parser.subscriptions.length == 0)1872 {1873 e = new Error("No data in the file");1874 }1875 if (e)1876 {1877 Cu.reportError(e);1878 }1879 if (e && !explicitFile)1880 {1881 sourceFile = this.sourceFile;1882 if (sourceFile)1883 {1884 var _tempVar15 = /^(.*)(\.\w+)$/.exec(sourceFile.leafName) || [null, sourceFile.leafName, ""];1885 var part1 = _tempVar15[1];1886 var part2 = _tempVar15[2];1887 sourceFile = sourceFile.clone();1888 sourceFile.leafName = part1 + "-backup" + ++backupIndex + part2;1889 IO.statFile(sourceFile, function(e, statData)1890 {1891 if (!e && statData.exists)1892 {1893 readFile(sourceFile, backupIndex);1894 }1895 else1896 {1897 doneReading(parser);1898 }1899 });1900 return;1901 }1902 }1903 doneReading(parser);1904 }.bind(this), "FilterStorageRead");1905 }.bind(this);1906 var doneReading = function(parser)1907 {1908 var specialMap =1909 {1910 "~il~": true,1911 "~wl~": true,1912 "~fl~": true,1913 "~eh~": true1914 };1915 var knownSubscriptions =1916 {1917 __proto__: null1918 };1919 for (var i = 0; i < parser.subscriptions.length; i++)1920 {1921 var subscription = parser.subscriptions[i];1922 if (subscription instanceof SpecialSubscription && subscription.filters.length == 0 && subscription.url in specialMap)1923 {1924 parser.subscriptions.splice(i--, 1);1925 }1926 else1927 {1928 knownSubscriptions[subscription.url] = subscription;1929 }1930 }1931 this.fileProperties = parser.fileProperties;1932 this.subscriptions = parser.subscriptions;1933 this.knownSubscriptions = knownSubscriptions;1934 Filter.knownFilters = parser.knownFilters;1935 Subscription.knownSubscriptions = parser.knownSubscriptions;1936 if (parser.userFilters)1937 {1938 for (var i = 0; i < parser.userFilters.length; i++)1939 {1940 var filter = Filter.fromText(parser.userFilters[i]);1941 this.addFilter(filter, null, undefined, true);1942 }1943 }1944 this._loading = false;1945 FilterNotifier.triggerListeners("load");1946 if (sourceFile != this.sourceFile)1947 {1948 this.saveToDisk();1949 }1950 }.bind(this);1951 var startRead = function(file)1952 {1953 this._loading = true;1954 readFile(file, 0);1955 }.bind(this);1956 var explicitFile;1957 if (sourceFile)1958 {1959 explicitFile = true;1960 startRead(sourceFile);1961 }1962 else1963 {1964 explicitFile = false;1965 sourceFile = FilterStorage.sourceFile;1966 var callback = function(e, statData)1967 {1968 if (e || !statData.exists)1969 {1970 var addonRoot = require("info").addonRoot;1971 sourceFile = Services.io.newURI(addonRoot + "defaults/patterns.ini", null, null);1972 }1973 startRead(sourceFile);1974 };1975 if (sourceFile)1976 {1977 IO.statFile(sourceFile, callback);1978 }1979 else1980 {1981 callback(true);1982 }1983 }1984 },1985 _generateFilterData: function(subscriptions)1986 {1987 var _generatorResult16 = [];1988 _generatorResult16.push("# Adblock Plus preferences");1989 _generatorResult16.push("version=" + formatVersion);1990 var saved =1991 {1992 __proto__: null1993 };1994 var buf = [];1995 for (var i = 0; i < subscriptions.length; i++)1996 {1997 var subscription = subscriptions[i];1998 for (var j = 0; j < subscription.filters.length; j++)1999 {2000 var filter = subscription.filters[j];2001 if (!(filter.text in saved))2002 {2003 filter.serialize(buf);2004 saved[filter.text] = filter;2005 for (var k = 0; k < buf.length; k++)2006 {2007 _generatorResult16.push(buf[k]);2008 }2009 buf.splice(0);2010 }2011 }2012 }2013 for (var i = 0; i < subscriptions.length; i++)2014 {2015 var subscription = subscriptions[i];2016 _generatorResult16.push("");2017 subscription.serialize(buf);2018 if (subscription.filters.length)2019 {2020 buf.push("", "[Subscription filters]");2021 subscription.serializeFilters(buf);2022 }2023 for (var k = 0; k < buf.length; k++)2024 {2025 _generatorResult16.push(buf[k]);2026 }2027 buf.splice(0);2028 }2029 return _generatorResult16;2030 },2031 _saving: false,2032 _needsSave: false,2033 saveToDisk: function(targetFile)2034 {2035 var explicitFile = true;2036 if (!targetFile)2037 {2038 targetFile = FilterStorage.sourceFile;2039 explicitFile = false;2040 }2041 if (!targetFile)2042 {2043 return;2044 }2045 if (!explicitFile && this._saving)2046 {2047 this._needsSave = true;2048 return;2049 }2050 try2051 {2052 targetFile.parent.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);2053 }2054 catch (e){}2055 var writeFilters = function()2056 {2057 IO.writeToFile(targetFile, true, this._generateFilterData(subscriptions), function(e)2058 {2059 if (!explicitFile)2060 {2061 this._saving = false;2062 }2063 if (e)2064 {2065 Cu.reportError(e);2066 }2067 if (!explicitFile && this._needsSave)2068 {2069 this._needsSave = false;2070 this.saveToDisk();2071 }2072 else2073 {2074 FilterNotifier.triggerListeners("save");2075 }2076 }.bind(this), "FilterStorageWrite");2077 }.bind(this);2078 var checkBackupRequired = function(callbackNotRequired, callbackRequired)2079 {2080 if (explicitFile || Prefs.patternsbackups <= 0)2081 {2082 callbackNotRequired();2083 }2084 else2085 {2086 IO.statFile(targetFile, function(e, statData)2087 {2088 if (e || !statData.exists)2089 {2090 callbackNotRequired();2091 }2092 else2093 {2094 var _tempVar17 = /^(.*)(\.\w+)$/.exec(targetFile.leafName) || [null, targetFile.leafName, ""];2095 var part1 = _tempVar17[1];2096 var part2 = _tempVar17[2];2097 var newestBackup = targetFile.clone();2098 newestBackup.leafName = part1 + "-backup1" + part2;2099 IO.statFile(newestBackup, function(e, statData)2100 {2101 if (!e && (!statData.exists || (Date.now() - statData.lastModified) / 3600000 >= Prefs.patternsbackupinterval))2102 {2103 callbackRequired(part1, part2);2104 }2105 else2106 {2107 callbackNotRequired();2108 }2109 });2110 }2111 });2112 }2113 }.bind(this);2114 var removeLastBackup = function(part1, part2)2115 {2116 var file = targetFile.clone();2117 file.leafName = part1 + "-backup" + Prefs.patternsbackups + part2;2118 IO.removeFile(file, function(e)2119 {2120 return renameBackup(part1, part2, Prefs.patternsbackups - 1);2121 });2122 }.bind(this);2123 var renameBackup = function(part1, part2, index)2124 {2125 if (index > 0)2126 {2127 var fromFile = targetFile.clone();2128 fromFile.leafName = part1 + "-backup" + index + part2;2129 var toName = part1 + "-backup" + (index + 1) + part2;2130 IO.renameFile(fromFile, toName, function(e)2131 {2132 return renameBackup(part1, part2, index - 1);2133 });2134 }2135 else2136 {2137 var toFile = targetFile.clone();2138 toFile.leafName = part1 + "-backup" + (index + 1) + part2;2139 IO.copyFile(targetFile, toFile, writeFilters);2140 }2141 }.bind(this);2142 var subscriptions = this.subscriptions.filter(function(s)2143 {2144 return !(s instanceof ExternalSubscription);2145 });2146 if (!explicitFile)2147 {2148 this._saving = true;2149 }2150 checkBackupRequired(writeFilters, removeLastBackup);2151 },2152 getBackupFiles: function()2153 {2154 var result = [];2155 var _tempVar18 = /^(.*)(\.\w+)$/.exec(FilterStorage.sourceFile.leafName) || [null, FilterStorage.sourceFile.leafName, ""];2156 var part1 = _tempVar18[1];2157 var part2 = _tempVar18[2];2158 for (var i = 1;; i++)2159 {2160 var file = FilterStorage.sourceFile.clone();2161 file.leafName = part1 + "-backup" + i + part2;2162 if (file.exists())2163 {2164 result.push(file);2165 }2166 else2167 {2168 break;2169 }2170 }2171 return result;2172 }2173 };2174 function addSubscriptionFilters(subscription)2175 {2176 if (!(subscription.url in FilterStorage.knownSubscriptions))2177 {2178 return;2179 }2180 for (var _loopIndex19 = 0; _loopIndex19 < subscription.filters.length; ++_loopIndex19)2181 {2182 var filter = subscription.filters[_loopIndex19];2183 filter.subscriptions.push(subscription);2184 }2185 }2186 function removeSubscriptionFilters(subscription)2187 {2188 if (!(subscription.url in FilterStorage.knownSubscriptions))2189 {2190 return;2191 }2192 for (var _loopIndex20 = 0; _loopIndex20 < subscription.filters.length; ++_loopIndex20)2193 {2194 var filter = subscription.filters[_loopIndex20];2195 var i = filter.subscriptions.indexOf(subscription);2196 if (i >= 0)2197 {2198 filter.subscriptions.splice(i, 1);2199 }2200 }2201 }2202 var PrivateBrowsing = exports.PrivateBrowsing =2203 {2204 enabled: false,2205 enabledForWindow: function(wnd)2206 {2207 try2208 {2209 return wnd.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsILoadContext).usePrivateBrowsing;2210 }2211 catch (e)2212 {2213 if (e.result != Cr.NS_NOINTERFACE)2214 {2215 Cu.reportError(e);2216 }2217 return false;2218 }2219 },2220 init: function()2221 {2222 if ("@mozilla.org/privatebrowsing;1" in Cc)2223 {2224 try2225 {2226 this.enabled = Cc["@mozilla.org/privatebrowsing;1"].getService(Ci.nsIPrivateBrowsingService).privateBrowsingEnabled;2227 Services.obs.addObserver(this, "private-browsing", true);2228 onShutdown.add(function()2229 {2230 Services.obs.removeObserver(this, "private-browsing");2231 }.bind(this));2232 }2233 catch (e)2234 {2235 Cu.reportError(e);2236 }2237 }2238 },2239 observe: function(subject, topic, data)2240 {2241 if (topic == "private-browsing")2242 {2243 if (data == "enter")2244 {2245 this.enabled = true;2246 }2247 else if (data == "exit")2248 {2249 this.enabled = false;2250 }2251 }2252 },2253 QueryInterface: XPCOMUtils.generateQI([Ci.nsISupportsWeakReference, Ci.nsIObserver])2254 };2255 PrivateBrowsing.init();2256 function INIParser()2257 {2258 this.fileProperties = this.curObj = {};2259 this.subscriptions = [];2260 this.knownFilters =2261 {2262 __proto__: null2263 };2264 this.knownSubscriptions =2265 {2266 __proto__: null2267 };2268 }2269 INIParser.prototype =2270 {2271 subscriptions: null,2272 knownFilters: null,2273 knownSubscrptions: null,2274 wantObj: true,2275 fileProperties: null,2276 curObj: null,2277 curSection: null,2278 userFilters: null,2279 process: function(val)2280 {2281 var origKnownFilters = Filter.knownFilters;2282 Filter.knownFilters = this.knownFilters;2283 var origKnownSubscriptions = Subscription.knownSubscriptions;2284 Subscription.knownSubscriptions = this.knownSubscriptions;2285 var match;2286 try2287 {2288 if (this.wantObj === true && (match = /^(\w+)=(.*)$/.exec(val)))2289 {2290 this.curObj[match[1]] = match[2];2291 }2292 else if (val === null || (match = /^\s*\[(.+)\]\s*$/.exec(val)))2293 {2294 if (this.curObj)2295 {2296 switch (this.curSection)2297 {2298 case "filter":2299 case "pattern":2300 if ("text" in this.curObj)2301 {2302 Filter.fromObject(this.curObj);2303 }2304 break;2305 case "subscription":2306 var subscription = Subscription.fromObject(this.curObj);2307 if (subscription)2308 {2309 this.subscriptions.push(subscription);2310 }2311 break;2312 case "subscription filters":2313 case "subscription patterns":2314 if (this.subscriptions.length)2315 {2316 var subscription = this.subscriptions[this.subscriptions.length - 1];2317 for (var _loopIndex21 = 0; _loopIndex21 < this.curObj.length; ++_loopIndex21)2318 {2319 var text = this.curObj[_loopIndex21];2320 var filter = Filter.fromText(text);2321 subscription.filters.push(filter);2322 filter.subscriptions.push(subscription);2323 }2324 }2325 break;2326 case "user patterns":2327 this.userFilters = this.curObj;2328 break;2329 }2330 }2331 if (val === null)2332 {2333 return;2334 }2335 this.curSection = match[1].toLowerCase();2336 switch (this.curSection)2337 {2338 case "filter":2339 case "pattern":2340 case "subscription":2341 this.wantObj = true;2342 this.curObj = {};2343 break;2344 case "subscription filters":2345 case "subscription patterns":2346 case "user patterns":2347 this.wantObj = false;2348 this.curObj = [];2349 break;2350 default:2351 this.wantObj = undefined;2352 this.curObj = null;2353 }2354 }2355 else if (this.wantObj === false && val)2356 {2357 this.curObj.push(val.replace(/\\\[/g, "["));2358 }2359 }2360 finally2361 {2362 Filter.knownFilters = origKnownFilters;2363 Subscription.knownSubscriptions = origKnownSubscriptions;2364 }2365 }2366 };2367 return exports;2368})();2369require.scopes["elemHide"] = (function()2370{2371 var exports = {};2372 var Utils = require("utils").Utils;2373 var IO = require("io").IO;2374 var Prefs = require("prefs").Prefs;2375 var ElemHideException = require("filterClasses").ElemHideException;2376 var FilterNotifier = require("filterNotifier").FilterNotifier;2377 var AboutHandler = require("elemHideHitRegistration").AboutHandler;2378 var filterByKey =2379 {2380 __proto__: null2381 };2382 var keyByFilter =2383 {2384 __proto__: null2385 };2386 var knownExceptions =2387 {2388 __proto__: null2389 };2390 var exceptions =2391 {2392 __proto__: null2393 };2394 var styleURL = null;2395 var ElemHide = exports.ElemHide =2396 {2397 isDirty: false,2398 applied: false,2399 init: function()2400 {2401 Prefs.addListener(function(name)2402 {2403 if (name == "enabled")2404 {2405 ElemHide.apply();2406 }2407 });2408 onShutdown.add(function()2409 {2410 ElemHide.unapply();2411 });2412 var styleFile = IO.resolveFilePath(Prefs.data_directory);2413 styleFile.append("elemhide.css");2414 styleURL = Services.io.newFileURI(styleFile).QueryInterface(Ci.nsIFileURL);2415 },2416 clear: function()2417 {2418 filterByKey =2419 {2420 __proto__: null2421 };2422 keyByFilter =2423 {2424 __proto__: null2425 };2426 knownExceptions =2427 {2428 __proto__: null2429 };2430 exceptions =2431 {2432 __proto__: null2433 };2434 ElemHide.isDirty = false;2435 ElemHide.unapply();2436 },2437 add: function(filter)2438 {2439 if (filter instanceof ElemHideException)2440 {2441 if (filter.text in knownExceptions)2442 {2443 return;2444 }2445 var selector = filter.selector;2446 if (!(selector in exceptions))2447 {2448 exceptions[selector] = [];2449 }2450 exceptions[selector].push(filter);2451 knownExceptions[filter.text] = true;2452 }2453 else2454 {2455 if (filter.text in keyByFilter)2456 {2457 return;2458 }2459 var key;2460 do2461 {2462 key = Math.random().toFixed(15).substr(5);2463 }2464 while (key in filterByKey);2465 filterByKey[key] = filter;2466 keyByFilter[filter.text] = key;2467 ElemHide.isDirty = true;2468 }2469 },2470 remove: function(filter)2471 {2472 if (filter instanceof ElemHideException)2473 {2474 if (!(filter.text in knownExceptions))2475 {2476 return;2477 }2478 var list = exceptions[filter.selector];2479 var index = list.indexOf(filter);2480 if (index >= 0)2481 {2482 list.splice(index, 1);2483 }2484 delete knownExceptions[filter.text];2485 }2486 else2487 {2488 if (!(filter.text in keyByFilter))2489 {2490 return;2491 }2492 var key = keyByFilter[filter.text];2493 delete filterByKey[key];2494 delete keyByFilter[filter.text];2495 ElemHide.isDirty = true;2496 }2497 },2498 getException: function(filter, docDomain)2499 {2500 var selector = filter.selector;2501 if (!(filter.selector in exceptions))2502 {2503 return null;2504 }2505 var list = exceptions[filter.selector];2506 for (var i = list.length - 1; i >= 0; i--)2507 {2508 if (list[i].isActiveOnDomain(docDomain))2509 {2510 return list[i];2511 }2512 }2513 return null;2514 },2515 _applying: false,2516 _needsApply: false,2517 apply: function()2518 {2519 if (this._applying)2520 {2521 this._needsApply = true;2522 return;2523 }2524 if (!ElemHide.isDirty || !Prefs.enabled)2525 {2526 if (Prefs.enabled && !ElemHide.applied)2527 {2528 try2529 {2530 Utils.styleService.loadAndRegisterSheet(styleURL, Ci.nsIStyleSheetService.USER_SHEET);2531 ElemHide.applied = true;2532 }2533 catch (e)2534 {2535 Cu.reportError(e);2536 }2537 }2538 else if (!Prefs.enabled && ElemHide.applied)2539 {2540 ElemHide.unapply();2541 }2542 return;2543 }2544 IO.writeToFile(styleURL.file, false, this._generateCSSContent(), function(e)2545 {2546 this._applying = false;2547 if (e && e.result == Cr.NS_ERROR_NOT_AVAILABLE)2548 {2549 IO.removeFile(styleURL.file, function(e2){});2550 }2551 else if (e)2552 {2553 Cu.reportError(e);2554 }2555 if (this._needsApply)2556 {2557 this._needsApply = false;2558 this.apply();2559 }2560 else if (!e || e.result == Cr.NS_ERROR_NOT_AVAILABLE)2561 {2562 ElemHide.isDirty = false;2563 ElemHide.unapply();2564 if (!e)2565 {2566 try2567 {2568 Utils.styleService.loadAndRegisterSheet(styleURL, Ci.nsIStyleSheetService.USER_SHEET);2569 ElemHide.applied = true;2570 }2571 catch (e)2572 {2573 Cu.reportError(e);2574 }2575 }2576 FilterNotifier.triggerListeners("elemhideupdate");2577 }2578 }.bind(this), "ElemHideWrite");2579 this._applying = true;2580 },2581 _generateCSSContent: function()2582 {2583 var _generatorResult16 = [];2584 var domains =2585 {2586 __proto__: null2587 };2588 var hasFilters = false;2589 for (var key in filterByKey)2590 {2591 var filter = filterByKey[key];2592 var domain = filter.selectorDomain || "";2593 var list;2594 if (domain in domains)2595 {2596 list = domains[domain];2597 }2598 else2599 {2600 list =2601 {2602 __proto__: null2603 };2604 domains[domain] = list;2605 }2606 list[filter.selector] = key;2607 hasFilters = true;2608 }2609 if (!hasFilters)2610 {2611 throw Cr.NS_ERROR_NOT_AVAILABLE;2612 }2613 function escapeChar(match)2614 {2615 return "\\" + match.charCodeAt(0).toString(16) + " ";2616 }2617 var cssTemplate = "-moz-binding: url(about:" + AboutHandler.aboutPrefix + "?%ID%#dummy) !important;";2618 for (var domain in domains)2619 {2620 var rules = [];2621 var list = domains[domain];2622 if (domain)2623 {2624 _generatorResult16.push(("@-moz-document domain(\"" + domain.split(",").join("\"),domain(\"") + "\"){").replace(/[^\x01-\x7F]/g, escapeChar));2625 }2626 else2627 {2628 _generatorResult16.push("@-moz-document url-prefix(\"http://\"),url-prefix(\"https://\")," + "url-prefix(\"mailbox://\"),url-prefix(\"imap://\")," + "url-prefix(\"news://\"),url-prefix(\"snews://\"){");2629 }2630 for (var selector in list)2631 {2632 _generatorResult16.push(selector.replace(/[^\x01-\x7F]/g, escapeChar) + "{" + cssTemplate.replace("%ID%", list[selector]) + "}");2633 }2634 _generatorResult16.push("}");2635 }2636 return _generatorResult16;2637 },2638 unapply: function()2639 {2640 if (ElemHide.applied)2641 {2642 try2643 {2644 Utils.styleService.unregisterSheet(styleURL, Ci.nsIStyleSheetService.USER_SHEET);2645 }2646 catch (e)2647 {2648 Cu.reportError(e);2649 }2650 ElemHide.applied = false;2651 }2652 },2653 get styleURL()2654 {2655 return ElemHide.applied ? styleURL.spec : null;2656 },2657 getFilterByKey: function(key)2658 {2659 return key in filterByKey ? filterByKey[key] : null;2660 },2661 getSelectorsForDomain: function(domain, specificOnly)2662 {2663 var result = [];2664 for (var key in filterByKey)2665 {2666 var filter = filterByKey[key];2667 if (specificOnly && (!filter.domains || filter.domains[""]))2668 {2669 continue;2670 }2671 if (filter.isActiveOnDomain(domain) && !this.getException(filter, domain))2672 {2673 result.push(filter.selector);2674 }2675 }2676 return result;2677 }2678 };2679 return exports;2680})();2681require.scopes["matcher"] = (function()2682{2683 var exports = {};2684 var _tempVar22 = require("filterClasses");2685 var Filter = _tempVar22.Filter;2686 var RegExpFilter = _tempVar22.RegExpFilter;2687 var WhitelistFilter = _tempVar22.WhitelistFilter;2688 function Matcher()2689 {2690 this.clear();2691 }2692 exports.Matcher = Matcher;2693 Matcher.prototype =2694 {2695 filterByKeyword: null,2696 keywordByFilter: null,2697 clear: function()2698 {2699 this.filterByKeyword =2700 {2701 __proto__: null2702 };2703 this.keywordByFilter =2704 {2705 __proto__: null2706 };2707 },2708 add: function(filter)2709 {2710 if (filter.text in this.keywordByFilter)2711 {2712 return;2713 }2714 var keyword = this.findKeyword(filter);2715 var oldEntry = this.filterByKeyword[keyword];2716 if (typeof oldEntry == "undefined")2717 {2718 this.filterByKeyword[keyword] = filter;2719 }2720 else if (oldEntry.length == 1)2721 {2722 this.filterByKeyword[keyword] = [oldEntry, filter];2723 }2724 else2725 {2726 oldEntry.push(filter);2727 }2728 this.keywordByFilter[filter.text] = keyword;2729 },2730 remove: function(filter)2731 {2732 if (!(filter.text in this.keywordByFilter))2733 {2734 return;2735 }2736 var keyword = this.keywordByFilter[filter.text];2737 var list = this.filterByKeyword[keyword];2738 if (list.length <= 1)2739 {2740 delete this.filterByKeyword[keyword];2741 }2742 else2743 {2744 var index = list.indexOf(filter);2745 if (index >= 0)2746 {2747 list.splice(index, 1);2748 if (list.length == 1)2749 {2750 this.filterByKeyword[keyword] = list[0];2751 }2752 }2753 }2754 delete this.keywordByFilter[filter.text];2755 },2756 findKeyword: function(filter)2757 {2758 var result = "";2759 var text = filter.text;2760 if (Filter.regexpRegExp.test(text))2761 {2762 return result;2763 }2764 var match = Filter.optionsRegExp.exec(text);2765 if (match)2766 {2767 text = match.input.substr(0, match.index);2768 }2769 if (text.substr(0, 2) == "@@")2770 {2771 text = text.substr(2);2772 }2773 var candidates = text.toLowerCase().match(/[^a-z0-9%*][a-z0-9%]{3,}(?=[^a-z0-9%*])/g);2774 if (!candidates)2775 {2776 return result;2777 }2778 var hash = this.filterByKeyword;2779 var resultCount = 16777215;2780 var resultLength = 0;2781 for (var i = 0, l = candidates.length; i < l; i++)2782 {2783 var candidate = candidates[i].substr(1);2784 var count = candidate in hash ? hash[candidate].length : 0;2785 if (count < resultCount || count == resultCount && candidate.length > resultLength)2786 {2787 result = candidate;2788 resultCount = count;2789 resultLength = candidate.length;2790 }2791 }2792 return result;2793 },2794 hasFilter: function(filter)2795 {2796 return filter.text in this.keywordByFilter;2797 },2798 getKeywordForFilter: function(filter)2799 {2800 if (filter.text in this.keywordByFilter)2801 {2802 return this.keywordByFilter[filter.text];2803 }2804 else2805 {2806 return null;2807 }2808 },2809 _checkEntryMatch: function(keyword, location, contentType, docDomain, thirdParty)2810 {2811 var list = this.filterByKeyword[keyword];2812 for (var i = 0; i < list.length; i++)2813 {2814 var filter = list[i];2815 if (filter.matches(location, contentType, docDomain, thirdParty))2816 {2817 return filter;2818 }2819 }2820 return null;2821 },2822 matchesAny: function(location, contentType, docDomain, thirdParty)2823 {2824 var candidates = location.toLowerCase().match(/[a-z0-9%]{3,}/g);2825 if (candidates === null)2826 {2827 candidates = [];2828 }2829 candidates.push("");2830 for (var i = 0, l = candidates.length; i < l; i++)2831 {2832 var substr = candidates[i];2833 if (substr in this.filterByKeyword)2834 {2835 var result = this._checkEntryMatch(substr, location, contentType, docDomain, thirdParty);2836 if (result)2837 {2838 return result;2839 }2840 }2841 }2842 return null;2843 }2844 };2845 function CombinedMatcher()2846 {2847 this.blacklist = new Matcher();2848 this.whitelist = new Matcher();2849 this.keys =2850 {2851 __proto__: null2852 };2853 this.resultCache =2854 {2855 __proto__: null2856 };2857 }2858 exports.CombinedMatcher = CombinedMatcher;2859 CombinedMatcher.maxCacheEntries = 1000;2860 CombinedMatcher.prototype =2861 {2862 blacklist: null,2863 whitelist: null,2864 keys: null,2865 resultCache: null,2866 cacheEntries: 0,2867 clear: function()2868 {2869 this.blacklist.clear();2870 this.whitelist.clear();2871 this.keys =2872 {2873 __proto__: null2874 };2875 this.resultCache =2876 {2877 __proto__: null2878 };2879 this.cacheEntries = 0;2880 },2881 add: function(filter)2882 {2883 if (filter instanceof WhitelistFilter)2884 {2885 if (filter.siteKeys)2886 {2887 for (var i = 0; i < filter.siteKeys.length; i++)2888 {2889 this.keys[filter.siteKeys[i]] = filter.text;2890 }2891 }2892 else2893 {2894 this.whitelist.add(filter);2895 }2896 }2897 else2898 {2899 this.blacklist.add(filter);2900 }2901 if (this.cacheEntries > 0)2902 {2903 this.resultCache =2904 {2905 __proto__: null2906 };2907 this.cacheEntries = 0;2908 }2909 },2910 remove: function(filter)2911 {2912 if (filter instanceof WhitelistFilter)2913 {2914 if (filter.siteKeys)2915 {2916 for (var i = 0; i < filter.siteKeys.length; i++)2917 {2918 delete this.keys[filter.siteKeys[i]];2919 }2920 }2921 else2922 {2923 this.whitelist.remove(filter);2924 }2925 }2926 else2927 {2928 this.blacklist.remove(filter);2929 }2930 if (this.cacheEntries > 0)2931 {2932 this.resultCache =2933 {2934 __proto__: null2935 };2936 this.cacheEntries = 0;2937 }2938 },2939 findKeyword: function(filter)2940 {2941 if (filter instanceof WhitelistFilter)2942 {2943 return this.whitelist.findKeyword(filter);2944 }2945 else2946 {2947 return this.blacklist.findKeyword(filter);2948 }2949 },2950 hasFilter: function(filter)2951 {2952 if (filter instanceof WhitelistFilter)2953 {2954 return this.whitelist.hasFilter(filter);2955 }2956 else2957 {2958 return this.blacklist.hasFilter(filter);2959 }2960 },2961 getKeywordForFilter: function(filter)2962 {2963 if (filter instanceof WhitelistFilter)2964 {2965 return this.whitelist.getKeywordForFilter(filter);2966 }2967 else2968 {2969 return this.blacklist.getKeywordForFilter(filter);2970 }2971 },2972 isSlowFilter: function(filter)2973 {2974 var matcher = filter instanceof WhitelistFilter ? this.whitelist : this.blacklist;2975 if (matcher.hasFilter(filter))2976 {2977 return !matcher.getKeywordForFilter(filter);2978 }2979 else2980 {2981 return !matcher.findKeyword(filter);2982 }2983 },2984 matchesAnyInternal: function(location, contentType, docDomain, thirdParty)2985 {2986 var candidates = location.toLowerCase().match(/[a-z0-9%]{3,}/g);2987 if (candidates === null)2988 {2989 candidates = [];2990 }2991 candidates.push("");2992 var blacklistHit = null;2993 for (var i = 0, l = candidates.length; i < l; i++)2994 {2995 var substr = candidates[i];2996 if (substr in this.whitelist.filterByKeyword)2997 {2998 var result = this.whitelist._checkEntryMatch(substr, location, contentType, docDomain, thirdParty);2999 if (result)3000 {3001 return result;3002 }3003 }3004 if (substr in this.blacklist.filterByKeyword && blacklistHit === null)3005 {3006 blacklistHit = this.blacklist._checkEntryMatch(substr, location, contentType, docDomain, thirdParty);3007 }3008 }3009 return blacklistHit;3010 },3011 matchesAny: function(location, contentType, docDomain, thirdParty)3012 {3013 var key = location + " " + contentType + " " + docDomain + " " + thirdParty;3014 if (key in this.resultCache)3015 {3016 return this.resultCache[key];3017 }3018 var result = this.matchesAnyInternal(location, contentType, docDomain, thirdParty);3019 if (this.cacheEntries >= CombinedMatcher.maxCacheEntries)3020 {3021 this.resultCache =3022 {3023 __proto__: null3024 };3025 this.cacheEntries = 0;3026 }3027 this.resultCache[key] = result;3028 this.cacheEntries++;3029 return result;3030 },3031 matchesByKey: function(location, key, docDomain)3032 {3033 key = key.toUpperCase();3034 if (key in this.keys)3035 {3036 var filter = Filter.knownFilters[this.keys[key]];3037 if (filter && filter.matches(location, "DOCUMENT", docDomain, false))3038 {3039 return filter;3040 }3041 else3042 {3043 return null;3044 }3045 }3046 else3047 {3048 return null;3049 }3050 }3051 };3052 var defaultMatcher = exports.defaultMatcher = new CombinedMatcher();3053 return exports;3054})();3055require.scopes["filterListener"] = (function()3056{3057 var exports = {};3058 var FilterStorage = require("filterStorage").FilterStorage;3059 var FilterNotifier = require("filterNotifier").FilterNotifier;3060 var ElemHide = require("elemHide").ElemHide;3061 var defaultMatcher = require("matcher").defaultMatcher;3062 var _tempVar23 = require("filterClasses");3063 var ActiveFilter = _tempVar23.ActiveFilter;3064 var RegExpFilter = _tempVar23.RegExpFilter;3065 var ElemHideBase = _tempVar23.ElemHideBase;3066 var Prefs = require("prefs").Prefs;3067 var batchMode = false;3068 var isDirty = 0;3069 var FilterListener = exports.FilterListener =3070 {3071 get batchMode()3072 {3073 return batchMode;3074 },3075 set batchMode(value)3076 {3077 batchMode = value;3078 flushElemHide();3079 },3080 setDirty: function(factor)3081 {3082 if (factor == 0 && isDirty > 0)3083 {3084 isDirty = 1;3085 }3086 else3087 {3088 isDirty += factor;3089 }3090 if (isDirty >= 1)3091 {3092 FilterStorage.saveToDisk();3093 }3094 }3095 };3096 var HistoryPurgeObserver =3097 {3098 observe: function(subject, topic, data)3099 {3100 if (topic == "browser:purge-session-history" && Prefs.clearStatsOnHistoryPurge)3101 {3102 FilterStorage.resetHitCounts();3103 FilterListener.setDirty(0);3104 Prefs.recentReports = [];3105 }3106 },3107 QueryInterface: XPCOMUtils.generateQI([Ci.nsISupportsWeakReference, Ci.nsIObserver])3108 };3109 function init()3110 {3111 FilterNotifier.addListener(function(action, item, newValue, oldValue)3112 {3113 var match = /^(\w+)\.(.*)/.exec(action);3114 if (match && match[1] == "filter")3115 {3116 onFilterChange(match[2], item, newValue, oldValue);3117 }3118 else if (match && match[1] == "subscription")3119 {3120 onSubscriptionChange(match[2], item, newValue, oldValue);3121 }3122 else3123 {3124 onGenericChange(action, item);3125 }3126 });3127 if ("nsIStyleSheetService" in Ci)3128 {3129 ElemHide.init();3130 }3131 else3132 {3133 flushElemHide = function(){};3134 }3135 FilterStorage.loadFromDisk();3136 Services.obs.addObserver(HistoryPurgeObserver, "browser:purge-session-history", true);3137 onShutdown.add(function()3138 {3139 Services.obs.removeObserver(HistoryPurgeObserver, "browser:purge-session-history");3140 });3141 }3142 init();3143 function flushElemHide()3144 {3145 if (!batchMode && ElemHide.isDirty)3146 {3147 ElemHide.apply();3148 }3149 }3150 function addFilter(filter)3151 {3152 if (!(filter instanceof ActiveFilter) || filter.disabled)3153 {3154 return;3155 }3156 var hasEnabled = false;3157 for (var i = 0; i < filter.subscriptions.length; i++)3158 {3159 if (!filter.subscriptions[i].disabled)3160 {3161 hasEnabled = true;3162 }3163 }3164 if (!hasEnabled)3165 {3166 return;3167 }3168 if (filter instanceof RegExpFilter)3169 {3170 defaultMatcher.add(filter);3171 }3172 else if (filter instanceof ElemHideBase)3173 {3174 ElemHide.add(filter);3175 }3176 }3177 function removeFilter(filter)3178 {3179 if (!(filter instanceof ActiveFilter))3180 {3181 return;3182 }3183 if (!filter.disabled)3184 {3185 var hasEnabled = false;3186 for (var i = 0; i < filter.subscriptions.length; i++)3187 {3188 if (!filter.subscriptions[i].disabled)3189 {3190 hasEnabled = true;3191 }3192 }3193 if (hasEnabled)3194 {3195 return;3196 }3197 }3198 if (filter instanceof RegExpFilter)3199 {3200 defaultMatcher.remove(filter);3201 }3202 else if (filter instanceof ElemHideBase)3203 {3204 ElemHide.remove(filter);3205 }3206 }3207 function onSubscriptionChange(action, subscription, newValue, oldValue)3208 {3209 FilterListener.setDirty(1);3210 if (action != "added" && action != "removed" && action != "disabled" && action != "updated")3211 {3212 return;3213 }3214 if (action != "removed" && !(subscription.url in FilterStorage.knownSubscriptions))3215 {3216 return;3217 }3218 if ((action == "added" || action == "removed" || action == "updated") && subscription.disabled)3219 {3220 return;3221 }3222 if (action == "added" || action == "removed" || action == "disabled")3223 {3224 var method = action == "added" || action == "disabled" && newValue == false ? addFilter : removeFilter;3225 if (subscription.filters)3226 {3227 subscription.filters.forEach(method);3228 }3229 }3230 else if (action == "updated")3231 {3232 subscription.oldFilters.forEach(removeFilter);3233 subscription.filters.forEach(addFilter);3234 }3235 flushElemHide();3236 }3237 function onFilterChange(action, filter, newValue, oldValue)3238 {3239 if (action == "hitCount" || action == "lastHit")3240 {3241 FilterListener.setDirty(0.002);3242 }3243 else3244 {3245 FilterListener.setDirty(1);3246 }3247 if (action != "added" && action != "removed" && action != "disabled")3248 {3249 return;3250 }3251 if ((action == "added" || action == "removed") && filter.disabled)3252 {3253 return;3254 }3255 if (action == "added" || action == "disabled" && newValue == false)3256 {3257 addFilter(filter);3258 }3259 else3260 {3261 removeFilter(filter);3262 }3263 flushElemHide();3264 }3265 function onGenericChange(action)3266 {3267 if (action == "load")3268 {3269 isDirty = 0;3270 defaultMatcher.clear();3271 ElemHide.clear();3272 for (var _loopIndex24 = 0; _loopIndex24 < FilterStorage.subscriptions.length; ++_loopIndex24)3273 {3274 var subscription = FilterStorage.subscriptions[_loopIndex24];3275 if (!subscription.disabled)3276 {3277 subscription.filters.forEach(addFilter);3278 }3279 }3280 flushElemHide();3281 }3282 else if (action == "save")3283 {3284 isDirty = 0;3285 }3286 }3287 return exports;3288})();3289require.scopes["synchronizer"] = (function()3290{3291 var exports = {};3292 var _tempVar25 = require("downloader");3293 var Downloader = _tempVar25.Downloader;3294 var Downloadable = _tempVar25.Downloadable;3295 var MILLIS_IN_SECOND = _tempVar25.MILLIS_IN_SECOND;3296 var MILLIS_IN_MINUTE = _tempVar25.MILLIS_IN_MINUTE;3297 var MILLIS_IN_HOUR = _tempVar25.MILLIS_IN_HOUR;3298 var MILLIS_IN_DAY = _tempVar25.MILLIS_IN_DAY;3299 var _tempVar26 = require("filterClasses");3300 var Filter = _tempVar26.Filter;3301 var CommentFilter = _tempVar26.CommentFilter;3302 var FilterStorage = require("filterStorage").FilterStorage;3303 var FilterNotifier = require("filterNotifier").FilterNotifier;3304 var Prefs = require("prefs").Prefs;3305 var _tempVar27 = require("subscriptionClasses");3306 var Subscription = _tempVar27.Subscription;3307 var DownloadableSubscription = _tempVar27.DownloadableSubscription;3308 var Utils = require("utils").Utils;3309 var INITIAL_DELAY = 6 * MILLIS_IN_MINUTE;3310 var CHECK_INTERVAL = 1 * MILLIS_IN_HOUR;3311 var DEFAULT_EXPIRATION_INTERVAL = 5 * MILLIS_IN_DAY;3312 var downloader = null;3313 var Synchronizer = exports.Synchronizer =3314 {3315 init: function()3316 {3317 downloader = new Downloader(this._getDownloadables.bind(this), INITIAL_DELAY, CHECK_INTERVAL);3318 onShutdown.add(function()3319 {3320 downloader.cancel();3321 });3322 downloader.onExpirationChange = this._onExpirationChange.bind(this);3323 downloader.onDownloadStarted = this._onDownloadStarted.bind(this);3324 downloader.onDownloadSuccess = this._onDownloadSuccess.bind(this);3325 downloader.onDownloadError = this._onDownloadError.bind(this);3326 },3327 isExecuting: function(url)3328 {3329 return downloader.isDownloading(url);3330 },3331 execute: function(subscription, manual)3332 {3333 downloader.download(this._getDownloadable(subscription, manual));3334 },3335 _getDownloadables: function()3336 {3337 var _generatorResult16 = [];3338 if (!Prefs.subscriptions_autoupdate)3339 {3340 return;3341 }3342 for (var _loopIndex28 = 0; _loopIndex28 < FilterStorage.subscriptions.length; ++_loopIndex28)3343 {3344 var subscription = FilterStorage.subscriptions[_loopIndex28];3345 if (subscription instanceof DownloadableSubscription)3346 {3347 _generatorResult16.push(this._getDownloadable(subscription, false));3348 }3349 }3350 return _generatorResult16;3351 },3352 _getDownloadable: function(subscription, manual)3353 {3354 var result = new Downloadable(subscription.url);3355 if (subscription.lastDownload != subscription.lastSuccess)3356 {3357 result.lastError = subscription.lastDownload * MILLIS_IN_SECOND;3358 }3359 result.lastCheck = subscription.lastCheck * MILLIS_IN_SECOND;3360 result.lastVersion = subscription.version;3361 result.softExpiration = subscription.softExpiration * MILLIS_IN_SECOND;3362 result.hardExpiration = subscription.expires * MILLIS_IN_SECOND;3363 result.manual = manual;3364 return result;3365 },3366 _onExpirationChange: function(downloadable)3367 {3368 var subscription = Subscription.fromURL(downloadable.url);3369 subscription.lastCheck = Math.round(downloadable.lastCheck / MILLIS_IN_SECOND);3370 subscription.softExpiration = Math.round(downloadable.softExpiration / MILLIS_IN_SECOND);3371 subscription.expires = Math.round(downloadable.hardExpiration / MILLIS_IN_SECOND);3372 },3373 _onDownloadStarted: function(downloadable)3374 {3375 var subscription = Subscription.fromURL(downloadable.url);3376 FilterNotifier.triggerListeners("subscription.downloadStatus", subscription);3377 },3378 _onDownloadSuccess: function(downloadable, responseText, errorCallback, redirectCallback)3379 {3380 var lines = responseText.split(/[\r\n]+/);3381 var match = /\[Adblock(?:\s*Plus\s*([\d\.]+)?)?\]/i.exec(lines[0]);3382 if (!match)3383 {3384 return errorCallback("synchronize_invalid_data");3385 }3386 var minVersion = match[1];3387 var remove = [];3388 var params =3389 {3390 redirect: null,3391 homepage: null,3392 title: null,3393 version: null,3394 expires: null3395 };3396 for (var i = 0; i < lines.length; i++)3397 {3398 var match = /^\s*!\s*(\w+)\s*:\s*(.*)/.exec(lines[i]);3399 if (match)3400 {3401 var keyword = match[1].toLowerCase();3402 var value = match[2];3403 if (keyword in params)3404 {3405 params[keyword] = value;3406 remove.push(i);3407 }3408 else if (keyword == "checksum")3409 {3410 lines.splice(i--, 1);3411 var checksum = Utils.generateChecksum(lines);3412 if (checksum && checksum != value.replace(/=+$/, ""))3413 {3414 return errorCallback("synchronize_checksum_mismatch");3415 }3416 }3417 }3418 }3419 if (params.redirect)3420 {3421 return redirectCallback(params.redirect);3422 }3423 var subscription = Subscription.fromURL(downloadable.redirectURL || downloadable.url);3424 if (downloadable.redirectURL && downloadable.redirectURL != downloadable.url)3425 {3426 var oldSubscription = Subscription.fromURL(downloadable.url);3427 subscription.title = oldSubscription.title;3428 subscription.disabled = oldSubscription.disabled;3429 subscription.lastCheck = oldSubscription.lastCheck;3430 var listed = oldSubscription.url in FilterStorage.knownSubscriptions;3431 if (listed)3432 {3433 FilterStorage.removeSubscription(oldSubscription);3434 }3435 delete Subscription.knownSubscriptions[oldSubscription.url];3436 if (listed)3437 {3438 FilterStorage.addSubscription(subscription);3439 }3440 }3441 subscription.lastSuccess = subscription.lastDownload = Math.round(Date.now() / MILLIS_IN_SECOND);3442 subscription.downloadStatus = "synchronize_ok";3443 subscription.errors = 0;3444 for (var i = remove.length - 1; i >= 0; i--)3445 {3446 lines.splice(remove[i], 1);3447 }3448 if (params.homepage)3449 {3450 var uri = Utils.makeURI(params.homepage);3451 if (uri && (uri.scheme == "http" || uri.scheme == "https"))3452 {3453 subscription.homepage = uri.spec;3454 }3455 }3456 if (params.title)3457 {3458 subscription.title = params.title;3459 subscription.fixedTitle = true;3460 }3461 else3462 {3463 subscription.fixedTitle = false;3464 }3465 subscription.version = params.version ? parseInt(params.version, 10) : 0;3466 var expirationInterval = DEFAULT_EXPIRATION_INTERVAL;3467 if (params.expires)3468 {3469 var match = /^(\d+)\s*(h)?/.exec(params.expires);3470 if (match)3471 {3472 var interval = parseInt(match[1], 10);3473 if (match[2])3474 {3475 expirationInterval = interval * MILLIS_IN_HOUR;3476 }3477 else3478 {3479 expirationInterval = interval * MILLIS_IN_DAY;3480 }3481 }3482 }3483 var _tempVar29 = downloader.processExpirationInterval(expirationInterval);3484 var softExpiration = _tempVar29[0];3485 var hardExpiration = _tempVar29[1];3486 subscription.softExpiration = Math.round(softExpiration / MILLIS_IN_SECOND);3487 subscription.expires = Math.round(hardExpiration / MILLIS_IN_SECOND);3488 delete subscription.requiredVersion;3489 delete subscription.upgradeRequired;3490 if (minVersion)3491 {3492 var addonVersion = require("info").addonVersion;3493 subscription.requiredVersion = minVersion;3494 if (Services.vc.compare(minVersion, addonVersion) > 0)3495 {3496 subscription.upgradeRequired = true;3497 }3498 }3499 lines.shift();3500 var filters = [];3501 for (var _loopIndex30 = 0; _loopIndex30 < lines.length; ++_loopIndex30)3502 {3503 var line = lines[_loopIndex30];3504 line = Filter.normalize(line);3505 if (line)3506 {3507 filters.push(Filter.fromText(line));3508 }3509 }3510 FilterStorage.updateSubscriptionFilters(subscription, filters);3511 return undefined;3512 },3513 _onDownloadError: function(downloadable, downloadURL, error, channelStatus, responseStatus, redirectCallback)3514 {3515 var subscription = Subscription.fromURL(downloadable.url);3516 subscription.lastDownload = Math.round(Date.now() / MILLIS_IN_SECOND);3517 subscription.downloadStatus = error;3518 if (!downloadable.manual)3519 {3520 subscription.errors++;3521 if (redirectCallback && subscription.errors >= Prefs.subscriptions_fallbackerrors && /^https?:\/\//i.test(subscription.url))3522 {3523 subscription.errors = 0;3524 var fallbackURL = Prefs.subscriptions_fallbackurl;3525 var addonVersion = require("info").addonVersion;3526 fallbackURL = fallbackURL.replace(/%VERSION%/g, encodeURIComponent(addonVersion));3527 fallbackURL = fallbackURL.replace(/%SUBSCRIPTION%/g, encodeURIComponent(subscription.url));3528 fallbackURL = fallbackURL.replace(/%URL%/g, encodeURIComponent(downloadURL));3529 fallbackURL = fallbackURL.replace(/%ERROR%/g, encodeURIComponent(error));3530 fallbackURL = fallbackURL.replace(/%CHANNELSTATUS%/g, encodeURIComponent(channelStatus));3531 fallbackURL = fallbackURL.replace(/%RESPONSESTATUS%/g, encodeURIComponent(responseStatus));3532 var request = new XMLHttpRequest();3533 request.mozBackgroundRequest = true;3534 request.open("GET", fallbackURL);3535 request.overrideMimeType("text/plain");3536 request.channel.loadFlags = request.channel.loadFlags | request.channel.INHIBIT_CACHING | request.channel.VALIDATE_ALWAYS;3537 request.addEventListener("load", function(ev)3538 {3539 if (onShutdown.done)3540 {3541 return;3542 }3543 if (!(subscription.url in FilterStorage.knownSubscriptions))3544 {3545 return;3546 }3547 var match = /^(\d+)(?:\s+(\S+))?$/.exec(request.responseText);3548 if (match && match[1] == "301" && match[2] && /^https?:\/\//i.test(match[2]))3549 {3550 redirectCallback(match[2]);3551 }3552 else if (match && match[1] == "410")3553 {3554 var data = "[Adblock]\n" + subscription.filters.map(function(f)3555 {3556 return f.text;3557 }).join("\n");3558 redirectCallback("data:text/plain," + encodeURIComponent(data));3559 }3560 }, false);3561 request.send(null);3562 }3563 }3564 }3565 };3566 Synchronizer.init();3567 return exports;3568})();3569require.scopes["notification"] = (function()3570{3571 var exports = {};3572 var Prefs = require("prefs").Prefs;3573 var _tempVar31 = require("downloader");3574 var Downloader = _tempVar31.Downloader;3575 var Downloadable = _tempVar31.Downloadable;3576 var MILLIS_IN_MINUTE = _tempVar31.MILLIS_IN_MINUTE;3577 var MILLIS_IN_HOUR = _tempVar31.MILLIS_IN_HOUR;3578 var MILLIS_IN_DAY = _tempVar31.MILLIS_IN_DAY;3579 var Utils = require("utils").Utils;3580 var INITIAL_DELAY = 12 * MILLIS_IN_MINUTE;3581 var CHECK_INTERVAL = 1 * MILLIS_IN_HOUR;3582 var EXPIRATION_INTERVAL = 1 * MILLIS_IN_DAY;3583 function getNumericalSeverity(notification)3584 {3585 var levels =3586 {3587 information: 0,3588 critical: 13589 };3590 return notification.severity in levels ? levels[notification.severity] : levels.information;3591 }3592 function saveNotificationData()3593 {3594 Prefs.notificationdata = JSON.parse(JSON.stringify(Prefs.notificationdata));3595 }3596 function localize(translations, locale)3597 {3598 if (locale in translations)3599 {3600 return translations[locale];3601 }3602 var languagePart = locale.substring(0, locale.indexOf("-"));3603 if (languagePart && languagePart in translations)3604 {3605 return translations[languagePart];3606 }3607 var defaultLocale = "en-US";3608 return translations[defaultLocale];3609 }3610 var downloader = null;3611 var Notification = exports.Notification =3612 {3613 init: function()3614 {3615 downloader = new Downloader(this._getDownloadables.bind(this), INITIAL_DELAY, CHECK_INTERVAL);3616 onShutdown.add(function()3617 {3618 downloader.cancel();3619 });3620 downloader.onExpirationChange = this._onExpirationChange.bind(this);3621 downloader.onDownloadSuccess = this._onDownloadSuccess.bind(this);3622 downloader.onDownloadError = this._onDownloadError.bind(this);3623 },3624 _getDownloadables: function()3625 {3626 var _generatorResult16 = [];3627 var downloadable = new Downloadable(Prefs.notificationurl);3628 if (typeof Prefs.notificationdata.lastError === "number")3629 {3630 downloadable.lastError = Prefs.notificationdata.lastError;3631 }3632 if (typeof Prefs.notificationdata.lastCheck === "number")3633 {3634 downloadable.lastCheck = Prefs.notificationdata.lastCheck;3635 }3636 if (typeof Prefs.notificationdata.data === "object" && "version" in Prefs.notificationdata.data)3637 {3638 downloadable.lastVersion = Prefs.notificationdata.data.version;3639 }3640 if (typeof Prefs.notificationdata.softExpiration === "number")3641 {3642 downloadable.softExpiration = Prefs.notificationdata.softExpiration;3643 }3644 if (typeof Prefs.notificationdata.hardExpiration === "number")3645 {3646 downloadable.hardExpiration = Prefs.notificationdata.hardExpiration;3647 }3648 _generatorResult16.push(downloadable);3649 return _generatorResult16;3650 },3651 _onExpirationChange: function(downloadable)3652 {3653 Prefs.notificationdata.lastCheck = downloadable.lastCheck;3654 Prefs.notificationdata.softExpiration = downloadable.softExpiration;3655 Prefs.notificationdata.hardExpiration = downloadable.hardExpiration;3656 saveNotificationData();3657 },3658 _onDownloadSuccess: function(downloadable, responseText, errorCallback, redirectCallback)3659 {3660 try3661 {3662 Prefs.notificationdata.data = JSON.parse(responseText);3663 }3664 catch (e)3665 {3666 Cu.reportError(e);3667 errorCallback("synchronize_invalid_data");3668 return;3669 }3670 Prefs.notificationdata.lastError = 0;3671 Prefs.notificationdata.downloadStatus = "synchronize_ok";3672 var _tempVar32 = downloader.processExpirationInterval(EXPIRATION_INTERVAL);3673 Prefs.notificationdata.softExpiration = _tempVar32[0];3674 Prefs.notificationdata.hardExpiration = _tempVar32[1];3675 saveNotificationData();3676 },3677 _onDownloadError: function(downloadable, downloadURL, error, channelStatus, responseStatus, redirectCallback)3678 {3679 Prefs.notificationdata.lastError = Date.now();3680 Prefs.notificationdata.downloadStatus = error;3681 saveNotificationData();3682 },3683 getNextToShow: function()3684 {3685 function checkTarget(target, parameter, name, version)3686 {3687 var minVersionKey = parameter + "MinVersion";3688 var maxVersionKey = parameter + "MaxVersion";3689 return !(parameter in target && target[parameter] != name || minVersionKey in target && Services.vc.compare(version, target[minVersionKey]) < 0 || maxVersionKey in target && Services.vc.compare(version, target[maxVersionKey]) > 0);3690 }3691 if (typeof Prefs.notificationdata.data != "object" || !(Prefs.notificationdata.data.notifications instanceof Array))3692 {3693 return null;3694 }3695 if (!(Prefs.notificationdata.shown instanceof Array))3696 {3697 Prefs.notificationdata.shown = [];3698 saveNotificationData();3699 }3700 var _tempVar33 = require("info");3701 var addonName = _tempVar33.addonName;3702 var addonVersion = _tempVar33.addonVersion;3703 var application = _tempVar33.application;3704 var applicationVersion = _tempVar33.applicationVersion;3705 var platform = _tempVar33.platform;3706 var platformVersion = _tempVar33.platformVersion;3707 var notifications = Prefs.notificationdata.data.notifications;3708 var notificationToShow = null;3709 for (var _loopIndex34 = 0; _loopIndex34 < notifications.length; ++_loopIndex34)3710 {3711 var notification = notifications[_loopIndex34];3712 if ((typeof notification.severity === "undefined" || notification.severity === "information") && Prefs.notificationdata.shown.indexOf(notification.id) !== -1)3713 {3714 continue;3715 }3716 if (notification.targets instanceof Array)3717 {3718 var match = false;3719 for (var _loopIndex35 = 0; _loopIndex35 < notification.targets.length; ++_loopIndex35)3720 {3721 var target = notification.targets[_loopIndex35];3722 if (checkTarget(target, "extension", addonName, addonVersion) && checkTarget(target, "application", application, applicationVersion) && checkTarget(target, "platform", platform, platformVersion))3723 {3724 match = true;3725 break;3726 }3727 }3728 if (!match)3729 {3730 continue;3731 }3732 }3733 if (!notificationToShow || getNumericalSeverity(notification) > getNumericalSeverity(notificationToShow))3734 {3735 notificationToShow = notification;3736 }3737 }3738 if (notificationToShow && "id" in notificationToShow)3739 {3740 Prefs.notificationdata.shown.push(notificationToShow.id);3741 saveNotificationData();3742 }3743 return notificationToShow;3744 },3745 getLocalizedTexts: function(notification, locale)3746 {3747 locale = locale || Utils.appLocale;3748 var textKeys = ["title", "message"];3749 var localizedTexts = [];3750 for (var _loopIndex36 = 0; _loopIndex36 < textKeys.length; ++_loopIndex36)3751 {3752 var key = textKeys[_loopIndex36];3753 if (key in notification)3754 {3755 localizedTexts[key] = localize(notification[key], locale);3756 }3757 }3758 return localizedTexts;3759 }3760 };3761 Notification.init();3762 return exports;3763})();3764require.scopes["stats"] = (function()3765{3766 var exports = {};3767 var Prefs = require("prefs").Prefs;3768 var BlockingFilter = require("filterClasses").BlockingFilter;3769 var FilterNotifier = require("filterNotifier").FilterNotifier;3770 var badgeColor = "#646464";3771 var statsPerTab = new TabMap(true);3772 var getStats = exports.getStats = function getStats(key, tab)3773 {3774 if (!tab)3775 {3776 return key in Prefs.stats_total ? Prefs.stats_total[key] : 0;3777 }3778 var tabStats = statsPerTab.get(tab);3779 return tabStats ? tabStats.blocked : 0;3780 };3781 FilterNotifier.addListener(function(action, item, newValue, oldValue, tab)3782 {3783 if (action != "filter.hitCount" || !tab)3784 {3785 return;3786 }3787 var blocked = item instanceof BlockingFilter;3788 if (blocked)3789 {3790 if ("blocked" in Prefs.stats_total)3791 {3792 Prefs.stats_total.blocked++;3793 }3794 else3795 {3796 Prefs.stats_total.blocked = 1;3797 }3798 Prefs.stats_total = Prefs.stats_total;3799 var tabStats = statsPerTab.get(tab);3800 if (!tabStats)3801 {3802 tabStats = {};3803 statsPerTab.set(tab, tabStats);3804 }3805 if ("blocked" in tabStats)3806 {3807 tabStats.blocked++;3808 }3809 else3810 {3811 tabStats.blocked = 1;3812 }3813 if (Prefs.show_statsinicon)3814 {3815 tab.browserAction.setBadge(3816 {3817 color: badgeColor,3818 number: tabStats.blocked3819 });3820 }3821 }3822 });3823 function forEachTab(func)3824 {3825 ext.windows.getAll(function(windows)3826 {3827 for (var _loopIndex37 = 0; _loopIndex37 < windows.length; ++_loopIndex37)3828 {3829 var window = windows[_loopIndex37];3830 window.getAllTabs(function(tabs)3831 {3832 for (var i = 0; i < tabs.length; i++)3833 {3834 func(tabs[i]);3835 }3836 });3837 }3838 });3839 }3840 Prefs.addListener(function(name)3841 {3842 if (name != "show_statsinicon")3843 {3844 return;3845 }3846 forEachTab(function(tab)3847 {3848 var badge = null;3849 if (Prefs.show_statsinicon)3850 {3851 var tabStats = statsPerTab.get(tab);3852 if (tabStats && "blocked" in tabStats)3853 {3854 badge =3855 {3856 color: badgeColor,3857 number: tabStats.blocked3858 };3859 }3860 }3861 tab.browserAction.setBadge(badge);3862 });3863 });3864 return exports;3865})();3866require.scopes["whitelisting"] = (function()3867{3868 var exports = {};3869 var defaultMatcher = require("matcher").defaultMatcher;3870 var WhitelistFilter = require("filterClasses").WhitelistFilter;3871 var tabsWithKeyException = new TabMap(true);3872 var isWhitelisted = exports.isWhitelisted = function(url, parentUrl, type)3873 {3874 var filter = defaultMatcher.matchesAny(stripFragmentFromURL(url), type || "DOCUMENT", extractHostFromURL(parentUrl || url), false);3875 return filter instanceof WhitelistFilter ? filter : null;3876 };3877 var isFrameWhitelisted = exports.isFrameWhitelisted = function(tab, frame, type)3878 {3879 var urlsWithKeyException = tabsWithKeyException.get(tab);3880 for (; frame != null; frame = frame.parent)3881 {3882 if (urlsWithKeyException && stripFragmentFromURL(frame.url) in urlsWithKeyException)3883 {3884 return true;3885 }3886 if (isWhitelisted(frame.url, (frame.parent || {}).url, type))3887 {3888 return true;3889 }3890 }3891 return false;3892 };3893 var verifyKeyException = function(token, url, docDomain)3894 {3895 var match = token.match(/((.*?)=*)_(.*)/);3896 if (!match)3897 {3898 return false;3899 }3900 var strippedKey = match[2];3901 if (!defaultMatcher.matchesByKey(url, strippedKey, docDomain))3902 {3903 return false;3904 }3905 var uri = new URI(url);3906 var params = [uri.path, uri.asciiHost + (uri.port != -1 ? ":" + uri.port : ""), window.navigator.userAgent];3907 var key = match[1];3908 var signature = match[3];3909 return verifySignature(key, signature, params.join("\x00"));3910 };3911 var recordKeyException = function(tab, url)3912 {3913 var urlsWithKeyException = tabsWithKeyException.get(tab);3914 if (!urlsWithKeyException)3915 {3916 urlsWithKeyException =3917 {3918 __proto__: null3919 };3920 tabsWithKeyException.set(tab, urlsWithKeyException);3921 }3922 urlsWithKeyException[url] = null;3923 };3924 var processKeyException = exports.processKeyException = function(token, tab, frame)3925 {3926 var url = stripFragmentFromURL(frame.url);3927 var docDomain = extractHostFromURL((frame.parent || frame).url);3928 if (verifyKeyException(token, url, docDomain))3929 {3930 recordKeyException(tab, url);3931 }3932 };3933 return exports;...

Full Screen

Full Screen

network.js

Source:network.js Github

copy

Full Screen

...69 } catch (e) {70 return null;71 }72}73function stripFragmentFromUrl(url) {74 if (!url.includes('#')) return url;75 return url.substring(0, url.indexOf('#'));76}77class Request extends _instrumentation.SdkObject {78 constructor(frame, redirectedFrom, documentId, url, resourceType, method, postData, headers) {79 super(frame, 'request');80 this._response = null;81 this._redirectedFrom = void 0;82 this._redirectedTo = null;83 this._documentId = void 0;84 this._isFavicon = void 0;85 this._failureText = null;86 this._url = void 0;87 this._resourceType = void 0;88 this._method = void 0;89 this._postData = void 0;90 this._headers = void 0;91 this._headersMap = new Map();92 this._frame = void 0;93 this._waitForResponsePromise = void 0;94 this._waitForResponsePromiseCallback = () => {};95 this._responseEndTiming = -1;96 (0, _utils.assert)(!url.startsWith('data:'), 'Data urls should not fire requests');97 this._frame = frame;98 this._redirectedFrom = redirectedFrom;99 if (redirectedFrom) redirectedFrom._redirectedTo = this;100 this._documentId = documentId;101 this._url = stripFragmentFromUrl(url);102 this._resourceType = resourceType;103 this._method = method;104 this._postData = postData;105 this._headers = headers;106 for (const {107 name,108 value109 } of this._headers) this._headersMap.set(name.toLowerCase(), value);110 this._waitForResponsePromise = new Promise(f => this._waitForResponsePromiseCallback = f);111 this._isFavicon = url.endsWith('/favicon.ico');112 }113 _setFailureText(failureText) {114 this._failureText = failureText;115 this._waitForResponsePromiseCallback(null);...

Full Screen

Full Screen

utilsUri.js

Source:utilsUri.js Github

copy

Full Screen

1/*!2 * Parts of original code from ipv6.js <https://github.com/beaugunderson/javascript-ipv6>3 * Copyright 2011 Beau Gunderson4 * Available under MIT license <http://mths.be/mit>5 */6const RE_V4 = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|0x[0-9a-f][0-9a-f]?|0[0-7]{3})\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|0x[0-9a-f][0-9a-f]?|0[0-7]{3})$/i;7const RE_V4_HEX = /^0x([0-9a-f]{8})$/i;8const RE_V4_NUMERIC = /^[0-9]+$/;9const RE_V4inV6 = /(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;10const RE_BAD_CHARACTERS = /([^0-9a-f:])/i;11const RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]$)/i;12function isIPv4(address)13{14 if (RE_V4.test(address))15 return true;16 if (RE_V4_HEX.test(address))17 return true;18 if (RE_V4_NUMERIC.test(address))19 return true;20 return false;21}22function isIPv6(address)23{24 var a4addon = 0;25 var address4 = address.match(RE_V4inV6);26 if (address4)27 {28 var temp4 = address4[0].split('.');29 for (var i = 0; i < 4; i++)30 {31 if (/^0[0-9]+/.test(temp4[i]))32 return false;33 }34 address = address.replace(RE_V4inV6, '');35 if (/[0-9]$/.test(address))36 return false;37 address = address + temp4.join(':');38 a4addon = 2;39 }40 if (RE_BAD_CHARACTERS.test(address))41 return false;42 if (RE_BAD_ADDRESS.test(address))43 return false;44 function count(string, substring)45 {46 return (string.length - string.replace(new RegExp(substring,"g"), '').length) / substring.length;47 }48 var halves = count(address, '::');49 if (halves == 1 && count(address, ':') <= 6 + 2 + a4addon)50 return true;51 if (halves == 0 && count(address, ':') == 7 + a4addon)52 return true;53 return false;54}55/**56 * Returns base domain for specified host based on Public Suffix List.57 */58let getBaseDomain = exports.getBaseDomain = function getBaseDomain(/**String*/ hostname) /**String*/59{60 // remove trailing dot(s)61 hostname = hostname.replace(/\.+$/, '');62 // return IP address untouched63 if (isIPv6(hostname) || isIPv4(hostname))64 return hostname;65 // decode punycode if exists66 if (hostname.indexOf('xn--') >= 0)67 {68 hostname = punycode.toUnicode(hostname);69 }70 // search through PSL71 var prevDomains = [];72 var curDomain = hostname;73 var nextDot = curDomain.indexOf('.');74 var tld = 0;75 while (true)76 {77 var suffix = publicSuffixes[curDomain];78 if (typeof(suffix) != 'undefined')79 {80 tld = suffix;81 break;82 }83 if (nextDot < 0)84 {85 tld = 1;86 break;87 }88 prevDomains.push(curDomain.substring(0,nextDot));89 curDomain = curDomain.substring(nextDot+1);90 nextDot = curDomain.indexOf('.');91 }92 while (tld > 0 && prevDomains.length > 0)93 {94 curDomain = prevDomains.pop() + '.' + curDomain;95 tld--;96 }97 return curDomain;98}99/**100 * Checks whether a request is third party for the given document, uses101 * information from the public suffix list to determine the effective domain102 * name for the document.103 */104let isThirdParty = exports.isThirdParty = function isThirdParty(/**String*/ requestHost, /**String*/ documentHost)105{106 // Remove trailing dots107 requestHost = requestHost.replace(/\.+$/, "");108 documentHost = documentHost.replace(/\.+$/, "");109 // Extract domain name - leave IP addresses unchanged, otherwise leave only base domain110 var documentDomain = getBaseDomain(documentHost);111 if (requestHost.length > documentDomain.length)112 return (requestHost.substr(requestHost.length - documentDomain.length - 1) != "." + documentDomain);113 else114 return (requestHost != documentDomain);115}116/**117 * Extracts host name from a URL.118 */119let extractHostFromURL = exports.extractHostFromURL = function extractHostFromURL(/**String*/ url)120{121 if (url && extractHostFromURL._lastURL == url)122 return extractHostFromURL._lastDomain;123 var host = "";124 try125 {126 host = new URI(url).host;127 }128 catch (e)129 {130 // Keep the empty string for invalid URIs.131 }132 extractHostFromURL._lastURL = url;133 extractHostFromURL._lastDomain = host;134 return host;135}136/**137 * Extracts host name from the URL of the given frame. If the URL don't have host138 * information (like about:blank or data: URLs) it falls back to the parent frame.139 */140let extractHostFromFrame = exports.extractHostFromFrame = function extractHostFromFrame(frame)141{142 var host = extractHostFromURL(frame.url);143 if (!host)144 {145 var parentFrame = frame.parent;146 if (parentFrame)147 return extractHostFromFrame(parentFrame);148 }149 return host;150}151/**152 * Strips the fragment from a URL.153 */154let stripFragmentFromURL = exports.stripFragmentFromURL = function stripFragmentFromURL(/**String*/ url)155{156 return url.replace(/#.*/, "");157}158/**159 * Parses URLs and provides an interface similar to nsIURI in Gecko, see160 * https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIURI.161 * TODO: Make sure the parsing actually works the same as nsStandardURL.162 * @constructor163 */164let URI = exports.URI = function URI(/**String*/ spec)165{166 this.spec = spec;167 this._schemeEnd = spec.indexOf(":");168 if (this._schemeEnd < 0)169 throw new Error("Invalid URI scheme");170 if (spec.substr(this._schemeEnd + 1, 2) != "//")171 throw new Error("Unexpected URI structure");172 this._hostPortStart = this._schemeEnd + 3;173 if (this._hostPortStart == spec.length)174 throw new Error("Empty URI host");175 this._hostPortEnd = spec.indexOf("/", this._hostPortStart);176 if (this._hostPortEnd < 0)177 {178 var queryIndex = spec.indexOf("?", this._hostPortStart);179 var fragmentIndex = spec.indexOf("#", this._hostPortStart);180 if (queryIndex >= 0 && fragmentIndex >= 0)181 this._hostPortEnd = Math.min(queryIndex, fragmentIndex);182 else if (queryIndex >= 0)183 this._hostPortEnd = queryIndex;184 else if (fragmentIndex >= 0)185 this._hostPortEnd = fragmentIndex;186 else187 this._hostPortEnd = spec.length;188 }189 var authEnd = spec.indexOf("@", this._hostPortStart);190 if (authEnd >= 0 && authEnd < this._hostPortEnd)191 this._hostPortStart = authEnd + 1;192 this._portStart = -1;193 this._hostEnd = spec.indexOf("]", this._hostPortStart + 1);194 if (spec[this._hostPortStart] == "[" && this._hostEnd >= 0 && this._hostEnd < this._hostPortEnd)195 {196 // The host is an IPv6 literal197 this._hostStart = this._hostPortStart + 1;198 if (spec[this._hostEnd + 1] == ":")199 this._portStart = this._hostEnd + 2;200 }201 else202 {203 this._hostStart = this._hostPortStart;204 this._hostEnd = spec.indexOf(":", this._hostStart);205 if (this._hostEnd >= 0 && this._hostEnd < this._hostPortEnd)206 this._portStart = this._hostEnd + 1;207 else208 this._hostEnd = this._hostPortEnd;209 }210}211URI.prototype =212{213 spec: null,214 get scheme()215 {216 return this.spec.substring(0, this._schemeEnd).toLowerCase();217 },218 get host()219 {220 return this.spec.substring(this._hostStart, this._hostEnd);221 },222 get asciiHost()223 {224 var host = this.host;225 if (/^[\x00-\x7F]+$/.test(host))226 return host;227 else228 return punycode.toASCII(host);229 },230 get hostPort()231 {232 return this.spec.substring(this._hostPortStart, this._hostPortEnd);233 },234 get port()235 {236 if (this._portStart < 0)237 return -1;238 else239 return parseInt(this.spec.substring(this._portStart, this._hostPortEnd), 10);240 },241 get path()242 {243 return this.spec.substring(this._hostPortEnd);244 },245 get prePath()246 {247 return this.spec.substring(0, this._hostPortEnd);248 }...

Full Screen

Full Screen

basedomain.js

Source:basedomain.js Github

copy

Full Screen

1/*!2 * Parts of original code from ipv6.js <https://github.com/beaugunderson/javascript-ipv6>3 * Copyright 2011 Beau Gunderson4 * Available under MIT license <http://mths.be/mit>5 */6const RE_V4 = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|0x[0-9a-f][0-9a-f]?|0[0-7]{3})\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|0x[0-9a-f][0-9a-f]?|0[0-7]{3})$/i;7const RE_V4_HEX = /^0x([0-9a-f]{8})$/i;8const RE_V4_NUMERIC = /^[0-9]+$/;9const RE_V4inV6 = /(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;10const RE_BAD_CHARACTERS = /([^0-9a-f:])/i;11const RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]$)/i;12function isIPv4(address)13{14 if (RE_V4.test(address))15 return true;16 if (RE_V4_HEX.test(address))17 return true;18 if (RE_V4_NUMERIC.test(address))19 return true;20 return false;21}22function isIPv6(address)23{24 var a4addon = 0;25 var address4 = address.match(RE_V4inV6);26 if (address4)27 {28 var temp4 = address4[0].split('.');29 for (var i = 0; i < 4; i++)30 {31 if (/^0[0-9]+/.test(temp4[i]))32 return false;33 }34 address = address.replace(RE_V4inV6, '');35 if (/[0-9]$/.test(address))36 return false;37 address = address + temp4.join(':');38 a4addon = 2;39 }40 if (RE_BAD_CHARACTERS.test(address))41 return false;42 if (RE_BAD_ADDRESS.test(address))43 return false;44 function count(string, substring)45 {46 return (string.length - string.replace(new RegExp(substring,"g"), '').length) / substring.length;47 }48 var halves = count(address, '::');49 if (halves == 1 && count(address, ':') <= 6 + 2 + a4addon)50 return true;51 if (halves == 0 && count(address, ':') == 7 + a4addon)52 return true;53 return false;54}55/**56 * Returns base domain for specified host based on Public Suffix List.57 */58function getBaseDomain(/**String*/ hostname) /**String*/59{60 console.log('basedomain getBaseDomain');61 // remove trailing dot(s)62 hostname = hostname.replace(/\.+$/, '');63 // return IP address untouched64 if (isIPv6(hostname) || isIPv4(hostname))65 return hostname;66 67 // decode punycode if exists68 if (hostname.indexOf('xn--') >= 0)69 {70 hostname = punycode.toUnicode(hostname);71 }72 // search through PSL73 var prevDomains = [];74 var curDomain = hostname;75 var nextDot = curDomain.indexOf('.');76 var tld = 0;77 78 while (true)79 {80 var suffix = publicSuffixes[curDomain];81 if (typeof(suffix) != 'undefined')82 {83 tld = suffix;84 break;85 }86 87 if (nextDot < 0)88 {89 tld = 1;90 break;91 }92 93 prevDomains.push(curDomain.substring(0,nextDot));94 curDomain = curDomain.substring(nextDot+1);95 nextDot = curDomain.indexOf('.');96 }97 98 while (tld > 0 && prevDomains.length > 0)99 {100 curDomain = prevDomains.pop() + '.' + curDomain;101 tld--;102 }103 104 return curDomain;105}106/**107 * Checks whether a request is third party for the given document, uses108 * information from the public suffix list to determine the effective domain109 * name for the document.110 */111function isThirdParty(/**String*/ requestHost, /**String*/ documentHost)112{113 // Remove trailing dots114 requestHost = requestHost.replace(/\.+$/, "");115 documentHost = documentHost.replace(/\.+$/, "");116 // Extract domain name - leave IP addresses unchanged, otherwise leave only base domain117 var documentDomain = getBaseDomain(documentHost);118 if (requestHost.length > documentDomain.length)119 return (requestHost.substr(requestHost.length - documentDomain.length - 1) != "." + documentDomain);120 else121 return (requestHost != documentDomain);122}123/**124 * Extracts host name from a URL.125 */126function extractHostFromURL(/**String*/ url)127{128 if (url && extractHostFromURL._lastURL == url)129 return extractHostFromURL._lastDomain;130 var host = "";131 try132 {133 host = new URI(url).host;134 }135 catch (e)136 {137 // Keep the empty string for invalid URIs.138 }139 extractHostFromURL._lastURL = url;140 extractHostFromURL._lastDomain = host;141 return host;142}143/**144 * Strips the fragment from a URL.145 */146function stripFragmentFromURL(/**String*/ url)147{148 if ( ! url) {149 console.log('stripFragmentFromURL no URL');150 var err = new Error('foo');151 throw err;152 }153 return url.replace(/#.*/, "");154}155/**156 * Parses URLs and provides an interface similar to nsIURI in Gecko, see157 * https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIURI.158 * TODO: Make sure the parsing actually works the same as nsStandardURL.159 * @constructor160 */161function URI(/**String*/ spec)162{163 this.spec = spec;164 this._schemeEnd = spec.indexOf(":");165 if (this._schemeEnd < 0)166 throw new Error("Invalid URI scheme");167 if (spec.substr(this._schemeEnd + 1, 2) != "//")168 throw new Error("Unexpected URI structure");169 this._hostPortStart = this._schemeEnd + 3;170 if (this._hostPortStart == spec.length)171 throw new Error("Empty URI host");172 173 this._hostPortEnd = spec.indexOf("/", this._hostPortStart);174 if (this._hostPortEnd < 0) 175 {176 var queryIndex = spec.indexOf("?", this._hostPortStart);177 var fragmentIndex = spec.indexOf("#", this._hostPortStart);178 if (queryIndex >= 0 && fragmentIndex >= 0)179 this._hostPortEnd = Math.min(queryIndex, fragmentIndex);180 else if (queryIndex >= 0)181 this._hostPortEnd = queryIndex;182 else if (fragmentIndex >= 0)183 this._hostPortEnd = fragmentIndex;184 else185 this._hostPortEnd = spec.length;186 }187 var authEnd = spec.indexOf("@", this._hostPortStart);188 if (authEnd >= 0 && authEnd < this._hostPortEnd)189 this._hostPortStart = authEnd + 1;190 this._portStart = -1;191 this._hostEnd = spec.indexOf("]", this._hostPortStart + 1);192 if (spec[this._hostPortStart] == "[" && this._hostEnd >= 0 && this._hostEnd < this._hostPortEnd)193 {194 // The host is an IPv6 literal195 this._hostStart = this._hostPortStart + 1;196 if (spec[this._hostEnd + 1] == ":")197 this._portStart = this._hostEnd + 2;198 }199 else200 {201 this._hostStart = this._hostPortStart;202 this._hostEnd = spec.indexOf(":", this._hostStart);203 if (this._hostEnd >= 0 && this._hostEnd < this._hostPortEnd)204 this._portStart = this._hostEnd + 1;205 else206 this._hostEnd = this._hostPortEnd;207 }208}209URI.prototype =210{211 spec: null,212 get scheme()213 {214 return this.spec.substring(0, this._schemeEnd).toLowerCase();215 },216 get host()217 {218 return this.spec.substring(this._hostStart, this._hostEnd);219 },220 get asciiHost()221 {222 var host = this.host;223 if (/^[\x00-\x7F]+$/.test(host))224 return host;225 else226 return punycode.toASCII(host);227 },228 get hostPort()229 {230 return this.spec.substring(this._hostPortStart, this._hostPortEnd);231 },232 get port()233 {234 if (this._portStart < 0)235 return -1;236 else237 return parseInt(this.spec.substring(this._portStart, this._hostPortEnd), 10);238 },239 get path()240 {241 return this.spec.substring(this._hostPortEnd);242 },243 get prePath()244 {245 return this.spec.substring(0, this._hostPortEnd);246 }...

Full Screen

Full Screen

whitelisting.js

Source:whitelisting.js Github

copy

Full Screen

1/*2 * This file is part of Adblock Cash <http://adblockcash.org/>,3 * (based on Adblock Plus <http://adblockplus.org/> by Eyeo GmbH)4 * Copyright (C) Adblock Cash5 *6 * Adblock Cash is free software: you can redistribute it and/or modify7 * it under the terms of the GNU General Public License version 3 as8 * published by the Free Software Foundation.9 *10 * Adblock Cash is distributed in the hope that it will be useful,11 * but WITHOUT ANY WARRANTY; without even the implied warranty of12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the13 * GNU General Public License for more details.14 *15 * You should have received a copy of the GNU General Public License16 * along with Adblock Cash. If not, see <http://www.gnu.org/licenses/>.17 */18let {defaultMatcher} = require("./matcher");19let {WhitelistFilter} = require("./filterClasses");20let {PageMap} = require("./pages");21let UriUtils = require("./utilsUri");22let pagesWithKey = new PageMap();23let isWhitelisted = exports.isWhitelisted = function(url, parentUrl, type, key)24{25 let filter = defaultMatcher.matchesAny(26 UriUtils.stripFragmentFromURL(url),27 type || "DOCUMENT",28 UriUtils.extractHostFromURL(parentUrl || url),29 false,30 key31 );32 return (filter instanceof WhitelistFilter ? filter : null);33};34let isFrameWhitelisted = exports.isFrameWhitelisted = function(page, frame, type)35{36 for (; frame != null; frame = frame.parent)37 {38 let key = getKey(page, frame);39 if (isWhitelisted(frame.url, (frame.parent || {}).url, type, key))40 return true;41 }42 return false;43};44let getKey = exports.getKey = function(page, frame)45{46 let urlsWithKey = pagesWithKey.get(page);47 if (!urlsWithKey)48 return null;49 for (; frame != null; frame = frame.parent)50 {51 if (urlsWithKey[frame.url])52 return urlsWithKey[frame.url];53 }54 return null;55}56let verifyKey = function(key, signature, url, docDomain)57{58 let uri = new UriUtils.URI(url);59 let params = [60 uri.path, // REQUEST_URI61 uri.asciiHost + (uri.port != -1 ? ":" + uri.port : ""), // HTTP_HOST62 window.navigator.userAgent // HTTP_USER_AGENT63 ];64 return verifySignature(key, signature, params.join("\0"));65};66let recordKey = function(page, url, key)67{68 let urlsWithKey = pagesWithKey.get(page);69 if (!urlsWithKey)70 {71 urlsWithKey = {__proto__: null};72 pagesWithKey.set(page, urlsWithKey);73 }74 urlsWithKey[url] = key;75};76let processKey = exports.processKey = function(token, page, frame)77{78 let url = UriUtils.stripFragmentFromURL(frame.url);79 let docDomain = UriUtils.extractHostFromURL((frame.parent || frame).url);80 if (token.indexOf("_") < 0)81 return;82 let [key, signature] = token.split("_", 2);83 key = key.replace(/=/g, "");84 if (verifyKey(key, signature, url, docDomain))85 recordKey(page, url, key);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { stripFragmentFromUrl } = require('@playwright/test/lib/utils/utils');2const { stripFragmentFromUrl } = require('@playwright/test/lib/utils/utils');3const urlWithoutFragment = stripFragmentFromUrl(url);4console.log(urlWithoutFragment);5const { test, expect } = require('@playwright/test');6test('My test', async ({ page }) => {7 const url = page.url();8});

Full Screen

Using AI Code Generation

copy

Full Screen

1const { stripFragmentFromUrl } = require('playwright/lib/utils/utils');2const { stripFragmentFromUrl } = require('playwright/lib/utils/utils');3const { stripFragmentFromUrl } = require('playwright/lib/utils/utils');4const { stripFragmentFromUrl } = require('playwright/lib/utils/utils');5const { stripFragmentFromUrl } = require('playwright/lib/utils/utils');6const { stripFragmentFromUrl } = require('playwright/lib/utils/utils');7const { stripFragmentFromUrl } = require('playwright/lib/utils/utils');8const { stripFragmentFromUrl } = require('playwright/lib/utils/utils');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { stripFragmentFromUrl } = require('playwright/lib/utils/utils');2console.log(stripFragmentFromUrl(url));3const { stripFragmentFromUrl } = require('playwright/lib/utils/utils');4console.log(stripFragmentFromUrl(url));5const { stripFragmentFromUrl } = require('playwright/lib/utils/utils');6console.log(stripFragmentFromUrl(url));7const { stripFragmentFromUrl } = require('playwright/lib/utils/utils');8console.log(stripFragmentFromUrl(url));9const { stripFragmentFromUrl } = require('playwright/lib/utils/utils');10console.log(stripFragmentFromUrl(url));11const { stripFragmentFromUrl } = require('playwright/lib/utils/utils');12console.log(stripFragmentFromUrl(url));13const { stripFragmentFromUrl } = require('playwright/lib/utils/utils');14console.log(stripFragmentFromUrl(url));15const { stripFragmentFromUrl } = require('playwright/lib/utils/utils');16console.log(stripFragmentFromUrl(url));17const { stripFragmentFromUrl } = require('playwright/lib/utils/utils');18console.log(stripFragmentFromUrl(url));

Full Screen

Using AI Code Generation

copy

Full Screen

1const { InternalUtils } = require('playwright/lib/utils/internalUtils');2const newUrl = InternalUtils.stripFragmentFromUrl(url);3console.log(newUrl);4const { InternalUtils } = require('playwright/lib/utils/internalUtils');5const newUrl = InternalUtils.stripFragmentFromUrl(url);6console.log(newUrl);7const { InternalUtils } = require('playwright/lib/utils/internalUtils');8const newUrl = InternalUtils.stripFragmentFromUrl(url);9console.log(newUrl);10const { InternalUtils } = require('playwright/lib/utils/internalUtils');11const newUrl = InternalUtils.stripFragmentFromUrl(url);12console.log(newUrl);13const { InternalUtils } = require('playwright/lib/utils/internalUtils');14const newUrl = InternalUtils.stripFragmentFromUrl(url);15console.log(newUrl);16const { InternalUtils } = require('playwright/lib/utils/internalUtils');17const newUrl = InternalUtils.stripFragmentFromUrl(url);18console.log(newUrl);19const { InternalUtils } = require('playwright/lib/utils/internalUtils');20const newUrl = InternalUtils.stripFragmentFromUrl(url);21console.log(newUrl);

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful