aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEinar Egilsson2009-05-09 20:46:48 +0000
committerEinar Egilsson2009-05-09 20:46:48 +0000
commit612e652d4a9feac5331c0262bbe6d234df3542e7 (patch)
treeb62a5821f9188454db189c033127263e3c48ffd5
parent385393f45b40ad4bb67ec245388e271cf51f4994 (diff)
1.7 start
git-svn-id: http://einaregilsson.googlecode.com/svn/mozilla/redirector/trunk@209 119bf307-c92d-0410-89bd-8f53e6181181
-rw-r--r--Redirector.csproj81
-rw-r--r--Redirector.sln20
-rw-r--r--chrome/content/overlay.js181
-rw-r--r--chrome/content/overlay.xul5
-rw-r--r--chrome/content/redirect.js24
-rw-r--r--chrome/content/redirect.xul6
-rw-r--r--chrome/content/redirectList.js50
-rw-r--r--chrome/content/redirectList.xul62
-rw-r--r--chrome/content/redirector.js312
-rw-r--r--chrome/content/redirector.twsbin783 -> 0 bytes
-rw-r--r--chrome/content/redirlib.js229
-rw-r--r--chrome/locale/en-US/redirect.dtd1
-rw-r--r--chrome/locale/en-US/redirector.properties2
-rw-r--r--components/redirector.js338
-rw-r--r--defaults/preferences/redirector.js6
-rw-r--r--install.rdf6
-rw-r--r--make.bat11
17 files changed, 568 insertions, 766 deletions
diff --git a/Redirector.csproj b/Redirector.csproj
new file mode 100644
index 0000000..493850f
--- /dev/null
+++ b/Redirector.csproj
@@ -0,0 +1,81 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+ <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+ <ProductVersion>9.0.21022</ProductVersion>
+ <SchemaVersion>2.0</SchemaVersion>
+ <ProjectGuid>{1C962CCA-74DC-4F72-8C83-7617F2275D1A}</ProjectGuid>
+ <OutputType>Exe</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>Redirector</RootNamespace>
+ <AssemblyName>Redirector</AssemblyName>
+ <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
+ <FileAlignment>512</FileAlignment>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+ <DebugSymbols>true</DebugSymbols>
+ <DebugType>full</DebugType>
+ <Optimize>false</Optimize>
+ <OutputPath>bin\Debug\</OutputPath>
+ <DefineConstants>DEBUG;TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+ <DebugType>pdbonly</DebugType>
+ <Optimize>true</Optimize>
+ <OutputPath>bin\Release\</OutputPath>
+ <DefineConstants>TRACE</DefineConstants>
+ <ErrorReport>prompt</ErrorReport>
+ <WarningLevel>4</WarningLevel>
+ </PropertyGroup>
+ <ItemGroup>
+ <Reference Include="System" />
+ <Reference Include="System.Core">
+ <RequiredTargetFramework>3.5</RequiredTargetFramework>
+ </Reference>
+ <Reference Include="System.Xml.Linq">
+ <RequiredTargetFramework>3.5</RequiredTargetFramework>
+ </Reference>
+ <Reference Include="System.Data.DataSetExtensions">
+ <RequiredTargetFramework>3.5</RequiredTargetFramework>
+ </Reference>
+ <Reference Include="System.Data" />
+ <Reference Include="System.Xml" />
+ </ItemGroup>
+ <ItemGroup>
+ <Content Include="chrome\content\help.html" />
+ <Content Include="chrome\content\overlay.js" />
+ <Content Include="chrome\content\redirect.js" />
+ <Content Include="chrome\content\redirectList.js" />
+ <Content Include="chrome\content\redirector.png" />
+ <Content Include="chrome\content\statusactive.PNG" />
+ <Content Include="chrome\content\statusinactive.PNG" />
+ <Content Include="chrome\skin\overlay.css" />
+ <Content Include="components\redirector.js" />
+ <Content Include="defaults\preferences\redirector.js" />
+ </ItemGroup>
+ <ItemGroup>
+ <None Include="chrome.manifest" />
+ <None Include="chrome\content\overlay.xul" />
+ <None Include="chrome\content\redirect.xul" />
+ <None Include="chrome\content\redirectList.xul" />
+ <None Include="chrome\locale\en-US\redirect.dtd" />
+ <None Include="chrome\locale\en-US\redirectList.dtd" />
+ <None Include="chrome\locale\en-US\redirector.dtd" />
+ <None Include="chrome\locale\en-US\redirector.properties" />
+ <None Include="install.rdf" />
+ </ItemGroup>
+ <ItemGroup>
+ <Folder Include="Properties\" />
+ </ItemGroup>
+ <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
+ <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
+ Other similar extension points exist, see Microsoft.Common.targets.
+ <Target Name="BeforeBuild">
+ </Target>
+ <Target Name="AfterBuild">
+ </Target>
+ -->
+</Project> \ No newline at end of file
diff --git a/Redirector.sln b/Redirector.sln
new file mode 100644
index 0000000..a61c861
--- /dev/null
+++ b/Redirector.sln
@@ -0,0 +1,20 @@
+
+Microsoft Visual Studio Solution File, Format Version 10.00
+# Visual Studio 2008
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Redirector", "Redirector.csproj", "{1C962CCA-74DC-4F72-8C83-7617F2275D1A}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {1C962CCA-74DC-4F72-8C83-7617F2275D1A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {1C962CCA-74DC-4F72-8C83-7617F2275D1A}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {1C962CCA-74DC-4F72-8C83-7617F2275D1A}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {1C962CCA-74DC-4F72-8C83-7617F2275D1A}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/chrome/content/overlay.js b/chrome/content/overlay.js
index f1d2241..46f69cc 100644
--- a/chrome/content/overlay.js
+++ b/chrome/content/overlay.js
@@ -1,5 +1,10 @@
//// $Id$
+var Redirector = Components.classes["@einaregilsson.com/redirector;1"].getService(Components.interfaces.nsISupports).wrappedJSObject;
+
+function $(id) {
+ return document.getElementById(id);
+}
var RedirectorOverlay = {
@@ -12,172 +17,35 @@ var RedirectorOverlay = {
try {
// initialization code
- RedirLib.initialize(this);
- RedirLib.debug("Initializing...");
+ Redirector.debug("Initializing...");
$('contentAreaContextMenu')
.addEventListener("popupshowing", function(e) { RedirectorOverlay.showContextMenu(e); }, false);
- this.ffversion = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULAppInfo).version;
-
- if (!RedirLib.getBoolPref('showContextMenu')) {
+ if (!Redirector.getBoolPref('showContextMenu')) {
$('redirector-context').hidden = true;
}
- if (!RedirLib.getBoolPref('showStatusBarIcon')) {
+ if (!Redirector.getBoolPref('showStatusBarIcon')) {
$('redirector-status').hidden = true;
}
- Redirector.init();
- this.overrideOnStateChange();
- this.overrideOpenNewWindowWith();
- this.overrideOpenNewTabWith();
this.strings = document.getElementById("redirector-strings");
- Redirector.strings = this.strings;
this.prefObserver.register();
this.setStatusBarImg();
- RedirLib.debug("Finished initialization");
+ Redirector.debug("Finished initialization");
this.initialized = true;
} catch(e) {
- //Don't use RedirLib because it's initialization might have failed.
if (this.strings) {
- alert(this.strings.getString("initError")._(this.name) + "\n\n" + e);
+ alert(this.strings.getFormattedString("initError", [this.name]) + "\n\n" + e);
} else {
alert(e);
}
}
},
- isVersion3 : function() {
- return this.ffversion.toString().charAt(0) == '3';
- },
-
- overrideOnStateChange : function() {
- var origOnStateChange = nsBrowserStatusHandler.prototype.onStateChange;
-
- nsBrowserStatusHandler.prototype.onStateChange = function(aWebProgress, aRequest, aStateFlags, aStatus) {
- if(aStateFlags & Ci.nsIWebProgressListener.STATE_START
- && aStateFlags| Ci.nsIWebProgressListener.STATE_IS_NETWORK
- && aStateFlags| Ci.nsIWebProgressListener.STATE_IS_REQUEST
- && aRequest && aWebProgress.DOMWindow) {
-
- //If it's not a GET request we'll always do a slow redirect so the web will continue
- //to work in the way you'd expect
- try {
- var oHttp = aRequest.QueryInterface(Ci.nsIHttpChannel);
- var method = oHttp.requestMethod;
-
- if (method != "GET") {
- origOnStateChange.apply(this, arguments);
- return;
- }
-
- } catch(ex) {
- origOnStateChange.apply(this, arguments);
- return;
- }
-
- var uri = aRequest.QueryInterface(Ci.nsIChannel).URI.spec;
-
- RedirLib.debug('Checking url %1 for instant redirect'._(uri));
- var redirectUrl = Redirector.getRedirectUrlForInstantRedirect(uri);
- if (redirectUrl.url && oHttp.notificationCallbacks) {
- const NS_BINDING_ABORTED = 0x804b0002;
- aRequest.cancel(NS_BINDING_ABORTED);
- var newStateFlags = Ci.nsIWebProgressListener.STATE_STOP | Ci.nsIWebProgressListener.STATE_IS_NETWORK | Ci.nsIWebProgressListener.STATE_IS_REQUEST;
- origOnStateChange.call(this, aWebProgress, aRequest, newStateFlags, "");
- var interfaceRequestor = oHttp.notificationCallbacks.QueryInterface(Ci.nsIInterfaceRequestor);
- var targetDoc = interfaceRequestor.getInterface(Ci.nsIDOMWindow).document;
- var gotoUrl = Redirector.makeAbsoluteUrl(uri, redirectUrl.url);
- Redirector.goto(gotoUrl, redirectUrl.pattern, uri, targetDoc);
- } else {
- origOnStateChange.apply(this, arguments);
- }
-
- } else {
- origOnStateChange.apply(this, arguments);
- }
-
- };
- },
-
- overrideOpenNewWindowWith: function() {
-
- window.__openNewWindowWith = window.openNewWindowWith;
-
-
- if (this.isVersion3()) {
-
- window.openNewWindowWith = function (aUrl, aDocument, aPostData, aAllowThirdPartyFixup, aReferrer) {
- var redirectUrl = Redirector.getRedirectUrlForInstantRedirect(aUrl);
- if (redirectUrl.url) {
- __openNewWindowWith(redirectUrl.url, aDocument, aPostData, aAllowThirdPartyFixup, aUrl);
- } else {
- __openNewWindowWith(aUrl, aDocument, aPostData, aAllowThirdPartyFixup, aReferrer);
- }
- };
-
- } else { //version 2.*
-
- window.openNewWindowWith = function (href, sourceURL, postData, allowThirdPartyFixup) {
- var redirectUrl = Redirector.getRedirectUrlForInstantRedirect(href);
- if (redirectUrl.url) {
- __openNewWindowWith(redirectUrl.url, href, postData, allowThirdPartyFixup);
- } else {
- __openNewWindowWith(href, sourceURL, postData, allowThirdPartyFixup);
- }
- };
- }
- },
-
-
- overrideOpenNewTabWith: function() {
-
- window.__openNewTabWith = window.openNewTabWith;
- if (this.isVersion3()) {
- window.openNewTabWith = function (aUrl, aDocument, aPostData, aEvent, aAllowThirdPartyFixup, aReferrer) {
- var redirectUrl = Redirector.getRedirectUrlForInstantRedirect(aUrl);
- if (redirectUrl.url) {
- __openNewTabWith(redirectUrl.url, aDocument, aPostData, aEvent, aAllowThirdPartyFixup, aUrl);
- } else {
- __openNewTabWith(aUrl, aDocument, aPostData, aEvent, aAllowThirdPartyFixup, aReferrer);
- }
-
- };
-
- } else { //version 2.*
- window.openNewTabWith = function (href, sourceURL, postData, event, allowThirdPartyFixup) {
- var redirectUrl = Redirector.getRedirectUrlForInstantRedirect(href);
- if (redirectUrl.url) {
- __openNewTabWith(redirectUrl.url, href, postData, event, allowThirdPartyFixup);
- } else {
- __openNewTabWith(href, sourceURL, postData, event, allowThirdPartyFixup);
- }
-
- };
-
- }
- },
-
-
- onDOMContentLoaded : function(event) {
- var redirect, link, links, url;
-
- if (event.target.toString().indexOf('HTMLDocument') == -1) {
- return;
- }
-
- url = event.target.location.href;
-
- RedirLib.debug('Processing url %1'._(url));
- Redirector.processUrl(url, event.target);
- },
-
-
onUnload : function(event) {
RedirectorOverlay.prefObserver.unregister();
- Redirector.prefObserver.unregister();
- //Clean up here
- RedirLib.debug("Finished cleanup");
+ Redirector.debug("Finished cleanup");
},
showContextMenu : function(event) {
@@ -202,24 +70,37 @@ var RedirectorOverlay = {
if (item.saved) {
Redirector.addRedirect(item);
}
-
},
onMenuItemCommand: function(event) {
- Redirector.openSettings();
+ this.openSettings();
},
toggleEnabled : function(event) {
- RedirLib.setBoolPref('enabled', !RedirLib.getBoolPref('enabled'));
+ Redirector.setEnabled(!Redirector.enabled);
},
+ openSettings : function() {
+ var windowName = "redirectorSettings";
+ var windowsMediator = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);
+ var win = windowsMediator.getMostRecentWindow(windowName);
+ if (win) {
+ win.focus();
+ } else {
+ window.openDialog("chrome://redirector/content/redirectList.xul",
+ windowName,
+ "chrome,dialog,resizable=no,centerscreen", this);
+ }
+
+ },
+
statusBarClick : function(event) {
var LEFT = 0, RIGHT = 2;
if (event.button == LEFT) {
RedirectorOverlay.toggleEnabled();
} else if (event.button == RIGHT) {
- Redirector.openSettings();
+ this.openSettings();
//$('redirector-status-popup').showPopup();
}
},
@@ -227,16 +108,16 @@ var RedirectorOverlay = {
setStatusBarImg : function() {
var statusImg = $('redirector-statusbar-img');
- if (RedirLib.getBoolPref('enabled')) {
+ if (Redirector.enabled) {
statusImg.src = 'chrome://redirector/content/statusactive.PNG'
statusImg.setAttribute('tooltiptext', this.strings.getString('enabledTooltip'));
- Redirector.enabled = true;
} else {
statusImg.src = 'chrome://redirector/content/statusinactive.PNG'
statusImg.setAttribute('tooltiptext', this.strings.getString('disabledTooltip'));
- Redirector.enabled = false;
}
},
+
+
prefObserver : {
diff --git a/chrome/content/overlay.xul b/chrome/content/overlay.xul
index 5bd827f..f46bfcf 100644
--- a/chrome/content/overlay.xul
+++ b/chrome/content/overlay.xul
@@ -4,9 +4,6 @@
<!DOCTYPE overlay SYSTEM "chrome://redirector/locale/redirector.dtd">
<overlay id="redirector-overlay"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
-
- <script src="redirlib.js"/>
- <script src="redirector.js"/>
<script src="overlay.js"/>
<stringbundleset id="stringbundleset">
@@ -28,7 +25,7 @@
<statusbarpanel id="redirector-status">
<!-- Put back in later
<menupopup id="redirector-status-popup" position="at_pointer">
- <menuitem label="&RedirectorManageRedirects.label;" accesskey="&RedirectorManageRedirects.accesskey;" oncommand="Redirector.openSettings();" />
+ <menuitem label="&RedirectorManageRedirects.label;" accesskey="&RedirectorManageRedirects.accesskey;" oncommand="RedirectorOverlay.openSettings();" />
<menuitem label="&RedirectorHelp.label;" accesskey="&RedirectorHelp.accesskey;" oncommand="Redirector.openHelp();" />
</menupopup>
-->
diff --git a/chrome/content/redirect.js b/chrome/content/redirect.js
index be6cb96..fe468f0 100644
--- a/chrome/content/redirect.js
+++ b/chrome/content/redirect.js
@@ -1,5 +1,13 @@
//// $Id$
+const kRedirectorWildcard = 'W';
+const kRedirectorRegex= 'R';
+var Redirector = Components.classes["@einaregilsson.com/redirector;1"].getService(Components.interfaces.nsISupports).wrappedJSObject;
+
+function $(id) {
+ return document.getElementById(id);
+}
+
var Redirect = {
onLoad : function() {
@@ -9,7 +17,6 @@ var Redirect = {
$('txtPattern').value = item.pattern;
$('txtRedirectUrl').value = item.redirectUrl || '';
$('txtExcludePattern').value = item.excludePattern || '';
- $('chkOnlyIfLinkExists').checked = item.onlyIfLinkExists || false;
$('txtPattern').focus();
this.strings = document.getElementById("redirector-strings");
@@ -32,15 +39,19 @@ var Redirect = {
item.exampleUrl =$('txtExampleUrl').value;
item.redirectUrl = $('txtRedirectUrl').value;
item.excludePattern = $('txtExcludePattern').value;
- item.onlyIfLinkExists = $('chkOnlyIfLinkExists').checked;
item.saved = true;
return true;
},
+ msgBox : function(title, text) {
+ Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
+ .getService(Components.interfaces.nsIPromptService)
+ .alert(window, title, text);
+ },
+
testPattern : function() {
var redirectUrl, pattern, excludePattern, example, extName, isExcluded;
-
redirectUrl = $('txtRedirectUrl').value;
pattern = $('txtPattern').value;
excludePattern = $('txtExcludePattern').value;
@@ -62,12 +73,11 @@ var Redirect = {
var isRedirectMatch = redirectUrl || (redirectUrl === '' && $('txtRedirectUrl').value === '');
if (isRedirectMatch && !isExcluded) {
- RedirLib.msgBox(extName, this.strings.getFormattedString('testPatternSuccess', [pattern, example, redirectUrl]));
+ this.msgBox(extName, this.strings.getFormattedString('testPatternSuccess', [pattern, example, redirectUrl]));
} else if (isExcluded) {
- RedirLib.msgBox(extName, this.strings.getFormattedString('testPatternExclude', [example, excludePattern]));
+ this.msgBox(extName, this.strings.getFormattedString('testPatternExclude', [example, excludePattern]));
} else {
- RedirLib.msgBox(extName, this.strings.getFormattedString('testPatternFailure', [pattern, example]));
+ this.msgBox(extName, this.strings.getFormattedString('testPatternFailure', [pattern, example]));
}
}
-
}; \ No newline at end of file
diff --git a/chrome/content/redirect.xul b/chrome/content/redirect.xul
index 83ed8df..e808fc4 100644
--- a/chrome/content/redirect.xul
+++ b/chrome/content/redirect.xul
@@ -10,8 +10,6 @@
xmlns:nc="http://home.netscape.com/NC-rdf#"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/x-javascript" src="redirlib.js"/>
- <script type="application/x-javascript" src="redirector.js"/>
<script type="application/x-javascript" src="redirect.js"/>
<stringbundleset id="stringbundleset">
<stringbundle id="redirector-strings" src="chrome://redirector/locale/redirector.properties"/>
@@ -43,10 +41,6 @@
<radio id="rdoRegex" label="&rdoRegex.label;" accesskey="&rdoRegex.accessKey;" taborder="6"/>
</radiogroup>
</row>
- <row>
- <text value="&chkOnlyIfLinkExists.label;" />
- <checkbox id="chkOnlyIfLinkExists" label="" taborder="7"/>
- </row>
</rows>
</grid>
diff --git a/chrome/content/redirectList.js b/chrome/content/redirectList.js
index 1e61067..c50583b 100644
--- a/chrome/content/redirectList.js
+++ b/chrome/content/redirectList.js
@@ -1,3 +1,10 @@
+
+var Redirector = Components.classes["@einaregilsson.com/redirector;1"].getService(Components.interfaces.nsISupports).wrappedJSObject;
+
+function $(id) {
+ return document.getElementById(id);
+}
+
var RedirectList = {
id : "redirector@einaregilsson.com",
@@ -26,11 +33,8 @@ var RedirectList = {
onLoad : function() {
try {
- RedirLib.initialize(this);
- Redirector.init();
-
this.lstRedirects = $('lstRedirects');
- this.lstRedirects.selType = 'single'; //For fx3
+ this.lstRedirects.selType = 'single';
this.template = document.getElementsByTagName('richlistitem')[0];
this.lstRedirects.removeChild(this.template);
this.btnDelete = $('btnDelete');
@@ -44,10 +48,41 @@ var RedirectList = {
close : function() {
window.close();
},
+
+ moveUp : function(){
+ if (this.lstRedirects.selectedIndex <= 0) {
+ return;
+ }
+ this.switchItems(this.lstRedirects.selectedIndex-1);
+ },
+ moveDown : function() {
+ if (this.lstRedirects.selectedIndex == Redirector.list.length-1) {
+ return;
+ }
+ this.switchItems(this.lstRedirects.selectedIndex);
+ },
+
+ switchItems : function(firstIndex) {
+ var first = Redirector.list[firstIndex];
+ var second = Redirector.list[firstIndex+1];
+ Redirector.list[firstIndex] = second;
+ Redirector.list[firstIndex+1] = first;
+ this.setListItemValues(this.lstRedirects.children[firstIndex+1], first);
+ this.setListItemValues(this.lstRedirects.children[firstIndex], second);
+ this.lstRedirects.selectedIndex -= 1;
+ Redirector.save();
+ },
+
+ setListItemValues : function(listItem, item){
+ listItem.getElementsByAttribute('name', 'dscrIncludePattern')[0].setAttribute('value', item.pattern);
+ listItem.getElementsByAttribute('name', 'dscrExcludePattern')[0].setAttribute('value', item.excludePattern);
+ listItem.getElementsByAttribute('name', 'dscrRedirectTo')[0].setAttribute('value', item.redirectUrl);
+ },
+
addRedirect : function() {
- var item = { pattern : '', exampleUrl : '', redirectUrl : '', onlyIfLinkExists : false, patternType : 'W'};
+ var item = { pattern : '', exampleUrl : '', redirectUrl : '', patternType : 'W'};
window.openDialog("chrome://redirector/content/redirect.xul",
"redirect",
@@ -75,12 +110,9 @@ var RedirectList = {
"chrome,dialog,modal,centerscreen", item);
if (item.saved) {
- listItem.getElementsByAttribute('name', 'dscrIncludePattern')[0].setAttribute('value', item.pattern);
- listItem.getElementsByAttribute('name', 'dscrExcludePattern')[0].setAttribute('value', item.excludePattern);
- listItem.getElementsByAttribute('name', 'dscrRedirectTo')[0].setAttribute('value', item.redirectUrl);
+ this.setListItemValues(listItem, item);
Redirector.save();
}
-
},
deleteRedirect : function() {
diff --git a/chrome/content/redirectList.xul b/chrome/content/redirectList.xul
index e3638b0..630c364 100644
--- a/chrome/content/redirectList.xul
+++ b/chrome/content/redirectList.xul
@@ -11,39 +11,39 @@
xmlns:nc="http://home.netscape.com/NC-rdf#"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
- <script type="application/x-javascript" src="redirlib.js"/>
- <script type="application/x-javascript" src="redirector.js"/>
<script type="application/x-javascript" src="redirectList.js"/>
<vbox>
- <richlistbox seltype="single" id="lstRedirects" style="margin-bottom:5px; border:solid 1px grey;" height="330px" ondblclick="RedirectList.editRedirect();" onselect="RedirectList.selectionChange();">
- <richlistitem style="border-bottom:dotted 1px grey;" selected="false">
- <grid>
- <cols>
- </cols>
- <rows>
- <row>
- <label style="font-weight:bold;" value="&colIncludePattern.label;:" />
- <description name="dscrIncludePattern" />
- </row>
- <row>
- <label style="font-weight:bold;" value="&colExcludePattern.label;:" />
- <description name="dscrExcludePattern" />
- </row>
- <row>
- <label style="font-weight:bold;" value="&colRedirectTo.label;:" />
- <description name="dscrRedirectTo" />
- </row>
- </rows>
- </grid>
- </richlistitem>
- </richlistbox>
- <hbox style="align:right;">
- <button id="btnAdd" onclick="RedirectList.addRedirect();" label="&btnAdd.label;" disabled="false" />
- <button id="btnEdit" onclick="RedirectList.editRedirect();" label="&btnEdit.label;" disabled="true" />
- <button id="btnDelete" onclick="RedirectList.deleteRedirect();" label="&btnDelete.label;" disabled="true" />
- <button id="btnClose" onclick="RedirectList.close();" label="&btnClose.label;"/>
- <button id="btnHelp" onclick="Redirector.openHelp();" label="&btnHelp.label;"/>
- </hbox>
+ <richlistbox seltype="single" id="lstRedirects" style="margin-bottom:5px; border:solid 1px grey;" height="330px" ondblclick="RedirectList.editRedirect();" onselect="RedirectList.selectionChange();">
+ <richlistitem style="border-bottom:dotted 1px grey;" selected="false">
+ <grid>
+ <cols>
+ </cols>
+ <rows>
+ <row>
+ <label style="font-weight:bold;" value="&colIncludePattern.label;:" />
+ <description name="dscrIncludePattern" />
+ </row>
+ <row>
+ <label style="font-weight:bold;" value="&colExcludePattern.label;:" />
+ <description name="dscrExcludePattern" />
+ </row>
+ <row>
+ <label style="font-weight:bold;" value="&colRedirectTo.label;:" />
+ <description name="dscrRedirectTo" />
+ </row>
+ </rows>
+ </grid>
+ </richlistitem>
+ </richlistbox>
+ <hbox style="align:right;">
+ <button id="btnAdd" onclick="RedirectList.addRedirect();" label="&btnAdd.label;" disabled="false" />
+ <button id="btnEdit" onclick="RedirectList.editRedirect();" label="&btnEdit.label;" disabled="true" />
+ <button id="btnDelete" onclick="RedirectList.deleteRedirect();" label="&btnDelete.label;" disabled="true" />
+ <button id="btnClose" onclick="RedirectList.close();" label="&btnClose.label;"/>
+ <button id="btnHelp" onclick="Redirector.openHelp();" label="&btnHelp.label;"/>
+ <button id="btnUp" onclick="RedirectList.moveUp();" label="UP" disabled="false" />
+ <button id="btnDown" onclick="RedirectList.moveDown();" label="Down" />
+ </hbox>
</vbox>
</window>
diff --git a/chrome/content/redirector.js b/chrome/content/redirector.js
deleted file mode 100644
index fb902f6..0000000
--- a/chrome/content/redirector.js
+++ /dev/null
@@ -1,312 +0,0 @@
-const kRedirectorWildcard = 'W';
-const kRedirectorRegex= 'R';
-
-var Redirector = {
-
- list : [],
-
- enabled : true,
-
- init : function() {
- this.load();
- this.prefObserver.register();
- },
-
- unload : function() {
- this.prefObserver.unregister();
- },
-
- save : function() {
- var r
- , tempList = [];
-
- for each (r in this.list) {
- tempList.push([r.exampleUrl, r.pattern, r.redirectUrl, r.onlyIfLinkExists, r.patternType, r.excludePattern]);
- }
- RedirLib.setCharPref('redirects', tempList.toSource());
- },
-
- load : function() {
- var tempList = eval(RedirLib.getCharPref('redirects'));
- var arr;
-
- this.list = [];
-
- for each (arr in tempList) {
- this.list.push({
- exampleUrl : arr[0],
- pattern : arr[1],
- redirectUrl : arr[2],
- onlyIfLinkExists : arr[3],
- patternType : arr[4],
- excludePattern : arr[5] || ''
- });
- }
-
- },
-
- addRedirect : function(redirect) {
- this.list.push(redirect);
- this.save();
- },
-
- deleteAt : function(index) {
- this.list.splice(index, 1);
- this.save();
- },
-
- getRedirectUrlForInstantRedirect : function(url) {
- var redirect, link, links, redirectUrl;
-
- if (this.enabled) {
-
- for each (redirect in this.list) {
-
- redirectUrl = this.getRedirectUrl(url, redirect);
- //Can't do fast redirect if it requires that link exists
- //we need the original page to verify that it exists.
- //Slow redirect will be done automatically.
- if (redirectUrl) {
- if (redirect.redirectUrl.startsWith('xpath:')) {
- RedirLib.msgBox(this.strings.getString('extensionName'), this.strings.getString('xpathDeprecated'));
- } else if (!redirect.onlyIfLinkExists) {
- RedirLib.debug('%1 matches %2, and it\'s not only if link exists. Can do instant redirect.'._(redirect.pattern, url));
- return { 'url' : redirectUrl, 'pattern' : redirect.pattern};
- } else {
- RedirLib.debug('%1 matches %2, but it\'s "only if link exists" and so has to be a slow redirect'._(redirect.pattern, url));
- }
- }
- }
- }
- return { 'url' : null, 'pattern' : null};
- },
-
- getRedirectUrl: function(url, redirect) {
-
- if (redirect.patternType == kRedirectorWildcard) {
- if (this.wildcardMatch(redirect.excludePattern, url, 'whatever')) {
- RedirLib.debug('%1 matches exclude pattern %2'._(url, redirect.excludePattern));
- return null;
- }
- return this.wildcardMatch(redirect.pattern, url, redirect.redirectUrl);
- } else if (redirect.patternType == kRedirectorRegex) {
- if (this.regexMatch(redirect.excludePattern, url, 'whatever')) {
- RedirLib.debug('%1 matches exclude pattern %2'._(url, redirect.excludePattern));
- return null;
- }
- return this.regexMatch(redirect.pattern, url, redirect.redirectUrl);
- }
- return null;
- },
-
- processUrl : function(url, doc) {
- var redirect, link, links, redirectUrl;
-
- if (!this.enabled) {
- return;
- }
-
- for each (redirect in this.list) {
-
- redirectUrl = this.getRedirectUrl(url, redirect);
-
- if (redirectUrl) {
- RedirLib.debug('%1 matches %2'._(redirect.pattern, url));
- if (redirect.onlyIfLinkExists) {
- links = window.content.document.getElementsByTagName('a');
-
- for each(link in links) {
-
- if (link.href && link.href.toString() == redirectUrl) {
- RedirLib.debug('Found a link for %1'._(redirectUrl));
- this.goto(redirectUrl, redirect.pattern, url, doc);
- return;
- }
- }
-
- RedirLib.debug('Did not find a link for %1'._(redirectUrl));
-
- } else {
- this.goto(redirectUrl, redirect.pattern, url, doc);
- }
- }
- }
- },
-
- makeAbsoluteUrl : function(currentUrl, relativeUrl) {
-
- if (relativeUrl.startsWith('http://') || relativeUrl.startsWith('https://')) {
- return relativeUrl;
- }
-
- var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
- RedirLib.debug(currentUrl);
- var uri = ioService.newURI(currentUrl, null, null);
-
- return uri.resolve(relativeUrl);
- },
-
- goto : function(redirectUrl, pattern, url, doc) {
-
- redirectUrl = this.makeAbsoluteUrl(url, redirectUrl);
-
- if (redirectUrl.startsWith('xpath:')) {
- //Do nothing, the instant redirect will have popped up a message
- } else if (redirectUrl == url) {
- RedirLib.msgBox(this.strings.getString('extensionName'), this.strings.getFormattedString('recursiveError', [pattern, redirectUrl]));
- } else {
- doc.location.href = redirectUrl;
- }
- },
-
- regexMatch : function(pattern, text, redirectUrl) {
-
- if (!pattern) {
- return null;
- }
- var strings, rx, match;
- try {
- rx = new RegExp(pattern, 'gi');
- match = rx.exec(text);
- } catch(e) {
- //HACK, need to make this better
- if (window.RedirectorOverlay) {
- strings = window.RedirectorOverlay.strings;
- } else if(window.Redirect) {
- strings = window.Redirect.strings;
- }
- RedirLib.msgBox(strings.getString('extensionName'), strings.getFormattedString('regexPatternError', [pattern, e.toString()]));
- return null;
- }
-
- var rxrepl;
-
- if (match) {
- for (var i = 1; i < match.length; i++) {
- rxrepl = new RegExp('\\$' + i, 'gi');
- redirectUrl = redirectUrl.replace(rxrepl, match[i]);
- }
- return redirectUrl;
- }
-
- return null;
-
- },
-
- wildcardMatch : function(pattern, text, redirectUrl) {
- var parts
- , part
- , i
- , pos
- , originalText
- , stars;
-
- if (!pattern) {
- return null;
- }
- parts = pattern.split('*');
-
- stars = [];
- originalText = text;
- var starStart = -1;
-
- for (i in parts) {
-
- part = parts[i];
-
- pos = text.lastIndexOf(part);
-
- if (pos == -1) {
- return null;
- }
-
- if (i == 0 && pos != 0) {
- return null;
- }
-
- if (i == parts.length -1 && i != "" && text.substr(text.length - part.length) != part) {
- return null;
-
- }
-
- if (i == 0) {
- //Do nothing, part will be added on next run
- } else if (i == parts.length-1 && parts[i] == '') {
- stars.push(text);
- } else {
- stars.push(text.substr(0, pos));
- }
-
- text = text.substr(pos + part.length);
- }
-
- for (var i = 1; i <= stars.length; i++) {
- redirectUrl = redirectUrl.replace(new RegExp('\\$' + i, 'gi'), stars[i-1]);
- }
-
- return redirectUrl;
- },
-
- openHelp : function() {
- var windowName = "redirectorHelp";
- var windowsMediator = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);
- var win;
- var iter = windowsMediator.getEnumerator(null);
- while (iter.hasMoreElements()) {
- win = iter.getNext();
- if (win.name == windowName) {
- win.focus();
- return;
- }
- }
- window.openDialog("chrome://redirector/content/help.html", windowName, "chrome,dialog,resizable=yes,location=0,toolbar=0,status=0,width=800px,height=600px,centerscreen", this);
- },
-
-
- openSettings : function() {
- var windowName = "redirectorSettings";
- var windowsMediator = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator);
- var win = windowsMediator.getMostRecentWindow(windowName);
- if (win) {
- win.focus();
- } else {
- window.openDialog("chrome://redirector/content/redirectList.xul",
- windowName,
- "chrome,dialog,resizable=no,centerscreen", this);
- }
-
- },
-
- prefObserver : {
-
- getService : function() {
- return Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefBranchInternal);
- },
-
- register: function() {
- this.getService().addObserver('extensions.redirector', this, false);
- },
-
- unregister: function() {
- this.getService().removeObserver('extensions.redirector', this);
- },
-
- observe : function(subject, topic, data) {
- if (topic != 'nsPref:changed') {
- return;
- }
-
- if (!window.Redirector) {
- return;
- }
-
- if (data == 'extensions.redirector.redirects') {
- Redirector.load();
- } else if (data == 'extensions.redirector.enabled') {
- Redirector.enabled = RedirLib.getBoolPref('enabled');
- }
- }
-
- }
-};
-
diff --git a/chrome/content/redirector.tws b/chrome/content/redirector.tws
deleted file mode 100644
index b69455f..0000000
--- a/chrome/content/redirector.tws
+++ /dev/null
Binary files differ
diff --git a/chrome/content/redirlib.js b/chrome/content/redirlib.js
deleted file mode 100644
index c25f0fb..0000000
--- a/chrome/content/redirlib.js
+++ /dev/null
@@ -1,229 +0,0 @@
-/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
- *
- * RedirLib - Utility functions for Firefox extensions
- *
- * Einar Egilsson
- *
- * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
-
-var RedirLib = {
-
- _debug : false,
- _ext : null,
- _cout : null,
- _prefBranch : null,
- version : 0.2,
-
- initialize : function(extension) {
- this._ext = extension;
- this._cout = Cc["@mozilla.org/consoleservice;1"].getService(Ci.nsIConsoleService);
- this._debug = true;
- this._initPrefs();
- },
-
- debug : function(str) {
- if (!this._ext) {
- return; //not initalized yet, _ext will be null
- }
-
- if (this._ext.prefs.debug) {
- this._cout.logStringMessage("%1: %2"._(this._ext.name, str));
- }
- },
-
-
- debugObject : function(name, obj) {
- s = name + ': ';
- for (x in obj)
- s += "\n\t%1 : %2"._(x, obj[x]);
- this.debug(s);
- },
-
- //Adds all prefs to a prefs object on the extension object, and registers a pref observer
- //for the branch.
- _initPrefs : function() {
-
- this._prefBranch = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService)
- .getBranch("extensions.%1."._(this._ext.id.split("@")[0]));
- this._ext.prefs = {};
-
- var list = this._prefBranch.getChildList("", {}).toString().split(",");
-
- for (i in list) {
-
- var name = list[i];
-
- var type = this._prefBranch.getPrefType(name);
-
- if (type == this._prefBranch.PREF_STRING) {
- this._ext.prefs[name] = this._prefBranch.getCharPref(name);
- } else if (type == this._prefBranch.PREF_INT) {
- this._ext.prefs[name] = this._prefBranch.getIntPref(name);
- } else if (type == this._prefBranch.PREF_BOOL) {
- this._ext.prefs[name] = this._prefBranch.getBoolPref(name);
- }
- }
- },
-
-
- getCharPref : function(branch) {
- return this._prefBranch.getCharPref(branch);
- },
-
- setCharPref : function(branch, value) {
- return this._prefBranch.setCharPref(branch, value);
- },
-
- setBoolPref : function(branch, value) {
- return this._prefBranch.setBoolPref(branch, value);
- },
-
- getBoolPref : function(branch) {
- return this._prefBranch.getBoolPref(branch);
- },
-
- getIntPref : function(branch) {
- return this._prefBranch.getIntPref(branch);
- },
-
- getExtensionFolder : function() {
- return Cc["@mozilla.org/extensions/manager;1"]
- .getService(Ci.nsIExtensionManager)
- .getInstallLocation(this._ext.id)
- .getItemLocation(this._ext.id);
-
- },
-
- getEnvVar : function(name) {
- return Cc["@mozilla.org/process/environment;1"]
- .getService(Ci.nsIEnvironment)
- .get(name);
-
- },
-
- setEnvVar : function(name, value) {
- return Cc["@mozilla.org/process/environment;1"]
- .getService(Ci.nsIEnvironment)
- .set(name, value);
-
- },
-
- msgBox : function(title, text) {
- Cc["@mozilla.org/embedcomp/prompt-service;1"]
- .getService(Ci.nsIPromptService)
- .alert(window, title, text);
- },
-
- //Converts a chrome path to a local file path. Note that the
- //file specified at the end of the chrome path does not have
- //to exist.
- chromeToPath : function(path) {
- var rv;
- var ios = Cc["@mozilla.org/network/io-service;1"].createInstance(Ci.nsIIOService);
- var uri = ios.newURI(path, 'UTF-8', null);
- var cr = Cc["@mozilla.org/chrome/chrome-registry;1"].createInstance(Ci.nsIChromeRegistry);
- return cr.convertChromeURL(uri);
- return decodeURI(rv.spec.substr("file:///".length).replace(/\//g, "\\"));
- },
-
- //Saves 'content' to file 'filepath'. Note that filepath needs to
- //be a real file path, not a chrome path.
- saveToFile : function(filepath, content) {
- var file = this.getFile(filepath);
-
- if (!file.exists()) {
- file.create(Ci.nsIFile.NORMAL_FILE_TYPE, 420);
- }
- var outputStream = Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
-
- outputStream.init( file, 0x04 | 0x08 | 0x20, 420, 0 );
- var result = outputStream.write( content, content.length );
- outputStream.close();
- },
-
- startProcess: function(filename, args) {
-
- var file = this.getFile(filename);
-
- args = args ? args : [];
-
- if (file.exists()) {
- var nsIProcess = Cc["@mozilla.org/process/util;1"].getService(Ci.nsIProcess);
- nsIProcess.init(file);
- nsIProcess.run(false, args, args.length);
- } else {
- throw Error("File '%1' does not exist!"._(filename));
- }
-
- },
-
- //Simulates a double click on the file in question
- launchFile : function(filepath) {
- var f = this.getFile(filepath);
- f.launch();
- },
-
-
- //Gets a local file reference, return the interface nsILocalFile.
- getFile : function(filepath) {
- var f = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
- f.initWithPath(filepath);
- return f;
- },
-
- //Returns all elements that match the query sent in. The root used
- //in the query is the window.content.document, so this will only
- //work for html content.
- xpath : function(doc, query) {
- return doc.evaluate(query, doc, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
- }
-
-
-
-};
-
-//************** Some prototype enhancements ************** //
-
-if (!window.Cc) window.Cc = Components.classes;
-if (!window.Ci) window.Ci = Components.interfaces;
-
-//Returns true if the string contains the substring str.
-String.prototype.contains = function (str) {
- return this.indexOf(str) != -1;
-};
-
-String.prototype.trim = function() {
- return this.replace(/^\s*|\s*$/gi, '');
-};
-
-String.prototype.startsWith = function(s) {
- return (this.length >= s.length && this.substr(0, s.length) == s);
-};
-
-String.prototype.endsWith = function(s) {
- return (this.length >= s.length && this.substr(this.length - s.length) == s);
-};
-
-//Inserts the arguments into the string. E.g. if
-//the string is "Hello %1" then "Hello %1"._('johnny')
-//would return "Hello johnny"
-String.prototype._ = function() {
- s = this;
- for (var i = 0; i < arguments.length; i++) {
- var nr = "%" + (i+1);
- var repl;
- if (arguments[i] == null) {
- repl = "null";
- } else if (arguments[i] == undefined) {
- repl = "undefined";
- } else {
- repl = arguments[i];
- }
- s = s.replace(new RegExp(nr, "g"), repl);
- }
- return s;
-};
-
-function $(id) {
- return document.getElementById(id);
-} \ No newline at end of file
diff --git a/chrome/locale/en-US/redirect.dtd b/chrome/locale/en-US/redirect.dtd
index ecf1d76..30968fb 100644
--- a/chrome/locale/en-US/redirect.dtd
+++ b/chrome/locale/en-US/redirect.dtd
@@ -4,7 +4,6 @@
<!ENTITY txtPattern.label "Include Pattern">
<!ENTITY txtExcludePattern.label "Exclude Pattern">
<!ENTITY txtRedirectUrl.label "Redirect to">
-<!ENTITY chkOnlyIfLinkExists.label "Only if link exists">
<!ENTITY btnTestPattern.label "Test pattern">
<!ENTITY rdoWildcard.label "Wildcard">
<!ENTITY rdoWildcard.accessKey "W">
diff --git a/chrome/locale/en-US/redirector.properties b/chrome/locale/en-US/redirector.properties
index 45207a1..bac0d6c 100644
--- a/chrome/locale/en-US/redirector.properties
+++ b/chrome/locale/en-US/redirector.properties
@@ -1,4 +1,4 @@
-initError=Failed to initialize %1.
+initError=Failed to initialize %S.
extensions.redirector@einaregilsson.com.description=Automatically redirects to user-defined urls on certain pages
extensionName=Redirector
addCurrentUrl=Add current url to Redirector
diff --git a/components/redirector.js b/components/redirector.js
new file mode 100644
index 0000000..4c962ee
--- /dev/null
+++ b/components/redirector.js
@@ -0,0 +1,338 @@
+
+const CSSB_CONTRACTID = "@einaregilsson.com/redirector;1";
+const CSSB_CID = Components.ID("{b7a7a54f-0581-47ff-b086-d6920cb7a3f7}");
+
+const Cc = Components.classes;
+const Ci = Components.interfaces;
+const Cr = Components.results;
+const kRedirectorWildcard = 'W';
+const kRedirectorRegex= 'R';
+
+const nsIContentPolicy = Ci.nsIContentPolicy;
+
+function RedirectorPolicy() {
+ this.prefBranch = Cc["@mozilla.org/preferences-service;1"].getService(Ci.nsIPrefService).getBranch("extensions.redirector.");
+
+ //Check if we need to update existing redirects
+
+ var data = this.prefBranch.getCharPref('redirects');
+ var version = this.prefBranch.getCharPref('version');
+ this.debugEnabled = this.prefBranch.getBoolPref('debug');
+ this.enabled = this.prefBranch.getBoolPref('enabled');
+ this.loadStrings();
+ //Here update checks are handled
+ if (version == 'undefined') { //Either a fresh install of Redirector, or first time install of v2.0
+ if (data) { //There is some data in redirects, we are upgrading from a previous version, need to upgrade data
+ var tempList = eval(data);
+ var arr;
+ var newArr = []
+ for each (arr in tempList) {
+ if (arr.length == 5) {
+ arr.push(''); //For those that don't have an exclude pattern. Backwards compatibility is a bitch!
+ }
+ arr.splice(3,1); //Remove the "only if link exists" data
+ newArr.push(arr.join(',,,'));
+ }
+ this.prefBranch.setCharPref('redirects', newArr.join(':::'));
+ }
+ this.prefBranch.setCharPref('version', '2.0');
+ }
+ //Update finished
+
+ //Now get from the new format
+ data = this.prefBranch.getCharPref('redirects');
+ var arr;
+ this.list = [];
+ for each (redirectString in data.split(':::')) {
+ arr = redirectString.split(',,,');
+ this.list.push({
+ exampleUrl : arr[0],
+ pattern : arr[1],
+ redirectUrl : arr[2],
+ patternType : arr[3],
+ excludePattern : arr[4]
+ });
+ }
+}
+
+RedirectorPolicy.prototype = {
+ prefBranch : null,
+ list : null,
+ strings : null,
+
+ loadStrings : function() {
+ var src = 'chrome://redirector/locale/redirector.properties';
+ var localeService = Cc["@mozilla.org/intl/nslocaleservice;1"].getService(Ci.nsILocaleService);
+ var appLocale = localeService.getApplicationLocale();
+ var stringBundleService = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService);
+ this.strings = stringBundleService.createBundle(src, appLocale);
+ },
+
+ debug : function(msg) {
+ if (this.debugEnabled) {
+ dump("REDIRECTOR: " + msg + "\n");
+ }
+ },
+
+ // nsIContentPolicy interface implementation
+ shouldLoad: function(contentType, contentLocation, requestOrigin, aContext, mimeTypeGuess, extra) {
+ if (!this.enabled) {
+ return nsIContentPolicy.ACCEPT;
+ }
+ if (contentLocation.scheme != "http" && contentLocation.scheme != "https") {
+ return nsIContentPolicy.ACCEPT;
+ }
+
+ if (contentType != nsIContentPolicy.TYPE_DOCUMENT && contentType != nsIContentPolicy.TYPE_SUBDOCUMENT) {
+ return nsIContentPolicy.ACCEPT;
+ }
+
+ if (!aContext || !aContext.loadURI) {
+ return nsIContentPolicy.ACCEPT;
+ }
+ this.debug("CHECK: " + contentLocation.spec + "\n");
+
+ var url = contentLocation.spec;
+
+ for each (var redirect in this.list) {
+ var redirectUrl = this.getRedirectUrl(url, redirect);
+ if (redirectUrl) {
+ redirectUrl = this.makeAbsoluteUrl(url, redirectUrl);
+ aContext.loadURI(redirectUrl, requestOrigin, null);
+ return nsIContentPolicy.REJECT_REQUEST;
+ }
+ }
+ return nsIContentPolicy.ACCEPT;
+ },
+
+ shouldProcess: function(contentType, contentLocation, requestOrigin, insecNode, mimeType, extra) {
+ return nsIContentPolicy.ACCEPT;
+ },
+
+ setEnabled : function(val) {
+ this.enabled = val;
+ this.prefBranch.setBoolPref('enabled', val);
+ },
+
+ addRedirect : function(redirect) {
+ this.list.push(redirect);
+ this.save();
+ },
+
+ deleteAt : function(index) {
+ this.list.splice(index, 1);
+ this.save();
+ },
+
+ save : function() {
+ var r
+ , tempList = [];
+
+ for each (r in this.list) {
+ tempList.push([r.exampleUrl, r.pattern, r.redirectUrl, r.patternType, r.excludePattern].join(',,,'));
+ }
+ this.prefBranch.setCharPref('redirects', tempList.join(':::'));
+ },
+
+ getBoolPref : function(name) {
+ return this.prefBranch.getBoolPref(name);
+ },
+
+ regexMatch : function(pattern, text, redirectUrl) {
+
+ if (!pattern) {
+ return null;
+ }
+ var strings, rx, match;
+ try {
+ rx = new RegExp(pattern, 'gi');
+ match = rx.exec(text);
+ } catch(e) {
+ this.msgBox(this.strings.GetStringFromName('extensionName'), this.strings.formatStringFromName('regexPatternError', [pattern, e.toString()],2));
+ return null;
+ }
+
+ var rxrepl;
+
+ if (match) {
+ for (var i = 1; i < match.length; i++) {
+ rxrepl = new RegExp('\\$' + i, 'gi');
+ redirectUrl = redirectUrl.replace(rxrepl, match[i]);
+ }
+ return redirectUrl;
+ }
+
+ return null;
+
+ },
+
+ msgBox : function(title, text) {
+ Cc["@mozilla.org/embedcomp/prompt-service;1"]
+ .getService(Ci.nsIPromptService)
+ .alert(null, title, text);
+ },
+
+ getRedirectUrl: function(url, redirect) {
+
+ if (redirect.patternType == kRedirectorWildcard) {
+ if (this.wildcardMatch(redirect.excludePattern, url, 'whatever')) {
+ this.debug(url + ' matches exclude pattern ' + redirect.excludePattern);
+ return null;
+ }
+ return this.wildcardMatch(redirect.pattern, url, redirect.redirectUrl);
+ } else if (redirect.patternType == kRedirectorRegex) {
+ if (this.regexMatch(redirect.excludePattern, url, 'whatever')) {
+ this.debug(url + ' matches exclude pattern ' + redirect.excludePattern);
+ return null;
+ }
+ return this.regexMatch(redirect.pattern, url, redirect.redirectUrl);
+ }
+ return null;
+ },
+
+ makeAbsoluteUrl : function(currentUrl, relativeUrl) {
+
+ if (relativeUrl.match(/https?:/)) {
+ return relativeUrl;
+ }
+
+ var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
+ //this.debug(currentUrl);
+ var uri = ioService.newURI(currentUrl, null, null);
+
+ return uri.resolve(relativeUrl);
+ },
+
+ wildcardMatch : function(pattern, text, redirectUrl) {
+ var parts
+ , part
+ , i
+ , pos
+ , originalText
+ , stars;
+
+ if (!pattern) {
+ return null;
+ }
+ parts = pattern.split('*');
+
+ stars = [];
+ originalText = text;
+ var starStart = -1;
+
+ for (i in parts) {
+
+ part = parts[i];
+
+ pos = text.lastIndexOf(part);
+
+ if (pos == -1) {
+ return null;
+ }
+
+ if (i == 0 && pos != 0) {
+ return null;
+ }
+
+ if (i == parts.length -1 && i != "" && text.substr(text.length - part.length) != part) {
+ return null;
+
+ }
+
+ if (i == 0) {
+ //Do nothing, part will be added on next run
+ } else if (i == parts.length-1 && parts[i] == '') {
+ stars.push(text);
+ } else {
+ stars.push(text.substr(0, pos));
+ }
+
+ text = text.substr(pos + part.length);
+ }
+
+ for (var i = 1; i <= stars.length; i++) {
+ redirectUrl = redirectUrl.replace(new RegExp('\\$' + i, 'gi'), stars[i-1]);
+ }
+
+ return redirectUrl;
+ }
+};
+
+/*
+ * Factory object
+ */
+
+var redirectorInstance = null;
+
+const factory = {
+ // nsIFactory interface implementation
+ createInstance: function(outer, iid) {
+ if (outer != null) {
+ Components.returnCode = Cr.NS_ERROR_NO_AGGREGATION;
+ return null;
+ }
+
+ if (!iid.equals(Ci.nsIContentPolicy) &&
+ !iid.equals(Ci.nsISupports)) {
+ Components.returnCode = Cr.NS_ERROR_NO_INTERFACE;
+ return null;
+ }
+
+ if(!redirectorInstance) {
+ redirectorInstance = new RedirectorPolicy();
+ redirectorInstance.wrappedJSObject = redirectorInstance;
+ }
+
+ return redirectorInstance;
+ },
+
+ // nsISupports interface implementation
+ QueryInterface: function(iid) {
+ if (iid.equals(Ci.nsISupports) ||
+ iid.equals(Ci.nsIModule) ||
+ iid.equals(Ci.nsIFactory)) {
+ return this;
+ }
+ Components.returnCode = Cr.NS_ERROR_NO_INTERFACE;
+ return null;
+ }
+}
+
+
+/*
+ * Module object
+ */
+const module = {
+ registerSelf: function(compMgr, fileSpec, location, type) {
+ compMgr = compMgr.QueryInterface(Ci.nsIComponentRegistrar);
+ compMgr.registerFactoryLocation(CSSB_CID,
+ "Redirector content policy",
+ CSSB_CONTRACTID,
+ fileSpec, location, type);
+
+ var catman = Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager);
+ catman.addCategoryEntry("content-policy", CSSB_CONTRACTID, CSSB_CONTRACTID, true, true);
+ },
+
+ unregisterSelf: function(compMgr, fileSpec, location) {
+ compMgr.QueryInterface(Ci.nsIComponentRegistrar).unregisterFactoryLocation(CSSB_CID, fileSpec);
+ Cc["@mozilla.org/categorymanager;1"].getService(Ci.nsICategoryManager).deleteCategoryEntry("content-policy", CSSB_CONTRACTID, true);
+ },
+
+ getClassObject: function(compMgr, cid, iid) {
+ if (cid.equals(CSSB_CID)) {
+ return factory;
+ }
+
+ Components.returnCode = Cr.NS_ERROR_NOT_REGISTERED;
+ return null;
+ },
+
+ canUnload: function(compMgr) {
+ return true;
+ }
+};
+
+function NSGetModule(comMgr, fileSpec) {
+ return module;
+} \ No newline at end of file
diff --git a/defaults/preferences/redirector.js b/defaults/preferences/redirector.js
index 6fb628b..50a9511 100644
--- a/defaults/preferences/redirector.js
+++ b/defaults/preferences/redirector.js
@@ -4,7 +4,9 @@ pref("extensions.redirector.debug", false);
pref("extensions.redirector.enabled", true);
pref("extensions.redirector.showContextMenu", true);
pref("extensions.redirector.showStatusBarIcon", true);
-pref("extensions.redirector.redirects", '[]');
+pref("extensions.redirector.redirects", '');
+pref("extensions.redirector.version", 'undefined');
// See http://kb.mozillazine.org/Localize_extension_descriptions
-pref("extensions.redirector@einaregilsson.com.description", "chrome://redirector/locale/redirector.properties"); \ No newline at end of file
+pref("extensions.redirector@einaregilsson.com.description", "chrome://redirector/locale/redirector.properties");
+
diff --git a/install.rdf b/install.rdf
index 14826aa..cabc2ac 100644
--- a/install.rdf
+++ b/install.rdf
@@ -5,7 +5,7 @@
<Description about="urn:mozilla:install-manifest">
<em:id>redirector@einaregilsson.com</em:id>
<em:name>Redirector</em:name>
- <em:version>1.6</em:version>
+ <em:version>1.7</em:version>
<em:creator>Einar Egilsson</em:creator>
<em:description>Automatically redirects to user-defined urls on certain pages</em:description>
<em:homepageURL>http://tech.einaregilsson.com/projects/redirector/</em:homepageURL>
@@ -14,8 +14,8 @@
<em:targetApplication>
<Description>
<em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id> <!-- firefox -->
- <em:minVersion>2.0</em:minVersion>
- <em:maxVersion>3.0.*</em:maxVersion>
+ <em:minVersion>3.0</em:minVersion>
+ <em:maxVersion>3.5b4</em:maxVersion>
</Description>
</em:targetApplication>
</Description>
diff --git a/make.bat b/make.bat
deleted file mode 100644
index e4868af..0000000
--- a/make.bat
+++ /dev/null
@@ -1,11 +0,0 @@
-::
-:: Build script for extension
-::
-:: Einar Þór Egilsson - 26.10.2006
-::
-
-SET EXT=Redirector.xpi
-
-IF NOT EXIST build md build
-IF EXIST build\%EXT% del build\%EXT%
-zip -r build\%EXT% *.* -x build* *.py *.bat \ No newline at end of file