zotero/components/zotero-service.js

482 lines
15 KiB
JavaScript
Raw Normal View History

/*
***** BEGIN LICENSE BLOCK *****
2010-12-26 19:05:52 +00:00
Copyright © 2009 Center for History and New Media
George Mason University, Fairfax, Virginia, USA
http://zotero.org
This file is part of Zotero.
Zotero is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Zotero is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Zotero. If not, see <http://www.gnu.org/licenses/>.
Based on nsChromeExtensionHandler example code by Ed Anuff at
http://kb.mozillazine.org/Dev_:_Extending_the_Chrome_Protocol
***** END LICENSE BLOCK *****
*/
const Cc = Components.classes;
const Ci = Components.interfaces;
/** XPCOM files to be loaded for all modes **/
const xpcomFilesAll = [
'zotero',
'date',
'debug',
'error',
'file',
'http',
'mimeTypeHandler',
'openurl',
'ipc',
'progressWindow',
'translation/translate',
'translation/translate_firefox',
'translation/tlds',
'utilities',
'isbn',
'utilities_internal',
'utilities_translate'
];
/** XPCOM files to be loaded only for local translation and DB access **/
const xpcomFilesLocal = [
'libraryTreeView',
'collectionTreeView',
'annotate',
'attachments',
'cite',
2011-07-19 03:52:02 +00:00
'cookieSandbox',
'data_access',
'data/dataObjects',
'data/cachedTypes',
'data/item',
'data/items',
'data/collection',
'data/collections',
'data/creator',
'data/creators',
2.0b3 megacommit - Support for group libraries - General support for multiple libraries of different types - Streamlined sync support - Using solely libraryID and key rather than itemID, and removed all itemID-changing code - Combined two requests for increased performance and decreased server load - Added warning on user account change - Provide explicit error message on SSL failure - Removed snapshot and link toolbar buttons and changed browser context menu options and drags to create parent items + snapshots - Closes #786, Add numPages field - Fixes #1063, Duplicate item with tags broken in Sync Preview - Added better purging of deleted tags - Added local user key before first sync - Add clientDateModified to all objects for more flexibility in syncing - Added new triples-based Relation object type, currently used to store links between items copied between local and group libraries - Updated zotero.org translator for groups - Additional trigger-based consistency checks - Fixed broken URL drag in Firefox 3.5 - Disabled zeroconf menu option (no longer functional) Developer-specific changes: - Overhauled data layer - Data object constructors no longer take arguments (return to 1.0-like API) - Existing objects can be retrieved by setting id or library/key properties - id/library/key must be set for new objects before other fields - New methods: - ZoteroPane.getSelectedLibraryID() - ZoteroPane.getSelectedGroup(asID) - ZoteroPane.addItemFromDocument(doc, itemType, saveSnapshot) - ZoteroPane.addItemFromURL(url, itemType) - ZoteroPane.canEdit() - Zotero.CollectionTreeView.selectLibrary(libraryID) - New Zotero.URI methods - Changed methods - Many data object methods now take a libraryID - ZoteroPane.addAttachmentFromPage(link, itemID) - Removed saveItem and saveAttachments parameters from Zotero.Translate constructor - translate() now takes a libraryID, null for local library, or false to not save items (previously on constructor) - saveAttachments is now a translate() parameter - Zotero.flattenArguments() better handles passed objects - Zotero.File.getFileHash() (not currently used)
2009-05-14 18:23:40 +00:00
'data/group',
'data/groups',
'data/itemFields',
'data/notes',
2.0b3 megacommit - Support for group libraries - General support for multiple libraries of different types - Streamlined sync support - Using solely libraryID and key rather than itemID, and removed all itemID-changing code - Combined two requests for increased performance and decreased server load - Added warning on user account change - Provide explicit error message on SSL failure - Removed snapshot and link toolbar buttons and changed browser context menu options and drags to create parent items + snapshots - Closes #786, Add numPages field - Fixes #1063, Duplicate item with tags broken in Sync Preview - Added better purging of deleted tags - Added local user key before first sync - Add clientDateModified to all objects for more flexibility in syncing - Added new triples-based Relation object type, currently used to store links between items copied between local and group libraries - Updated zotero.org translator for groups - Additional trigger-based consistency checks - Fixed broken URL drag in Firefox 3.5 - Disabled zeroconf menu option (no longer functional) Developer-specific changes: - Overhauled data layer - Data object constructors no longer take arguments (return to 1.0-like API) - Existing objects can be retrieved by setting id or library/key properties - id/library/key must be set for new objects before other fields - New methods: - ZoteroPane.getSelectedLibraryID() - ZoteroPane.getSelectedGroup(asID) - ZoteroPane.addItemFromDocument(doc, itemType, saveSnapshot) - ZoteroPane.addItemFromURL(url, itemType) - ZoteroPane.canEdit() - Zotero.CollectionTreeView.selectLibrary(libraryID) - New Zotero.URI methods - Changed methods - Many data object methods now take a libraryID - ZoteroPane.addAttachmentFromPage(link, itemID) - Removed saveItem and saveAttachments parameters from Zotero.Translate constructor - translate() now takes a libraryID, null for local library, or false to not save items (previously on constructor) - saveAttachments is now a translate() parameter - Zotero.flattenArguments() better handles passed objects - Zotero.File.getFileHash() (not currently used)
2009-05-14 18:23:40 +00:00
'data/libraries',
'data/relation',
'data/relations',
'data/tag',
'data/tags',
'db',
Duplicate detection: - Adds a per-library "Duplicate Items" virtual search to the source list -- shows up by default for "My Library" but can be added to and removed from all libraries - Current matching algorithm is very basic: finds exact title matches (after normalizing case/diacritics/punctuation/spacing) and DOI/ISBN matches (untested) - In duplicates view, sets are selected automatically; in other views, duplicate items can be selected manually and the merge interface can be brought up with "Merge Items" in the context menu - Can select a master item and individual fields to merge from other versions - Word processor integration code will automatically find mapped replacements and update documents with new item keys Possible future improvements: - Improved detection algorithms - UI tweaks - Currently if any items differ, all available versions will be shown as master item options, even if only one item is different; probably the earliest equivalent item should be shown for each distinct version - Caching of results for performance - Confidence scale - Creator version selection (currently the creators from the chosen master item are kept) - Merging of matching child items - Better sorting of duplicates if not clustered together by the selected sort column - Relation path compression when merging items that are already mapped to previously removed duplicates Other changes in this commit: - Don't show Trash in word processor integration windows - Consider items in trash to be missing in word processor documents - Selection of special views (Trash, Unfiled, Duplicates) is now restored properly in new windows - Disabled field transform context menu when item isn't editable - Left/right arrow now expands/collapses all selected items instead of just the last-selected row - Relation deletions are now synced - The same items row is now reselected after item deletion - (dev) Zotero.Item.getNotes(), Zotero.Item.getAttachments(), and Zotero.Item.getTags() now return empty arrays rather than FALSE if no matches -- tests on those return values in third-party code will need to be changed - (dev) New function Zotero.Utilities.removeDiacritics(str, lowercaseOnly) -- could be used to generate ASCII BibTeX keys - (dev) New 'tempTable' search condition can take a table to join against -- useful for implementing virtual source lists - (dev) Significant UI code cleanup - (dev) Moved all item pane content into itemPane.xul - Probably various other things Needless to say, this needs testing.
2011-07-22 21:24:38 +00:00
'duplicates',
'fulltext',
'id',
'integration',
'itemTreeView',
'locateManager',
'mime',
'notifier',
'proxy',
'quickCopy',
'report',
'schema',
'search',
'server',
'style',
'sync',
'storage',
'storage/streamListener',
'storage/queueManager',
'storage/queue',
'storage/request',
'storage/mode',
Zotero File Storage megacommit - Group file sync via Zotero File Storage - Split file syncing into separate modules for ZFS and WebDAV - Dragging items between libraries copies child notes, snapshots/files, and links based on checkboxes for each (enabled by default) in the Zotero preferences - Sync errors now trigger an exclamation/error icon separate from the sync icon, with a popup window displaying the error and an option to report it - Various errors that could cause perpetual sync icon spinning now stop the sync properly - Zotero.Utilities.md5(str) is now md5(strOrFile, base64) - doPost(), doHead(), and retrieveSource() now takes a headers parameter instead of requestContentType - doHead() can now accept an nsIURI (with login credentials), is a background request, and isn't cached - When library access or file writing access is denied during sync, display a warning and then reset local group to server version - Perform additional steps (e.g., removing local groups) when switching sync users to prevent errors - Compare hash as well as mod time when checking for modified local files - Don't trigger notifications when removing groups from the client - Clear relation links to items in removed groups - Zotero.Item.attachmentHash property to get file MD5 - importFromFile() now takes libraryID as a third parameter - Zotero.Attachments.getNumFiles() returns the number of files in the attachment directory - Zotero.Attachments.copyAttachmentToLibrary() copies an attachment item, including files, to another library - Removed Zotero.File.getFileHash() in favor of updated Zotero.Utilities.md5() - Zotero.File.copyDirectory(dir, newDir) copies all files from dir into newDir - Preferences shuffling: OpenURL to Advanced, import/export character set options to Export, "Include URLs of paper articles in references" to Styles - Other stuff I don't remember Suffice it to say, this could use testing.
2009-09-13 07:23:29 +00:00
'storage/zfs',
'storage/webdav',
'syncedSettings',
'timeline',
2.0b3 megacommit - Support for group libraries - General support for multiple libraries of different types - Streamlined sync support - Using solely libraryID and key rather than itemID, and removed all itemID-changing code - Combined two requests for increased performance and decreased server load - Added warning on user account change - Provide explicit error message on SSL failure - Removed snapshot and link toolbar buttons and changed browser context menu options and drags to create parent items + snapshots - Closes #786, Add numPages field - Fixes #1063, Duplicate item with tags broken in Sync Preview - Added better purging of deleted tags - Added local user key before first sync - Add clientDateModified to all objects for more flexibility in syncing - Added new triples-based Relation object type, currently used to store links between items copied between local and group libraries - Updated zotero.org translator for groups - Additional trigger-based consistency checks - Fixed broken URL drag in Firefox 3.5 - Disabled zeroconf menu option (no longer functional) Developer-specific changes: - Overhauled data layer - Data object constructors no longer take arguments (return to 1.0-like API) - Existing objects can be retrieved by setting id or library/key properties - id/library/key must be set for new objects before other fields - New methods: - ZoteroPane.getSelectedLibraryID() - ZoteroPane.getSelectedGroup(asID) - ZoteroPane.addItemFromDocument(doc, itemType, saveSnapshot) - ZoteroPane.addItemFromURL(url, itemType) - ZoteroPane.canEdit() - Zotero.CollectionTreeView.selectLibrary(libraryID) - New Zotero.URI methods - Changed methods - Many data object methods now take a libraryID - ZoteroPane.addAttachmentFromPage(link, itemID) - Removed saveItem and saveAttachments parameters from Zotero.Translate constructor - translate() now takes a libraryID, null for local library, or false to not save items (previously on constructor) - saveAttachments is now a translate() parameter - Zotero.flattenArguments() better handles passed objects - Zotero.File.getFileHash() (not currently used)
2009-05-14 18:23:40 +00:00
'uri',
'translation/translate_item',
'translation/translator',
'server_connector'
];
Initial Zotero 1.5 Megacommit Apologies for the massive (and, due to data_access.js splitting, difficult-to-follow) commit. Please note that external code that accesses the data layer may need to be tweaked for compatibility. Here's a comprehensive-as-possible changelog: - Added server sync functionality (incomplete) - Overhaul of data layer - Split data_access.js into separate files (item.js, items.js, creator.js, etc.) - Made creators and collections first-class objects, similar to items - Constructors now take id as first parameter, e.g. new Zotero.Item(1234, 'book'), to allow explicit id setting and id changing - Made various data layer operations (including attachment fields) require a save() rather than making direct DB changes - Better handling of unsaved objects - Item.setCreator() now takes creator objects instead of creator ids, and Item.save() will auto-save unsaved creators - clone() now works on unsaved objects - Newly created object instances are now disabled after save() to force refetch of globally accessible instance using Zotero.(Items|Creators|etc.).get() - Added secondary lookup key to data objects - Deprecated getID() and getItemType() methods in favor of .id and .itemTypeID properties - toArray() deprecated in favor of serialize(), which has a somewhat modified format - Added support for multiple creators with identical data -- currently unimplemented in interface and most of data layer - Added Item.diff() for comparing item metadata - Database changes - Added SQLite triggers to enforce foreign key constraints - Added Zotero.DB.transactionVacuum flag to run a VACUUM after a transaction - Added Zotero.DB.transactionDate, .transactionDateTime, and transactionTimestamp to retrieve consistent timestamps for entire transaction - Properly store 64-bit integers - Set PRAGMA locking_mode=EXCLUSIVE on database - Set SQLite page size to 4096 on new databases - Set SQLite page cache to 8MB - Do some database cleanup and integrity checking on migration from 1.0 branch - Removed IF NOT EXISTS from userdata.sql CREATE statements -- userdata.sql is now processed only on DB initialization - Removed itemNoteTitles table and moved titles into itemNotes - Abstracted metadata edit box and note box into flexible XBL bindings with various modes, including read-only states - Massive speed-up of item tree view - Several fixes from 1.0 branch for Fx3 compatibility - Added Notifier observer to log delete events for syncing - Zotero.Utilities changes - New methods getSQLDataType() and md5() - Removed onError from Zotero.Utilities.HTTP.doGet() - Don't display more than 1024 characters in doPost() debug output - Don't display passwords in doPost() debug output - Added Zotero.Notifier.untrigger() -- currently unused - Added Zotero.reloadDataObjects() to reset all in-memory objects - Added |chars| parameter to Zotero.randomString(len, chars) - Added Zotero.Date.getUnixTimestamp() and Date.toUnixTimestamp(JSDate) - Adjusted zotero-service.js to simplify file inclusion Various things (such as tags) are temporarily broken.
2008-05-04 08:32:48 +00:00
/** XPCOM files to be loaded only for connector translation and DB access **/
const xpcomFilesConnector = [
'connector/translate_item',
'connector/translator',
'connector/connector',
'connector/connector_firefox',
'connector/cachedTypes',
'connector/repo',
'connector/typeSchemaData'
];
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
Components.utils.import("resource://gre/modules/Services.jsm");
var instanceID = (new Date()).getTime();
var isFirstLoadThisSession = true;
var zContext = null;
var zInitOptions = {};
ZoteroContext = function() {}
ZoteroContext.prototype = {
/**
* Convenience method to replicate window.alert()
**/
// TODO: is this still used? if so, move to zotero.js
"alert":function alert(msg){
this.Zotero.debug("alert() is deprecated from Zotero XPCOM");
Cc["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Ci.nsIPromptService)
.alert(null, "", msg);
},
/**
* Convenience method to replicate window.confirm()
**/
// TODO: is this still used? if so, move to zotero.js
"confirm":function confirm(msg){
this.Zotero.debug("confirm() is deprecated from Zotero XPCOM");
return Cc["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Ci.nsIPromptService)
.confirm(null, "", msg);
},
"Cc":Cc,
"Ci":Ci,
/**
* Convenience method to replicate window.setTimeout()
**/
"setTimeout":function setTimeout(func, ms){
this.Zotero.setTimeout(func, ms);
},
/**
* Switches in or out of connector mode
*/
"switchConnectorMode":function(isConnector) {
if(isConnector !== this.isConnector) {
Services.obs.notifyObservers(zContext.Zotero, "zotero-before-reload", isConnector ? "connector" : "full");
zContext.Zotero.shutdown().then(function() {
// create a new zContext
makeZoteroContext(isConnector);
zContext.Zotero.init(zInitOptions);
}).done();
}
return zContext;
},
/**
* Shuts down Zotero, calls a callback (that may return a promise),
* then reinitializes Zotero. Returns a promise that is resolved
* when this process completes.
*/
"reinit":function(cb, isConnector) {
Services.obs.notifyObservers(zContext.Zotero, "zotero-before-reload", isConnector ? "connector" : "full");
return zContext.Zotero.shutdown().then(function() {
return cb ? cb() : false;
}).finally(function() {
makeZoteroContext(isConnector);
zContext.Zotero.init(zInitOptions);
});
}
};
/**
* The class from which the Zotero global XPCOM context is constructed
*
* @constructor
* This runs when ZoteroService is first requested to load all applicable scripts and initialize
* Zotero. Calls to other XPCOM components must be in here rather than in top-level code, as other
* components may not have yet been initialized.
*/
function makeZoteroContext(isConnector) {
if(zContext) {
// Swap out old zContext
var oldzContext = zContext;
// Create new zContext
zContext = new ZoteroContext();
// Swap in old Zotero object, so that references don't break, but empty it
zContext.Zotero = oldzContext.Zotero;
for(var key in zContext.Zotero) delete zContext.Zotero[key];
} else {
zContext = new ZoteroContext();
zContext.Zotero = function() {};
}
2013-01-21 06:58:01 +00:00
var subscriptLoader = Cc["@mozilla.org/moz/jssubscript-loader;1"].getService(Ci.mozIJSSubScriptLoader);
// Load zotero.js first
2013-01-21 06:58:01 +00:00
subscriptLoader.loadSubScript("chrome://zotero/content/xpcom/" + xpcomFilesAll[0] + ".js", zContext);
// Load CiteProc into Zotero.CiteProc namespace
zContext.Zotero.CiteProc = {"Zotero":zContext.Zotero};
subscriptLoader.loadSubScript("chrome://zotero/content/xpcom/citeproc-prereqs.js", zContext.Zotero.CiteProc);
2013-01-21 06:58:01 +00:00
subscriptLoader.loadSubScript("chrome://zotero/content/xpcom/citeproc.js", zContext.Zotero.CiteProc);
// Load XRegExp object into Zotero.XRegExp
const xregexpFiles = [
/**Core functions**/
'xregexp',
/**Addons**/
'addons/build', //adds ability to "build regular expressions using named subpatterns, for readability and pattern reuse"
'addons/matchrecursive', //adds ability to "match recursive constructs using XRegExp pattern strings as left and right delimiters"
2013-01-21 06:58:01 +00:00
/**Unicode support**/
'addons/unicode/unicode-base', //required for all other unicode packages. Adds \p{Letter} category
//'addons/unicode/unicode-blocks', //adds support for all Unicode blocks (e.g. InArabic, InCyrillic_Extended_A, etc.)
'addons/unicode/unicode-categories', //adds support for all Unicode categories (e.g. Punctuation, Lowercase_Letter, etc.)
//'addons/unicode/unicode-properties', //adds Level 1 Unicode properties (e.g. Uppercase, White_Space, etc.)
//'addons/unicode/unicode-scripts' //adds support for all Unicode scripts (e.g. Gujarati, Cyrillic, etc.)
'addons/unicode/unicode-zotero' //adds support for some Unicode categories used in Zotero
];
for (var i=0; i<xregexpFiles.length; i++) {
subscriptLoader.loadSubScript("chrome://zotero/content/xpcom/xregexp/" + xregexpFiles[i] + ".js", zContext);
}
// Load remaining xpcomFiles
for (var i=1; i<xpcomFilesAll.length; i++) {
try {
2013-01-21 06:58:01 +00:00
subscriptLoader.loadSubScript("chrome://zotero/content/xpcom/" + xpcomFilesAll[i] + ".js", zContext);
}
catch (e) {
Components.utils.reportError("Error loading " + xpcomFilesAll[i] + ".js", zContext);
throw (e);
}
}
// Load xpcomFiles for specific mode
for each(var xpcomFile in (isConnector ? xpcomFilesConnector : xpcomFilesLocal)) {
try {
2013-01-21 06:58:01 +00:00
subscriptLoader.loadSubScript("chrome://zotero/content/xpcom/" + xpcomFile + ".js", zContext);
}
catch (e) {
Components.utils.reportError("Error loading " + xpcomFile + ".js", zContext);
throw (e);
}
}
// Load RDF files into Zotero.RDF.AJAW namespace (easier than modifying all of the references)
const rdfXpcomFiles = [
2012-04-26 22:36:17 +00:00
'rdf/init',
'rdf/uri',
'rdf/term',
'rdf/identity',
'rdf/match',
'rdf/n3parser',
'rdf/rdfparser',
'rdf/serialize'
];
2012-05-05 20:53:00 +00:00
zContext.Zotero.RDF = {Zotero:zContext.Zotero};
for (var i=0; i<rdfXpcomFiles.length; i++) {
2013-01-21 06:58:01 +00:00
subscriptLoader.loadSubScript("chrome://zotero/content/xpcom/" + rdfXpcomFiles[i] + ".js", zContext.Zotero.RDF);
}
if(isStandalone()) {
// If isStandalone, load standalone.js
2013-01-21 06:58:01 +00:00
subscriptLoader.loadSubScript("chrome://zotero/content/xpcom/standalone.js", zContext);
}
// load nsTransferable (query: do we still use this?)
2013-01-21 06:58:01 +00:00
subscriptLoader.loadSubScript("chrome://global/content/nsTransferable.js", zContext);
// add connector-related properties
zContext.Zotero.isConnector = isConnector;
zContext.Zotero.instanceID = instanceID;
zContext.Zotero.__defineGetter__("isFirstLoadThisSession", function() isFirstLoadThisSession);
};
/**
* The class representing the Zotero service, and affiliated XPCOM goop
*/
function ZoteroService() {
try {
var start = Date.now();
if(isFirstLoadThisSession) {
makeZoteroContext(false);
try {
zContext.Zotero.init(zInitOptions);
} catch(e) {
if(e === "ZOTERO_SHOULD_START_AS_CONNECTOR") {
// if Zotero should start as a connector, reload it
zContext.Zotero.shutdown().then(function() {
makeZoteroContext(true);
zContext.Zotero.init(zInitOptions);
}).done();
} else {
throw e;
}
}
}
isFirstLoadThisSession = false; // no longer first load
this.wrappedJSObject = zContext.Zotero;
zContext.Zotero.debug("Initialized in "+(Date.now() - start)+" ms");
} catch(e) {
var msg = e instanceof Error
? e.name + ': ' + e.message + '\n' + e.fileName + ':' + e.lineNumber + '\n' + e.stack
: '' + e;
dump(msg + '\n');
Components.utils.reportError(e);
throw e;
}
}
ZoteroService.prototype = {
contractID: '@zotero.org/Zotero;1',
classDescription: 'Zotero',
classID: Components.ID('{e4c61080-ec2d-11da-8ad9-0800200c9a66}'),
QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsISupports,
Components.interfaces.nsIProtocolHandler])
}
var _isStandalone = null;
/**
* Determine whether Zotero Standalone is running
*/
function isStandalone() {
if(_isStandalone === null) {
var appInfo = Components.classes["@mozilla.org/xre/app-info;1"].
getService(Components.interfaces.nsIXULAppInfo);
_isStandalone = appInfo.ID === 'zotero@chnm.gmu.edu';
}
return _isStandalone;
}
/**
* The class representing the Zotero command line handler
*/
function ZoteroCommandLineHandler() {}
ZoteroCommandLineHandler.prototype = {
/* nsICommandLineHandler */
handle : function(cmdLine) {
// Force debug output
if (cmdLine.handleFlag("ZoteroDebug", false)) {
zInitOptions.forceDebugLog = true;
}
// handler to open Zotero pane at startup in Zotero for Firefox
if (!isStandalone() && cmdLine.handleFlag("ZoteroPaneOpen", false)) {
zInitOptions.openPane = true;
}
// handler for Zotero integration commands
// this is typically used on Windows only, via WM_COPYDATA rather than the command line
var agent = cmdLine.handleFlagWithParam("ZoteroIntegrationAgent", false);
if(agent) {
// Don't open a new window
cmdLine.preventDefault = true;
var command = cmdLine.handleFlagWithParam("ZoteroIntegrationCommand", false);
var docId = cmdLine.handleFlagWithParam("ZoteroIntegrationDocument", false);
// Not quite sure why this is necessary to get the appropriate scoping
var Zotero = this.Zotero;
Zotero.setTimeout(function() { Zotero.Integration.execCommand(agent, command, docId) }, 0);
}
// handler for Windows IPC commands
var ipcParam = cmdLine.handleFlagWithParam("ZoteroIPC", false);
if(ipcParam) {
// Don't open a new window
cmdLine.preventDefault = true;
var Zotero = this.Zotero;
Zotero.setTimeout(function() { Zotero.IPC.parsePipeInput(ipcParam) }, 0);
}
// special handler for "zotero" URIs at the command line to prevent them from opening a new
// window
if(isStandalone()) {
var param = cmdLine.handleFlagWithParam("url", false);
if(param) {
var uri = cmdLine.resolveURI(param);
if(uri.schemeIs("zotero")) {
// Check for existing window and focus it
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var win = wm.getMostRecentWindow("navigator:browser");
if(win) {
win.focus();
Components.classes["@mozilla.org/network/protocol;1?name=zotero"]
.createInstance(Components.interfaces.nsIProtocolHandler).newChannel(uri);
}
} else {
this.Zotero.debug("Not handling URL: "+uri.spec);
}
}
var param = cmdLine.handleFlagWithParam("file", false);
if(param) {
var file = Components.classes["@mozilla.org/file/local;1"].
createInstance(Components.interfaces.nsILocalFile);
file.initWithPath(param);
if(file.leafName.substr(-4).toLowerCase() === ".csl"
|| file.leafName.substr(-8).toLowerCase() === ".csl.txt") {
// Install CSL file
this.Zotero.Styles.install(file);
} else {
// Ask before importing
var checkState = {"value":this.Zotero.Prefs.get('import.createNewCollection.fromFileOpenHandler')};
if(Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
.getService(Components.interfaces.nsIPromptService)
.confirmCheck(null, this.Zotero.getString('ingester.importFile.title'),
this.Zotero.getString('ingester.importFile.text', [file.leafName]),
this.Zotero.getString('ingester.importFile.intoNewCollection'),
checkState)) {
// Perform file import in front window
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var browserWindow = wm.getMostRecentWindow("navigator:browser");
browserWindow.Zotero_File_Interface.importFile(file, checkState.value);
this.Zotero.Prefs.set('import.createNewCollection.fromFileOpenHandler', checkState.value);
}
}
}
}
if (cmdLine.handleFlag("ZoteroNoUserInput", false)) {
zInitOptions.noUserInput = true;
}
},
contractID: "@mozilla.org/commandlinehandler/general-startup;1?type=zotero",
classDescription: "Zotero Command Line Handler",
classID: Components.ID("{531828f8-a16c-46be-b9aa-14845c3b010f}"),
service: true,
_xpcom_categories: [{category:"command-line-handler", entry:"m-zotero"}],
QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsICommandLineHandler,
Components.interfaces.nsISupports])
};
ZoteroCommandLineHandler.prototype.__defineGetter__("Zotero", function() {
if(!zContext) new ZoteroService();
return zContext.Zotero;
});
/**
* XPCOMUtils.generateNSGetFactory was introduced in Mozilla 2 (Firefox 4).
* XPCOMUtils.generateNSGetModule is for Mozilla 1.9.2 (Firefox 3.6).
*/
if (XPCOMUtils.generateNSGetFactory) {
var NSGetFactory = XPCOMUtils.generateNSGetFactory([ZoteroService, ZoteroCommandLineHandler]);
} else {
var NSGetModule = XPCOMUtils.generateNSGetModule([ZoteroService, ZoteroCommandLineHandler]);
}