You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@camel.apache.org by js...@apache.org on 2009/03/19 12:11:05 UTC
svn commit: r755920 [6/11] - in
/camel/trunk/components/camel-web/src/main/webapp/js/dojox: json/ jsonPath/
lang/ lang/aspect/ lang/functional/ lang/oo/ layout/ layout/dnd/
layout/ext-dijit/ layout/ext-dijit/layout/ layout/nls/ layout/nls/en/
layout/nl...
Added: camel/trunk/components/camel-web/src/main/webapp/js/dojox/off/offline.js.uncompressed.js
URL: http://svn.apache.org/viewvc/camel/trunk/components/camel-web/src/main/webapp/js/dojox/off/offline.js.uncompressed.js?rev=755920&view=auto
==============================================================================
--- camel/trunk/components/camel-web/src/main/webapp/js/dojox/off/offline.js.uncompressed.js (added)
+++ camel/trunk/components/camel-web/src/main/webapp/js/dojox/off/offline.js.uncompressed.js Thu Mar 19 11:10:58 2009
@@ -0,0 +1,6243 @@
+/*
+ Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved.
+ Available via Academic Free License >= 2.1 OR the modified BSD license.
+ see: http://dojotoolkit.org/license for details
+*/
+
+/*
+ This is a compiled version of Dojo, built for deployment and not for
+ development. To get an editable version, please visit:
+
+ http://dojotoolkit.org
+
+ for documentation and information on getting the source.
+*/
+
+if(!dojo._hasResource["dojox.storage.Provider"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
+dojo._hasResource["dojox.storage.Provider"] = true;
+dojo.provide("dojox.storage.Provider");
+
+dojo.declare("dojox.storage.Provider", null, {
+ // summary: A singleton for working with dojox.storage.
+ // description:
+ // dojox.storage exposes the current available storage provider on this
+ // platform. It gives you methods such as dojox.storage.put(),
+ // dojox.storage.get(), etc.
+ //
+ // For more details on dojox.storage, see the primary documentation
+ // page at
+ // http://manual.dojotoolkit.org/storage.html
+ //
+ // Note for storage provider developers who are creating subclasses-
+ // This is the base class for all storage providers Specific kinds of
+ // Storage Providers should subclass this and implement these methods.
+ // You should avoid initialization in storage provider subclass's
+ // constructor; instead, perform initialization in your initialize()
+ // method.
+ constructor: function(){
+ },
+
+ // SUCCESS: String
+ // Flag that indicates a put() call to a
+ // storage provider was succesful.
+ SUCCESS: "success",
+
+ // FAILED: String
+ // Flag that indicates a put() call to
+ // a storage provider failed.
+ FAILED: "failed",
+
+ // PENDING: String
+ // Flag that indicates a put() call to a
+ // storage provider is pending user approval.
+ PENDING: "pending",
+
+ // SIZE_NOT_AVAILABLE: String
+ // Returned by getMaximumSize() if this storage provider can not determine
+ // the maximum amount of data it can support.
+ SIZE_NOT_AVAILABLE: "Size not available",
+
+ // SIZE_NO_LIMIT: String
+ // Returned by getMaximumSize() if this storage provider has no theoretical
+ // limit on the amount of data it can store.
+ SIZE_NO_LIMIT: "No size limit",
+
+ // DEFAULT_NAMESPACE: String
+ // The namespace for all storage operations. This is useful if several
+ // applications want access to the storage system from the same domain but
+ // want different storage silos.
+ DEFAULT_NAMESPACE: "default",
+
+ // onHideSettingsUI: Function
+ // If a function is assigned to this property, then when the settings
+ // provider's UI is closed this function is called. Useful, for example,
+ // if the user has just cleared out all storage for this provider using
+ // the settings UI, and you want to update your UI.
+ onHideSettingsUI: null,
+
+ initialize: function(){
+ // summary:
+ // Allows this storage provider to initialize itself. This is
+ // called after the page has finished loading, so you can not do
+ // document.writes(). Storage Provider subclasses should initialize
+ // themselves inside of here rather than in their function
+ // constructor.
+ console.warn("dojox.storage.initialize not implemented");
+ },
+
+ isAvailable: function(){ /*Boolean*/
+ // summary:
+ // Returns whether this storage provider is available on this
+ // platform.
+ console.warn("dojox.storage.isAvailable not implemented");
+ },
+
+ put: function( /*string*/ key,
+ /*object*/ value,
+ /*function*/ resultsHandler,
+ /*string?*/ namespace){
+ // summary:
+ // Puts a key and value into this storage system.
+ // description:
+ // Example-
+ // var resultsHandler = function(status, key, message, namespace){
+ // alert("status="+status+", key="+key+", message="+message);
+ // };
+ // dojox.storage.put("test", "hello world", resultsHandler);
+ //
+ // Arguments:
+ //
+ // status - The status of the put operation, given by
+ // dojox.storage.FAILED, dojox.storage.SUCCEEDED, or
+ // dojox.storage.PENDING
+ // key - The key that was used for the put
+ // message - An optional message if there was an error or things failed.
+ // namespace - The namespace of the key. This comes at the end since
+ // it was added later.
+ //
+ // Important note: if you are using Dojo Storage in conjunction with
+ // Dojo Offline, then you don't need to provide
+ // a resultsHandler; this is because for Dojo Offline we
+ // use Google Gears to persist data, which has unlimited data
+ // once the user has given permission. If you are using Dojo
+ // Storage apart from Dojo Offline, then under the covers hidden
+ // Flash might be used, which is both asychronous and which might
+ // get denied; in this case you must provide a resultsHandler.
+ // key:
+ // A string key to use when retrieving this value in the future.
+ // value:
+ // A value to store; this can be any JavaScript type.
+ // resultsHandler:
+ // A callback function that will receive three arguments. The
+ // first argument is one of three values: dojox.storage.SUCCESS,
+ // dojox.storage.FAILED, or dojox.storage.PENDING; these values
+ // determine how the put request went. In some storage systems
+ // users can deny a storage request, resulting in a
+ // dojox.storage.FAILED, while in other storage systems a storage
+ // request must wait for user approval, resulting in a
+ // dojox.storage.PENDING status until the request is either
+ // approved or denied, resulting in another call back with
+ // dojox.storage.SUCCESS.
+ // The second argument in the call back is the key name that was being stored.
+ // The third argument in the call back is an optional message that
+ // details possible error messages that might have occurred during
+ // the storage process.
+ // namespace:
+ // Optional string namespace that this value will be placed into;
+ // if left off, the value will be placed into dojox.storage.DEFAULT_NAMESPACE
+
+ console.warn("dojox.storage.put not implemented");
+ },
+
+ get: function(/*string*/ key, /*string?*/ namespace){ /*Object*/
+ // summary:
+ // Gets the value with the given key. Returns null if this key is
+ // not in the storage system.
+ // key:
+ // A string key to get the value of.
+ // namespace:
+ // Optional string namespace that this value will be retrieved from;
+ // if left off, the value will be retrieved from dojox.storage.DEFAULT_NAMESPACE
+ // return: Returns any JavaScript object type; null if the key is not present
+ console.warn("dojox.storage.get not implemented");
+ },
+
+ hasKey: function(/*string*/ key, /*string?*/ namespace){
+ // summary: Determines whether the storage has the given key.
+ return !!this.get(key, namespace); // Boolean
+ },
+
+ getKeys: function(/*string?*/ namespace){ /*Array*/
+ // summary: Enumerates all of the available keys in this storage system.
+ // return: Array of available keys
+ console.warn("dojox.storage.getKeys not implemented");
+ },
+
+ clear: function(/*string?*/ namespace){
+ // summary:
+ // Completely clears this storage system of all of it's values and
+ // keys. If 'namespace' is provided just clears the keys in that
+ // namespace.
+ console.warn("dojox.storage.clear not implemented");
+ },
+
+ remove: function(/*string*/ key, /*string?*/ namespace){
+ // summary: Removes the given key from this storage system.
+ console.warn("dojox.storage.remove not implemented");
+ },
+
+ getNamespaces: function(){ /*string[]*/
+ console.warn("dojox.storage.getNamespaces not implemented");
+ },
+
+ isPermanent: function(){ /*Boolean*/
+ // summary:
+ // Returns whether this storage provider's values are persisted
+ // when this platform is shutdown.
+ console.warn("dojox.storage.isPermanent not implemented");
+ },
+
+ getMaximumSize: function(){ /* mixed */
+ // summary: The maximum storage allowed by this provider
+ // returns:
+ // Returns the maximum storage size
+ // supported by this provider, in
+ // thousands of bytes (i.e., if it
+ // returns 60 then this means that 60K
+ // of storage is supported).
+ //
+ // If this provider can not determine
+ // it's maximum size, then
+ // dojox.storage.SIZE_NOT_AVAILABLE is
+ // returned; if there is no theoretical
+ // limit on the amount of storage
+ // this provider can return, then
+ // dojox.storage.SIZE_NO_LIMIT is
+ // returned
+ console.warn("dojox.storage.getMaximumSize not implemented");
+ },
+
+ putMultiple: function( /*array*/ keys,
+ /*array*/ values,
+ /*function*/ resultsHandler,
+ /*string?*/ namespace){
+ // summary:
+ // Puts multiple keys and values into this storage system.
+ // description:
+ // Example-
+ // var resultsHandler = function(status, key, message){
+ // alert("status="+status+", key="+key+", message="+message);
+ // };
+ // dojox.storage.put(["test"], ["hello world"], resultsHandler);
+ //
+ // Important note: if you are using Dojo Storage in conjunction with
+ // Dojo Offline, then you don't need to provide
+ // a resultsHandler; this is because for Dojo Offline we
+ // use Google Gears to persist data, which has unlimited data
+ // once the user has given permission. If you are using Dojo
+ // Storage apart from Dojo Offline, then under the covers hidden
+ // Flash might be used, which is both asychronous and which might
+ // get denied; in this case you must provide a resultsHandler.
+ // keys:
+ // An array of string keys to use when retrieving this value in the future,
+ // one per value to be stored
+ // values:
+ // An array of values to store; this can be any JavaScript type, though the
+ // performance of plain strings is considerably better
+ // resultsHandler:
+ // A callback function that will receive three arguments. The
+ // first argument is one of three values: dojox.storage.SUCCESS,
+ // dojox.storage.FAILED, or dojox.storage.PENDING; these values
+ // determine how the put request went. In some storage systems
+ // users can deny a storage request, resulting in a
+ // dojox.storage.FAILED, while in other storage systems a storage
+ // request must wait for user approval, resulting in a
+ // dojox.storage.PENDING status until the request is either
+ // approved or denied, resulting in another call back with
+ // dojox.storage.SUCCESS.
+ // The second argument in the call back is the key name that was being stored.
+ // The third argument in the call back is an optional message that
+ // details possible error messages that might have occurred during
+ // the storage process.
+ // namespace:
+ // Optional string namespace that this value will be placed into;
+ // if left off, the value will be placed into dojox.storage.DEFAULT_NAMESPACE
+
+ for(var i = 0; i < keys.length; i++){
+ dojox.storage.put(keys[i], values[i], resultsHandler, namespace);
+ }
+ },
+
+ getMultiple: function(/*array*/ keys, /*string?*/ namespace){ /*Object*/
+ // summary:
+ // Gets the valuse corresponding to each of the given keys.
+ // Returns a null array element for each given key that is
+ // not in the storage system.
+ // keys:
+ // An array of string keys to get the value of.
+ // namespace:
+ // Optional string namespace that this value will be retrieved from;
+ // if left off, the value will be retrieved from dojox.storage.DEFAULT_NAMESPACE
+ // return: Returns any JavaScript object type; null if the key is not present
+
+ var results = [];
+ for(var i = 0; i < keys.length; i++){
+ results.push(dojox.storage.get(keys[i], namespace));
+ }
+
+ return results;
+ },
+
+ removeMultiple: function(/*array*/ keys, /*string?*/ namespace) {
+ // summary: Removes the given keys from this storage system.
+
+ for(var i = 0; i < keys.length; i++){
+ dojox.storage.remove(keys[i], namespace);
+ }
+ },
+
+ isValidKeyArray: function( keys) {
+ if(keys === null || keys === undefined || !dojo.isArray(keys)){
+ return false;
+ }
+
+ // JAC: This could be optimized by running the key validity test
+ // directly over a joined string
+ return !dojo.some(keys, function(key){
+ return !this.isValidKey(key);
+ }, this); // Boolean
+ },
+
+ hasSettingsUI: function(){ /*Boolean*/
+ // summary: Determines whether this provider has a settings UI.
+ return false;
+ },
+
+ showSettingsUI: function(){
+ // summary: If this provider has a settings UI, determined
+ // by calling hasSettingsUI(), it is shown.
+ console.warn("dojox.storage.showSettingsUI not implemented");
+ },
+
+ hideSettingsUI: function(){
+ // summary: If this provider has a settings UI, hides it.
+ console.warn("dojox.storage.hideSettingsUI not implemented");
+ },
+
+ isValidKey: function(/*string*/ keyName){ /*Boolean*/
+ // summary:
+ // Subclasses can call this to ensure that the key given is valid
+ // in a consistent way across different storage providers. We use
+ // the lowest common denominator for key values allowed: only
+ // letters, numbers, and underscores are allowed. No spaces.
+ if(keyName === null || keyName === undefined){
+ return false;
+ }
+
+ return /^[0-9A-Za-z_]*$/.test(keyName);
+ },
+
+ getResourceList: function(){ /* Array[] */
+ // summary:
+ // Returns a list of URLs that this
+ // storage provider might depend on.
+ // description:
+ // This method returns a list of URLs that this
+ // storage provider depends on to do its work.
+ // This list is used by the Dojo Offline Toolkit
+ // to cache these resources to ensure the machinery
+ // used by this storage provider is available offline.
+ // What is returned is an array of URLs.
+ // Note that Dojo Offline uses Gears as its native
+ // storage provider, and does not support using other
+ // kinds of storage providers while offline anymore.
+
+ return [];
+ }
+});
+
+}
+
+if(!dojo._hasResource["dojox.storage.manager"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
+dojo._hasResource["dojox.storage.manager"] = true;
+dojo.provide("dojox.storage.manager");
+//
+// FIXME: refactor this to use an AdapterRegistry
+
+dojox.storage.manager = new function(){
+ // summary: A singleton class in charge of the dojox.storage system
+ // description:
+ // Initializes the storage systems and figures out the best available
+ // storage options on this platform.
+
+ // currentProvider: Object
+ // The storage provider that was automagically chosen to do storage
+ // on this platform, such as dojox.storage.FlashStorageProvider.
+ this.currentProvider = null;
+
+ // available: Boolean
+ // Whether storage of some kind is available.
+ this.available = false;
+
+ // providers: Array
+ // Array of all the static provider instances, useful if you want to
+ // loop through and see what providers have been registered.
+ this.providers = [];
+
+ this._initialized = false;
+
+ this._onLoadListeners = [];
+
+ this.initialize = function(){
+ // summary:
+ // Initializes the storage system and autodetects the best storage
+ // provider we can provide on this platform
+ this.autodetect();
+ };
+
+ this.register = function(/*string*/ name, /*Object*/ instance){
+ // summary:
+ // Registers the existence of a new storage provider; used by
+ // subclasses to inform the manager of their existence. The
+ // storage manager will select storage providers based on
+ // their ordering, so the order in which you call this method
+ // matters.
+ // name:
+ // The full class name of this provider, such as
+ // "dojox.storage.FlashStorageProvider".
+ // instance:
+ // An instance of this provider, which we will use to call
+ // isAvailable() on.
+
+ // keep list of providers as a list so that we can know what order
+ // storage providers are preferred; also, store the providers hashed
+ // by name in case someone wants to get a provider that uses
+ // a particular storage backend
+ this.providers.push(instance);
+ this.providers[name] = instance;
+ };
+
+ this.setProvider = function(storageClass){
+ // summary:
+ // Instructs the storageManager to use the given storage class for
+ // all storage requests.
+ // description:
+ // Example-
+ // dojox.storage.setProvider(
+ // dojox.storage.IEStorageProvider)
+
+ };
+
+ this.autodetect = function(){
+ // summary:
+ // Autodetects the best possible persistent storage provider
+ // available on this platform.
+
+ //
+
+ if(this._initialized){ // already finished
+ return;
+ }
+
+ // a flag to force the storage manager to use a particular
+ // storage provider type, such as
+ // djConfig = {forceStorageProvider: "dojox.storage.WhatWGStorageProvider"};
+ var forceProvider = dojo.config["forceStorageProvider"] || false;
+
+ // go through each provider, seeing if it can be used
+ var providerToUse;
+ //FIXME: use dojo.some
+ for(var i = 0; i < this.providers.length; i++){
+ providerToUse = this.providers[i];
+ if(forceProvider && forceProvider == providerToUse.declaredClass){
+ // still call isAvailable for this provider, since this helps some
+ // providers internally figure out if they are available
+ // FIXME: This should be refactored since it is non-intuitive
+ // that isAvailable() would initialize some state
+ providerToUse.isAvailable();
+ break;
+ }else if(!forceProvider && providerToUse.isAvailable()){
+ break;
+ }
+ }
+
+ if(!providerToUse){ // no provider available
+ this._initialized = true;
+ this.available = false;
+ this.currentProvider = null;
+ console.warn("No storage provider found for this platform");
+ this.loaded();
+ return;
+ }
+
+ // create this provider and mix in it's properties
+ // so that developers can do dojox.storage.put rather
+ // than dojox.storage.currentProvider.put, for example
+ this.currentProvider = providerToUse;
+ dojo.mixin(dojox.storage, this.currentProvider);
+
+ // have the provider initialize itself
+ dojox.storage.initialize();
+
+ this._initialized = true;
+ this.available = true;
+ };
+
+ this.isAvailable = function(){ /*Boolean*/
+ // summary: Returns whether any storage options are available.
+ return this.available;
+ };
+
+ this.addOnLoad = function(func){ /* void */
+ // summary:
+ // Adds an onload listener to know when Dojo Offline can be used.
+ // description:
+ // Adds a listener to know when Dojo Offline can be used. This
+ // ensures that the Dojo Offline framework is loaded and that the
+ // local dojox.storage system is ready to be used. This method is
+ // useful if you don't want to have a dependency on Dojo Events
+ // when using dojox.storage.
+ // func: Function
+ // A function to call when Dojo Offline is ready to go
+ this._onLoadListeners.push(func);
+
+ if(this.isInitialized()){
+ this._fireLoaded();
+ }
+ };
+
+ this.removeOnLoad = function(func){ /* void */
+ // summary: Removes the given onLoad listener
+ for(var i = 0; i < this._onLoadListeners.length; i++){
+ if(func == this._onLoadListeners[i]){
+ this._onLoadListeners = this._onLoadListeners.splice(i, 1);
+ break;
+ }
+ }
+ };
+
+ this.isInitialized = function(){ /*Boolean*/
+ // summary:
+ // Returns whether the storage system is initialized and ready to
+ // be used.
+
+ // FIXME: This should REALLY not be in here, but it fixes a tricky
+ // Flash timing bug.
+ // Confirm that this is still needed with the newly refactored Dojo
+ // Flash. Used to be for Internet Explorer. -- Brad Neuberg
+ if(this.currentProvider != null
+ && this.currentProvider.declaredClass == "dojox.storage.FlashStorageProvider"
+ && dojox.flash.ready == false){
+ return false;
+ }else{
+ return this._initialized;
+ }
+ };
+
+ this.supportsProvider = function(/*string*/ storageClass){ /* Boolean */
+ // summary: Determines if this platform supports the given storage provider.
+ // description:
+ // Example-
+ // dojox.storage.manager.supportsProvider(
+ // "dojox.storage.InternetExplorerStorageProvider");
+
+ // construct this class dynamically
+ try{
+ // dynamically call the given providers class level isAvailable()
+ // method
+ var provider = eval("new " + storageClass + "()");
+ var results = provider.isAvailable();
+ if(!results){ return false; }
+ return results;
+ }catch(e){
+ return false;
+ }
+ };
+
+ this.getProvider = function(){ /* Object */
+ // summary: Gets the current provider
+ return this.currentProvider;
+ };
+
+ this.loaded = function(){
+ // summary:
+ // The storage provider should call this method when it is loaded
+ // and ready to be used. Clients who will use the provider will
+ // connect to this method to know when they can use the storage
+ // system. You can either use dojo.connect to connect to this
+ // function, or can use dojox.storage.manager.addOnLoad() to add
+ // a listener that does not depend on the dojo.event package.
+ // description:
+ // Example 1-
+ // if(dojox.storage.manager.isInitialized() == false){
+ // dojo.connect(dojox.storage.manager, "loaded", TestStorage, "initialize");
+ // }else{
+ // dojo.connect(dojo, "loaded", TestStorage, "initialize");
+ // }
+ // Example 2-
+ // dojox.storage.manager.addOnLoad(someFunction);
+
+
+ // FIXME: we should just provide a Deferred for this. That way you
+ // don't care when this happens or has happened. Deferreds are in Base
+ this._fireLoaded();
+ };
+
+ this._fireLoaded = function(){
+ //
+
+ dojo.forEach(this._onLoadListeners, function(i){
+ try{
+ i();
+ }catch(e){ }
+ });
+ };
+
+ this.getResourceList = function(){
+ // summary:
+ // Returns a list of whatever resources are necessary for storage
+ // providers to work.
+ // description:
+ // This will return all files needed by all storage providers for
+ // this particular environment type. For example, if we are in the
+ // browser environment, then this will return the hidden SWF files
+ // needed by the FlashStorageProvider, even if we don't need them
+ // for the particular browser we are working within. This is meant
+ // to faciliate Dojo Offline, which must retrieve all resources we
+ // need offline into the offline cache -- we retrieve everything
+ // needed, in case another browser that requires different storage
+ // mechanisms hits the local offline cache. For example, if we
+ // were to sync against Dojo Offline on Firefox 2, then we would
+ // not grab the FlashStorageProvider resources needed for Safari.
+ var results = [];
+ dojo.forEach(dojox.storage.manager.providers, function(currentProvider){
+ results = results.concat(currentProvider.getResourceList());
+ });
+
+ return results;
+ }
+};
+
+}
+
+if(!dojo._hasResource["dojo.gears"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
+dojo._hasResource["dojo.gears"] = true;
+dojo.provide("dojo.gears");
+
+dojo.gears._gearsObject = function(){
+ // summary:
+ // factory method to get a Google Gears plugin instance to
+ // expose in the browser runtime environment, if present
+ var factory;
+ var results;
+
+ var gearsObj = dojo.getObject("google.gears");
+ if(gearsObj){ return gearsObj; } // already defined elsewhere
+
+ if(typeof GearsFactory != "undefined"){ // Firefox
+ factory = new GearsFactory();
+ }else{
+ if(dojo.isIE){
+ // IE
+ try{
+ factory = new ActiveXObject("Gears.Factory");
+ }catch(e){
+ // ok to squelch; there's no gears factory. move on.
+ }
+ }else if(navigator.mimeTypes["application/x-googlegears"]){
+ // Safari?
+ factory = document.createElement("object");
+ factory.setAttribute("type", "application/x-googlegears");
+ factory.setAttribute("width", 0);
+ factory.setAttribute("height", 0);
+ factory.style.display = "none";
+ document.documentElement.appendChild(factory);
+ }
+ }
+
+ // still nothing?
+ if(!factory){ return null; }
+
+ // define the global objects now; don't overwrite them though if they
+ // were somehow set internally by the Gears plugin, which is on their
+ // dev roadmap for the future
+ dojo.setObject("google.gears.factory", factory);
+ return dojo.getObject("google.gears");
+};
+
+/*=====
+dojo.gears.available = {
+ // summary: True if client is using Google Gears
+};
+=====*/
+// see if we have Google Gears installed, and if
+// so, make it available in the runtime environment
+// and in the Google standard 'google.gears' global object
+dojo.gears.available = (!!dojo.gears._gearsObject())||0;
+
+}
+
+if(!dojo._hasResource["dojox.sql._crypto"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
+dojo._hasResource["dojox.sql._crypto"] = true;
+dojo.provide("dojox.sql._crypto");
+dojo.mixin(dojox.sql._crypto, {
+ // summary: dojox.sql cryptography code
+ // description:
+ // Taken from http://www.movable-type.co.uk/scripts/aes.html by
+ // Chris Veness (CLA signed); adapted for Dojo and Google Gears Worker Pool
+ // by Brad Neuberg, bkn3@columbia.edu
+ //
+ // _POOL_SIZE:
+ // Size of worker pool to create to help with crypto
+ _POOL_SIZE: 100,
+
+ encrypt: function(plaintext, password, callback){
+ // summary:
+ // Use Corrected Block TEA to encrypt plaintext using password
+ // (note plaintext & password must be strings not string objects).
+ // Results will be returned to the 'callback' asychronously.
+ this._initWorkerPool();
+
+ var msg ={plaintext: plaintext, password: password};
+ msg = dojo.toJson(msg);
+ msg = "encr:" + String(msg);
+
+ this._assignWork(msg, callback);
+ },
+
+ decrypt: function(ciphertext, password, callback){
+ // summary:
+ // Use Corrected Block TEA to decrypt ciphertext using password
+ // (note ciphertext & password must be strings not string objects).
+ // Results will be returned to the 'callback' asychronously.
+ this._initWorkerPool();
+
+ var msg = {ciphertext: ciphertext, password: password};
+ msg = dojo.toJson(msg);
+ msg = "decr:" + String(msg);
+
+ this._assignWork(msg, callback);
+ },
+
+ _initWorkerPool: function(){
+ // bugs in Google Gears prevents us from dynamically creating
+ // and destroying workers as we need them -- the worker
+ // pool functionality stops working after a number of crypto
+ // cycles (probably related to a memory leak in Google Gears).
+ // this is too bad, since it results in much simpler code.
+
+ // instead, we have to create a pool of workers and reuse them. we
+ // keep a stack of 'unemployed' Worker IDs that are currently not working.
+ // if a work request comes in, we pop off the 'unemployed' stack
+ // and put them to work, storing them in an 'employed' hashtable,
+ // keyed by their Worker ID with the value being the callback function
+ // that wants the result. when an employed worker is done, we get
+ // a message in our 'manager' which adds this worker back to the
+ // unemployed stack and routes the result to the callback that
+ // wanted it. if all the workers were employed in the past but
+ // more work needed to be done (i.e. it's a tight labor pool ;)
+ // then the work messages are pushed onto
+ // a 'handleMessage' queue as an object tuple{msg: msg, callback: callback}
+
+ if(!this._manager){
+ try{
+ this._manager = google.gears.factory.create("beta.workerpool", "1.0");
+ this._unemployed = [];
+ this._employed ={};
+ this._handleMessage = [];
+
+ var self = this;
+ this._manager.onmessage = function(msg, sender){
+ // get the callback necessary to serve this result
+ var callback = self._employed["_" + sender];
+
+ // make this worker unemployed
+ self._employed["_" + sender] = undefined;
+ self._unemployed.push("_" + sender);
+
+ // see if we need to assign new work
+ // that was queued up needing to be done
+ if(self._handleMessage.length){
+ var handleMe = self._handleMessage.shift();
+ self._assignWork(handleMe.msg, handleMe.callback);
+ }
+
+ // return results
+ callback(msg);
+ }
+
+ var workerInit = "function _workerInit(){"
+ + "gearsWorkerPool.onmessage = "
+ + String(this._workerHandler)
+ + ";"
+ + "}";
+
+ var code = workerInit + " _workerInit();";
+
+ // create our worker pool
+ for(var i = 0; i < this._POOL_SIZE; i++){
+ this._unemployed.push("_" + this._manager.createWorker(code));
+ }
+ }catch(exp){
+ throw exp.message||exp;
+ }
+ }
+ },
+
+ _assignWork: function(msg, callback){
+ // can we immediately assign this work?
+ if(!this._handleMessage.length && this._unemployed.length){
+ // get an unemployed worker
+ var workerID = this._unemployed.shift().substring(1); // remove _
+
+ // list this worker as employed
+ this._employed["_" + workerID] = callback;
+
+ // do the worke
+ this._manager.sendMessage(msg, parseInt(workerID,10));
+ }else{
+ // we have to queue it up
+ this._handleMessage ={msg: msg, callback: callback};
+ }
+ },
+
+ _workerHandler: function(msg, sender){
+
+ /* Begin AES Implementation */
+
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
+
+ // Sbox is pre-computed multiplicative inverse in GF(2^8) used in SubBytes and KeyExpansion [§5.1.1]
+ var Sbox = [0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
+ 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
+ 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
+ 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
+ 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
+ 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
+ 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
+ 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
+ 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
+ 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
+ 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
+ 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
+ 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
+ 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
+ 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
+ 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16];
+
+ // Rcon is Round Constant used for the Key Expansion [1st col is 2^(r-1) in GF(2^8)] [§5.2]
+ var Rcon = [ [0x00, 0x00, 0x00, 0x00],
+ [0x01, 0x00, 0x00, 0x00],
+ [0x02, 0x00, 0x00, 0x00],
+ [0x04, 0x00, 0x00, 0x00],
+ [0x08, 0x00, 0x00, 0x00],
+ [0x10, 0x00, 0x00, 0x00],
+ [0x20, 0x00, 0x00, 0x00],
+ [0x40, 0x00, 0x00, 0x00],
+ [0x80, 0x00, 0x00, 0x00],
+ [0x1b, 0x00, 0x00, 0x00],
+ [0x36, 0x00, 0x00, 0x00] ];
+
+ /*
+ * AES Cipher function: encrypt 'input' with Rijndael algorithm
+ *
+ * takes byte-array 'input' (16 bytes)
+ * 2D byte-array key schedule 'w' (Nr+1 x Nb bytes)
+ *
+ * applies Nr rounds (10/12/14) using key schedule w for 'add round key' stage
+ *
+ * returns byte-array encrypted value (16 bytes)
+ */
+ function Cipher(input, w) { // main Cipher function [§5.1]
+ var Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
+ var Nr = w.length/Nb - 1; // no of rounds: 10/12/14 for 128/192/256-bit keys
+
+ var state = [[],[],[],[]]; // initialise 4xNb byte-array 'state' with input [§3.4]
+ for (var i=0; i<4*Nb; i++) state[i%4][Math.floor(i/4)] = input[i];
+
+ state = AddRoundKey(state, w, 0, Nb);
+
+ for (var round=1; round<Nr; round++) {
+ state = SubBytes(state, Nb);
+ state = ShiftRows(state, Nb);
+ state = MixColumns(state, Nb);
+ state = AddRoundKey(state, w, round, Nb);
+ }
+
+ state = SubBytes(state, Nb);
+ state = ShiftRows(state, Nb);
+ state = AddRoundKey(state, w, Nr, Nb);
+
+ var output = new Array(4*Nb); // convert state to 1-d array before returning [§3.4]
+ for (var i=0; i<4*Nb; i++) output[i] = state[i%4][Math.floor(i/4)];
+ return output;
+ }
+
+
+ function SubBytes(s, Nb) { // apply SBox to state S [§5.1.1]
+ for (var r=0; r<4; r++) {
+ for (var c=0; c<Nb; c++) s[r][c] = Sbox[s[r][c]];
+ }
+ return s;
+ }
+
+
+ function ShiftRows(s, Nb) { // shift row r of state S left by r bytes [§5.1.2]
+ var t = new Array(4);
+ for (var r=1; r<4; r++) {
+ for (var c=0; c<4; c++) t[c] = s[r][(c+r)%Nb]; // shift into temp copy
+ for (var c=0; c<4; c++) s[r][c] = t[c]; // and copy back
+ } // note that this will work for Nb=4,5,6, but not 7,8 (always 4 for AES):
+ return s; // see fp.gladman.plus.com/cryptography_technology/rijndael/aes.spec.311.pdf
+ }
+
+
+ function MixColumns(s, Nb) { // combine bytes of each col of state S [§5.1.3]
+ for (var c=0; c<4; c++) {
+ var a = new Array(4); // 'a' is a copy of the current column from 's'
+ var b = new Array(4); // 'b' is aâ¢{02} in GF(2^8)
+ for (var i=0; i<4; i++) {
+ a[i] = s[i][c];
+ b[i] = s[i][c]&0x80 ? s[i][c]<<1 ^ 0x011b : s[i][c]<<1;
+ }
+ // a[n] ^ b[n] is aâ¢{03} in GF(2^8)
+ s[0][c] = b[0] ^ a[1] ^ b[1] ^ a[2] ^ a[3]; // 2*a0 + 3*a1 + a2 + a3
+ s[1][c] = a[0] ^ b[1] ^ a[2] ^ b[2] ^ a[3]; // a0 * 2*a1 + 3*a2 + a3
+ s[2][c] = a[0] ^ a[1] ^ b[2] ^ a[3] ^ b[3]; // a0 + a1 + 2*a2 + 3*a3
+ s[3][c] = a[0] ^ b[0] ^ a[1] ^ a[2] ^ b[3]; // 3*a0 + a1 + a2 + 2*a3
+ }
+ return s;
+ }
+
+
+ function AddRoundKey(state, w, rnd, Nb) { // xor Round Key into state S [§5.1.4]
+ for (var r=0; r<4; r++) {
+ for (var c=0; c<Nb; c++) state[r][c] ^= w[rnd*4+c][r];
+ }
+ return state;
+ }
+
+
+ function KeyExpansion(key) { // generate Key Schedule (byte-array Nr+1 x Nb) from Key [§5.2]
+ var Nb = 4; // block size (in words): no of columns in state (fixed at 4 for AES)
+ var Nk = key.length/4 // key length (in words): 4/6/8 for 128/192/256-bit keys
+ var Nr = Nk + 6; // no of rounds: 10/12/14 for 128/192/256-bit keys
+
+ var w = new Array(Nb*(Nr+1));
+ var temp = new Array(4);
+
+ for (var i=0; i<Nk; i++) {
+ var r = [key[4*i], key[4*i+1], key[4*i+2], key[4*i+3]];
+ w[i] = r;
+ }
+
+ for (var i=Nk; i<(Nb*(Nr+1)); i++) {
+ w[i] = new Array(4);
+ for (var t=0; t<4; t++) temp[t] = w[i-1][t];
+ if (i % Nk == 0) {
+ temp = SubWord(RotWord(temp));
+ for (var t=0; t<4; t++) temp[t] ^= Rcon[i/Nk][t];
+ } else if (Nk > 6 && i%Nk == 4) {
+ temp = SubWord(temp);
+ }
+ for (var t=0; t<4; t++) w[i][t] = w[i-Nk][t] ^ temp[t];
+ }
+
+ return w;
+ }
+
+ function SubWord(w) { // apply SBox to 4-byte word w
+ for (var i=0; i<4; i++) w[i] = Sbox[w[i]];
+ return w;
+ }
+
+ function RotWord(w) { // rotate 4-byte word w left by one byte
+ w[4] = w[0];
+ for (var i=0; i<4; i++) w[i] = w[i+1];
+ return w;
+ }
+
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
+
+ /*
+ * Use AES to encrypt 'plaintext' with 'password' using 'nBits' key, in 'Counter' mode of operation
+ * - see http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
+ * for each block
+ * - outputblock = cipher(counter, key)
+ * - cipherblock = plaintext xor outputblock
+ */
+ function AESEncryptCtr(plaintext, password, nBits) {
+ if (!(nBits==128 || nBits==192 || nBits==256)) return ''; // standard allows 128/192/256 bit keys
+
+ // for this example script, generate the key by applying Cipher to 1st 16/24/32 chars of password;
+ // for real-world applications, a more secure approach would be to hash the password e.g. with SHA-1
+ var nBytes = nBits/8; // no bytes in key
+ var pwBytes = new Array(nBytes);
+ for (var i=0; i<nBytes; i++) pwBytes[i] = password.charCodeAt(i) & 0xff;
+
+ var key = Cipher(pwBytes, KeyExpansion(pwBytes));
+
+ key = key.concat(key.slice(0, nBytes-16)); // key is now 16/24/32 bytes long
+
+ // initialise counter block (NIST SP800-38A §B.2): millisecond time-stamp for nonce in 1st 8 bytes,
+ // block counter in 2nd 8 bytes
+ var blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
+ var counterBlock = new Array(blockSize); // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
+ var nonce = (new Date()).getTime(); // milliseconds since 1-Jan-1970
+
+ // encode nonce in two stages to cater for JavaScript 32-bit limit on bitwise ops
+ for (var i=0; i<4; i++) counterBlock[i] = (nonce >>> i*8) & 0xff;
+ for (var i=0; i<4; i++) counterBlock[i+4] = (nonce/0x100000000 >>> i*8) & 0xff;
+
+ // generate key schedule - an expansion of the key into distinct Key Rounds for each round
+ var keySchedule = KeyExpansion(key);
+
+ var blockCount = Math.ceil(plaintext.length/blockSize);
+ var ciphertext = new Array(blockCount); // ciphertext as array of strings
+
+ for (var b=0; b<blockCount; b++) {
+ // set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
+ // again done in two stages for 32-bit ops
+ for (var c=0; c<4; c++) counterBlock[15-c] = (b >>> c*8) & 0xff;
+ for (var c=0; c<4; c++) counterBlock[15-c-4] = (b/0x100000000 >>> c*8)
+
+ var cipherCntr = Cipher(counterBlock, keySchedule); // -- encrypt counter block --
+
+ // calculate length of final block:
+ var blockLength = b<blockCount-1 ? blockSize : (plaintext.length-1)%blockSize+1;
+
+ var ct = '';
+ for (var i=0; i<blockLength; i++) { // -- xor plaintext with ciphered counter byte-by-byte --
+ var plaintextByte = plaintext.charCodeAt(b*blockSize+i);
+ var cipherByte = plaintextByte ^ cipherCntr[i];
+ ct += String.fromCharCode(cipherByte);
+ }
+ // ct is now ciphertext for this block
+
+ ciphertext[b] = escCtrlChars(ct); // escape troublesome characters in ciphertext
+ }
+
+ // convert the nonce to a string to go on the front of the ciphertext
+ var ctrTxt = '';
+ for (var i=0; i<8; i++) ctrTxt += String.fromCharCode(counterBlock[i]);
+ ctrTxt = escCtrlChars(ctrTxt);
+
+ // use '-' to separate blocks, use Array.join to concatenate arrays of strings for efficiency
+ return ctrTxt + '-' + ciphertext.join('-');
+ }
+
+
+ /*
+ * Use AES to decrypt 'ciphertext' with 'password' using 'nBits' key, in Counter mode of operation
+ *
+ * for each block
+ * - outputblock = cipher(counter, key)
+ * - cipherblock = plaintext xor outputblock
+ */
+ function AESDecryptCtr(ciphertext, password, nBits) {
+ if (!(nBits==128 || nBits==192 || nBits==256)) return ''; // standard allows 128/192/256 bit keys
+
+ var nBytes = nBits/8; // no bytes in key
+ var pwBytes = new Array(nBytes);
+ for (var i=0; i<nBytes; i++) pwBytes[i] = password.charCodeAt(i) & 0xff;
+ var pwKeySchedule = KeyExpansion(pwBytes);
+ var key = Cipher(pwBytes, pwKeySchedule);
+ key = key.concat(key.slice(0, nBytes-16)); // key is now 16/24/32 bytes long
+
+ var keySchedule = KeyExpansion(key);
+
+ ciphertext = ciphertext.split('-'); // split ciphertext into array of block-length strings
+
+ // recover nonce from 1st element of ciphertext
+ var blockSize = 16; // block size fixed at 16 bytes / 128 bits (Nb=4) for AES
+ var counterBlock = new Array(blockSize);
+ var ctrTxt = unescCtrlChars(ciphertext[0]);
+ for (var i=0; i<8; i++) counterBlock[i] = ctrTxt.charCodeAt(i);
+
+ var plaintext = new Array(ciphertext.length-1);
+
+ for (var b=1; b<ciphertext.length; b++) {
+ // set counter (block #) in last 8 bytes of counter block (leaving nonce in 1st 8 bytes)
+ for (var c=0; c<4; c++) counterBlock[15-c] = ((b-1) >>> c*8) & 0xff;
+ for (var c=0; c<4; c++) counterBlock[15-c-4] = ((b/0x100000000-1) >>> c*8) & 0xff;
+
+ var cipherCntr = Cipher(counterBlock, keySchedule); // encrypt counter block
+
+ ciphertext[b] = unescCtrlChars(ciphertext[b]);
+
+ var pt = '';
+ for (var i=0; i<ciphertext[b].length; i++) {
+ // -- xor plaintext with ciphered counter byte-by-byte --
+ var ciphertextByte = ciphertext[b].charCodeAt(i);
+ var plaintextByte = ciphertextByte ^ cipherCntr[i];
+ pt += String.fromCharCode(plaintextByte);
+ }
+ // pt is now plaintext for this block
+
+ plaintext[b-1] = pt; // b-1 'cos no initial nonce block in plaintext
+ }
+
+ return plaintext.join('');
+ }
+
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
+
+ function escCtrlChars(str) { // escape control chars which might cause problems handling ciphertext
+ return str.replace(/[\0\t\n\v\f\r\xa0!-]/g, function(c) { return '!' + c.charCodeAt(0) + '!'; });
+ } // \xa0 to cater for bug in Firefox; include '-' to leave it free for use as a block marker
+
+ function unescCtrlChars(str) { // unescape potentially problematic control characters
+ return str.replace(/!\d\d?\d?!/g, function(c) { return String.fromCharCode(c.slice(1,-1)); });
+ }
+
+ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
+
+ function encrypt(plaintext, password){
+ return AESEncryptCtr(plaintext, password, 256);
+ }
+
+ function decrypt(ciphertext, password){
+ return AESDecryptCtr(ciphertext, password, 256);
+ }
+
+ /* End AES Implementation */
+
+ var cmd = msg.substr(0,4);
+ var arg = msg.substr(5);
+ if(cmd == "encr"){
+ arg = eval("(" + arg + ")");
+ var plaintext = arg.plaintext;
+ var password = arg.password;
+ var results = encrypt(plaintext, password);
+ gearsWorkerPool.sendMessage(String(results), sender);
+ }else if(cmd == "decr"){
+ arg = eval("(" + arg + ")");
+ var ciphertext = arg.ciphertext;
+ var password = arg.password;
+ var results = decrypt(ciphertext, password);
+ gearsWorkerPool.sendMessage(String(results), sender);
+ }
+ }
+});
+
+}
+
+if(!dojo._hasResource["dojox.sql._base"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
+dojo._hasResource["dojox.sql._base"] = true;
+dojo.provide("dojox.sql._base");
+
+
+dojo.mixin(dojox.sql, {
+ // summary:
+ // Executes a SQL expression.
+ // description:
+ // There are four ways to call this:
+ // 1) Straight SQL: dojox.sql("SELECT * FROM FOOBAR");
+ // 2) SQL with parameters: dojox.sql("INSERT INTO FOOBAR VALUES (?)", someParam)
+ // 3) Encrypting particular values:
+ // dojox.sql("INSERT INTO FOOBAR VALUES (ENCRYPT(?))", someParam, "somePassword", callback)
+ // 4) Decrypting particular values:
+ // dojox.sql("SELECT DECRYPT(SOMECOL1), DECRYPT(SOMECOL2) FROM
+ // FOOBAR WHERE SOMECOL3 = ?", someParam,
+ // "somePassword", callback)
+ //
+ // For encryption and decryption the last two values should be the the password for
+ // encryption/decryption, and the callback function that gets the result set.
+ //
+ // Note: We only support ENCRYPT(?) statements, and
+ // and DECRYPT(*) statements for now -- you can not have a literal string
+ // inside of these, such as ENCRYPT('foobar')
+ //
+ // Note: If you have multiple columns to encrypt and decrypt, you can use the following
+ // convenience form to not have to type ENCRYPT(?)/DECRYPT(*) many times:
+ //
+ // dojox.sql("INSERT INTO FOOBAR VALUES (ENCRYPT(?, ?, ?))",
+ // someParam1, someParam2, someParam3,
+ // "somePassword", callback)
+ //
+ // dojox.sql("SELECT DECRYPT(SOMECOL1, SOMECOL2) FROM
+ // FOOBAR WHERE SOMECOL3 = ?", someParam,
+ // "somePassword", callback)
+
+ dbName: null,
+
+ // summary:
+ // If true, then we print out any SQL that is executed
+ // to the debug window
+ debug: (dojo.exists("dojox.sql.debug") ? dojox.sql.debug:false),
+
+ open: function(dbName){
+ if(this._dbOpen && (!dbName || dbName == this.dbName)){
+ return;
+ }
+
+ if(!this.dbName){
+ this.dbName = "dot_store_"
+ + window.location.href.replace(/[^0-9A-Za-z_]/g, "_");
+ // database names in Gears are limited to 64 characters long
+ if(this.dbName.length > 63){
+ this.dbName = this.dbName.substring(0, 63);
+ }
+ }
+
+ if(!dbName){
+ dbName = this.dbName;
+ }
+
+ try{
+ this._initDb();
+ this.db.open(dbName);
+ this._dbOpen = true;
+ }catch(exp){
+ throw exp.message||exp;
+ }
+ },
+
+ close: function(dbName){
+ // on Internet Explorer, Google Gears throws an exception
+ // "Object not a collection", when we try to close the
+ // database -- just don't close it on this platform
+ // since we are running into a Gears bug; the Gears team
+ // said it's ok to not close a database connection
+ if(dojo.isIE){ return; }
+
+ if(!this._dbOpen && (!dbName || dbName == this.dbName)){
+ return;
+ }
+
+ if(!dbName){
+ dbName = this.dbName;
+ }
+
+ try{
+ this.db.close(dbName);
+ this._dbOpen = false;
+ }catch(exp){
+ throw exp.message||exp;
+ }
+ },
+
+ _exec: function(params){
+ try{
+ // get the Gears Database object
+ this._initDb();
+
+ // see if we need to open the db; if programmer
+ // manually called dojox.sql.open() let them handle
+ // it; otherwise we open and close automatically on
+ // each SQL execution
+ if(!this._dbOpen){
+ this.open();
+ this._autoClose = true;
+ }
+
+ // determine our parameters
+ var sql = null;
+ var callback = null;
+ var password = null;
+
+ var args = dojo._toArray(params);
+
+ sql = args.splice(0, 1)[0];
+
+ // does this SQL statement use the ENCRYPT or DECRYPT
+ // keywords? if so, extract our callback and crypto
+ // password
+ if(this._needsEncrypt(sql) || this._needsDecrypt(sql)){
+ callback = args.splice(args.length - 1, 1)[0];
+ password = args.splice(args.length - 1, 1)[0];
+ }
+
+ // 'args' now just has the SQL parameters
+
+ // print out debug SQL output if the developer wants that
+ if(this.debug){
+ this._printDebugSQL(sql, args);
+ }
+
+ // handle SQL that needs encryption/decryption differently
+ // do we have an ENCRYPT SQL statement? if so, handle that first
+ var crypto;
+ if(this._needsEncrypt(sql)){
+ crypto = new dojox.sql._SQLCrypto("encrypt", sql,
+ password, args,
+ callback);
+ return null; // encrypted results will arrive asynchronously
+ }else if(this._needsDecrypt(sql)){ // otherwise we have a DECRYPT statement
+ crypto = new dojox.sql._SQLCrypto("decrypt", sql,
+ password, args,
+ callback);
+ return null; // decrypted results will arrive asynchronously
+ }
+
+ // execute the SQL and get the results
+ var rs = this.db.execute(sql, args);
+
+ // Gears ResultSet object's are ugly -- normalize
+ // these into something JavaScript programmers know
+ // how to work with, basically an array of
+ // JavaScript objects where each property name is
+ // simply the field name for a column of data
+ rs = this._normalizeResults(rs);
+
+ if(this._autoClose){
+ this.close();
+ }
+
+ return rs;
+ }catch(exp){
+ exp = exp.message||exp;
+
+
+
+ if(this._autoClose){
+ try{
+ this.close();
+ }catch(e){
+
+ }
+ }
+
+ throw exp;
+ }
+
+ return null;
+ },
+
+ _initDb: function(){
+ if(!this.db){
+ try{
+ this.db = google.gears.factory.create('beta.database', '1.0');
+ }catch(exp){
+ dojo.setObject("google.gears.denied", true);
+ if(dojox.off){
+ dojox.off.onFrameworkEvent("coreOperationFailed");
+ }
+ throw "Google Gears must be allowed to run";
+ }
+ }
+ },
+
+ _printDebugSQL: function(sql, args){
+ var msg = "dojox.sql(\"" + sql + "\"";
+ for(var i = 0; i < args.length; i++){
+ if(typeof args[i] == "string"){
+ msg += ", \"" + args[i] + "\"";
+ }else{
+ msg += ", " + args[i];
+ }
+ }
+ msg += ")";
+
+
+ },
+
+ _normalizeResults: function(rs){
+ var results = [];
+ if(!rs){ return []; }
+
+ while(rs.isValidRow()){
+ var row = {};
+
+ for(var i = 0; i < rs.fieldCount(); i++){
+ var fieldName = rs.fieldName(i);
+ var fieldValue = rs.field(i);
+ row[fieldName] = fieldValue;
+ }
+
+ results.push(row);
+
+ rs.next();
+ }
+
+ rs.close();
+
+ return results;
+ },
+
+ _needsEncrypt: function(sql){
+ return /encrypt\([^\)]*\)/i.test(sql);
+ },
+
+ _needsDecrypt: function(sql){
+ return /decrypt\([^\)]*\)/i.test(sql);
+ }
+});
+
+dojo.declare("dojox.sql._SQLCrypto", null, {
+ // summary:
+ // A private class encapsulating any cryptography that must be done
+ // on a SQL statement. We instantiate this class and have it hold
+ // it's state so that we can potentially have several encryption
+ // operations happening at the same time by different SQL statements.
+ constructor: function(action, sql, password, args, callback){
+ if(action == "encrypt"){
+ this._execEncryptSQL(sql, password, args, callback);
+ }else{
+ this._execDecryptSQL(sql, password, args, callback);
+ }
+ },
+
+ _execEncryptSQL: function(sql, password, args, callback){
+ // strip the ENCRYPT/DECRYPT keywords from the SQL
+ var strippedSQL = this._stripCryptoSQL(sql);
+
+ // determine what arguments need encryption
+ var encryptColumns = this._flagEncryptedArgs(sql, args);
+
+ // asynchronously encrypt each argument that needs it
+ var self = this;
+ this._encrypt(strippedSQL, password, args, encryptColumns, function(finalArgs){
+ // execute the SQL
+ var error = false;
+ var resultSet = [];
+ var exp = null;
+ try{
+ resultSet = dojox.sql.db.execute(strippedSQL, finalArgs);
+ }catch(execError){
+ error = true;
+ exp = execError.message||execError;
+ }
+
+ // was there an error during SQL execution?
+ if(exp != null){
+ if(dojox.sql._autoClose){
+ try{ dojox.sql.close(); }catch(e){}
+ }
+
+ callback(null, true, exp.toString());
+ return;
+ }
+
+ // normalize SQL results into a JavaScript object
+ // we can work with
+ resultSet = dojox.sql._normalizeResults(resultSet);
+
+ if(dojox.sql._autoClose){
+ dojox.sql.close();
+ }
+
+ // are any decryptions necessary on the result set?
+ if(dojox.sql._needsDecrypt(sql)){
+ // determine which of the result set columns needs decryption
+ var needsDecrypt = self._determineDecryptedColumns(sql);
+
+ // now decrypt columns asynchronously
+ // decrypt columns that need it
+ self._decrypt(resultSet, needsDecrypt, password, function(finalResultSet){
+ callback(finalResultSet, false, null);
+ });
+ }else{
+ callback(resultSet, false, null);
+ }
+ });
+ },
+
+ _execDecryptSQL: function(sql, password, args, callback){
+ // strip the ENCRYPT/DECRYPT keywords from the SQL
+ var strippedSQL = this._stripCryptoSQL(sql);
+
+ // determine which columns needs decryption; this either
+ // returns the value *, which means all result set columns will
+ // be decrypted, or it will return the column names that need
+ // decryption set on a hashtable so we can quickly test a given
+ // column name; the key is the column name that needs
+ // decryption and the value is 'true' (i.e. needsDecrypt["someColumn"]
+ // would return 'true' if it needs decryption, and would be 'undefined'
+ // or false otherwise)
+ var needsDecrypt = this._determineDecryptedColumns(sql);
+
+ // execute the SQL
+ var error = false;
+ var resultSet = [];
+ var exp = null;
+ try{
+ resultSet = dojox.sql.db.execute(strippedSQL, args);
+ }catch(execError){
+ error = true;
+ exp = execError.message||execError;
+ }
+
+ // was there an error during SQL execution?
+ if(exp != null){
+ if(dojox.sql._autoClose){
+ try{ dojox.sql.close(); }catch(e){}
+ }
+
+ callback(resultSet, true, exp.toString());
+ return;
+ }
+
+ // normalize SQL results into a JavaScript object
+ // we can work with
+ resultSet = dojox.sql._normalizeResults(resultSet);
+
+ if(dojox.sql._autoClose){
+ dojox.sql.close();
+ }
+
+ // decrypt columns that need it
+ this._decrypt(resultSet, needsDecrypt, password, function(finalResultSet){
+ callback(finalResultSet, false, null);
+ });
+ },
+
+ _encrypt: function(sql, password, args, encryptColumns, callback){
+ //
+
+ this._totalCrypto = 0;
+ this._finishedCrypto = 0;
+ this._finishedSpawningCrypto = false;
+ this._finalArgs = args;
+
+ for(var i = 0; i < args.length; i++){
+ if(encryptColumns[i]){
+ // we have an encrypt() keyword -- get just the value inside
+ // the encrypt() parantheses -- for now this must be a ?
+ var sqlParam = args[i];
+ var paramIndex = i;
+
+ // update the total number of encryptions we know must be done asynchronously
+ this._totalCrypto++;
+
+ // FIXME: This currently uses DES as a proof-of-concept since the
+ // DES code used is quite fast and was easy to work with. Modify dojox.sql
+ // to be able to specify a different encryption provider through a
+ // a SQL-like syntax, such as dojox.sql("SET ENCRYPTION BLOWFISH"),
+ // and modify the dojox.crypto.Blowfish code to be able to work using
+ // a Google Gears Worker Pool
+
+ // do the actual encryption now, asychronously on a Gears worker thread
+ dojox.sql._crypto.encrypt(sqlParam, password, dojo.hitch(this, function(results){
+ // set the new encrypted value
+ this._finalArgs[paramIndex] = results;
+ this._finishedCrypto++;
+ // are we done with all encryption?
+ if(this._finishedCrypto >= this._totalCrypto
+ && this._finishedSpawningCrypto){
+ callback(this._finalArgs);
+ }
+ }));
+ }
+ }
+
+ this._finishedSpawningCrypto = true;
+ },
+
+ _decrypt: function(resultSet, needsDecrypt, password, callback){
+ //
+
+ this._totalCrypto = 0;
+ this._finishedCrypto = 0;
+ this._finishedSpawningCrypto = false;
+ this._finalResultSet = resultSet;
+
+ for(var i = 0; i < resultSet.length; i++){
+ var row = resultSet[i];
+
+ // go through each of the column names in row,
+ // seeing if they need decryption
+ for(var columnName in row){
+ if(needsDecrypt == "*" || needsDecrypt[columnName]){
+ this._totalCrypto++;
+ var columnValue = row[columnName];
+
+ // forming a closure here can cause issues, with values not cleanly
+ // saved on Firefox/Mac OS X for some of the values above that
+ // are needed in the callback below; call a subroutine that will form
+ // a closure inside of itself instead
+ this._decryptSingleColumn(columnName, columnValue, password, i,
+ function(finalResultSet){
+ callback(finalResultSet);
+ });
+ }
+ }
+ }
+
+ this._finishedSpawningCrypto = true;
+ },
+
+ _stripCryptoSQL: function(sql){
+ // replace all DECRYPT(*) occurrences with a *
+ sql = sql.replace(/DECRYPT\(\*\)/ig, "*");
+
+ // match any ENCRYPT(?, ?, ?, etc) occurrences,
+ // then replace with just the question marks in the
+ // middle
+ var matches = sql.match(/ENCRYPT\([^\)]*\)/ig);
+ if(matches != null){
+ for(var i = 0; i < matches.length; i++){
+ var encryptStatement = matches[i];
+ var encryptValue = encryptStatement.match(/ENCRYPT\(([^\)]*)\)/i)[1];
+ sql = sql.replace(encryptStatement, encryptValue);
+ }
+ }
+
+ // match any DECRYPT(COL1, COL2, etc) occurrences,
+ // then replace with just the column names
+ // in the middle
+ matches = sql.match(/DECRYPT\([^\)]*\)/ig);
+ if(matches != null){
+ for(i = 0; i < matches.length; i++){
+ var decryptStatement = matches[i];
+ var decryptValue = decryptStatement.match(/DECRYPT\(([^\)]*)\)/i)[1];
+ sql = sql.replace(decryptStatement, decryptValue);
+ }
+ }
+
+ return sql;
+ },
+
+ _flagEncryptedArgs: function(sql, args){
+ // capture literal strings that have question marks in them,
+ // and also capture question marks that stand alone
+ var tester = new RegExp(/([\"][^\"]*\?[^\"]*[\"])|([\'][^\']*\?[^\']*[\'])|(\?)/ig);
+ var matches;
+ var currentParam = 0;
+ var results = [];
+ while((matches = tester.exec(sql)) != null){
+ var currentMatch = RegExp.lastMatch+"";
+
+ // are we a literal string? then ignore it
+ if(/^[\"\']/.test(currentMatch)){
+ continue;
+ }
+
+ // do we have an encrypt keyword to our left?
+ var needsEncrypt = false;
+ if(/ENCRYPT\([^\)]*$/i.test(RegExp.leftContext)){
+ needsEncrypt = true;
+ }
+
+ // set the encrypted flag
+ results[currentParam] = needsEncrypt;
+
+ currentParam++;
+ }
+
+ return results;
+ },
+
+ _determineDecryptedColumns: function(sql){
+ var results = {};
+
+ if(/DECRYPT\(\*\)/i.test(sql)){
+ results = "*";
+ }else{
+ var tester = /DECRYPT\((?:\s*\w*\s*\,?)*\)/ig;
+ var matches = tester.exec(sql);
+ while(matches){
+ var lastMatch = new String(RegExp.lastMatch);
+ var columnNames = lastMatch.replace(/DECRYPT\(/i, "");
+ columnNames = columnNames.replace(/\)/, "");
+ columnNames = columnNames.split(/\s*,\s*/);
+ dojo.forEach(columnNames, function(column){
+ if(/\s*\w* AS (\w*)/i.test(column)){
+ column = column.match(/\s*\w* AS (\w*)/i)[1];
+ }
+ results[column] = true;
+ });
+
+ matches = tester.exec(sql)
+ }
+ }
+
+ return results;
+ },
+
+ _decryptSingleColumn: function(columnName, columnValue, password, currentRowIndex,
+ callback){
+ //
+ dojox.sql._crypto.decrypt(columnValue, password, dojo.hitch(this, function(results){
+ // set the new decrypted value
+ this._finalResultSet[currentRowIndex][columnName] = results;
+ this._finishedCrypto++;
+
+ // are we done with all encryption?
+ if(this._finishedCrypto >= this._totalCrypto
+ && this._finishedSpawningCrypto){
+ //
+ callback(this._finalResultSet);
+ }
+ }));
+ }
+});
+
+(function(){
+
+ var orig_sql = dojox.sql;
+ dojox.sql = new Function("return dojox.sql._exec(arguments);");
+ dojo.mixin(dojox.sql, orig_sql);
+
+})();
+
+}
+
+if(!dojo._hasResource["dojox.sql"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
+dojo._hasResource["dojox.sql"] = true;
+dojo.provide("dojox.sql");
+
+
+}
+
+if(!dojo._hasResource["dojox.storage.GearsStorageProvider"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
+dojo._hasResource["dojox.storage.GearsStorageProvider"] = true;
+dojo.provide("dojox.storage.GearsStorageProvider");
+
+
+
+
+
+if(dojo.gears.available){
+
+ (function(){
+ // make sure we don't define the gears provider if we're not gears
+ // enabled
+
+ dojo.declare("dojox.storage.GearsStorageProvider", dojox.storage.Provider, {
+ // summary:
+ // Storage provider that uses the features of Google Gears
+ // to store data (it is saved into the local SQL database
+ // provided by Gears, using dojox.sql)
+ // description:
+ // You can disable this storage provider with the following djConfig
+ // variable:
+ // var djConfig = { disableGearsStorage: true };
+ //
+ // Authors of this storage provider-
+ // Brad Neuberg, bkn3@columbia.edu
+ constructor: function(){
+ },
+ // instance methods and properties
+ TABLE_NAME: "__DOJO_STORAGE",
+ initialized: false,
+
+ _available: null,
+ _storageReady: false,
+
+ initialize: function(){
+ //
+ if(dojo.config["disableGearsStorage"] == true){
+ return;
+ }
+
+ // partition our storage data so that multiple apps
+ // on the same host won't collide
+ this.TABLE_NAME = "__DOJO_STORAGE";
+
+ // we delay creating our internal tables until an operation is
+ // actually called, to avoid having a Gears permission dialog
+ // on page load (bug #7538)
+
+ // indicate that this storage provider is now loaded
+ this.initialized = true;
+ dojox.storage.manager.loaded();
+ },
+
+ isAvailable: function(){
+ // is Google Gears available and defined?
+ return this._available = dojo.gears.available;
+ },
+
+ put: function(key, value, resultsHandler, namespace){
+ this._initStorage();
+
+ if(!this.isValidKey(key)){
+ throw new Error("Invalid key given: " + key);
+ }
+
+ namespace = namespace||this.DEFAULT_NAMESPACE;
+ if(!this.isValidKey(namespace)){
+ throw new Error("Invalid namespace given: " + key);
+ }
+
+ // serialize the value;
+ // handle strings differently so they have better performance
+ if(dojo.isString(value)){
+ value = "string:" + value;
+ }else{
+ value = dojo.toJson(value);
+ }
+
+ // try to store the value
+ try{
+ dojox.sql("DELETE FROM " + this.TABLE_NAME
+ + " WHERE namespace = ? AND key = ?",
+ namespace, key);
+ dojox.sql("INSERT INTO " + this.TABLE_NAME
+ + " VALUES (?, ?, ?)",
+ namespace, key, value);
+ }catch(e){
+ // indicate we failed
+
+ resultsHandler(this.FAILED, key, e.toString(), namespace);
+ return;
+ }
+
+ if(resultsHandler){
+ resultsHandler(dojox.storage.SUCCESS, key, null, namespace);
+ }
+ },
+
+ get: function(key, namespace){
+ this._initStorage();
+
+ if(!this.isValidKey(key)){
+ throw new Error("Invalid key given: " + key);
+ }
+
+ namespace = namespace||this.DEFAULT_NAMESPACE;
+ if(!this.isValidKey(namespace)){
+ throw new Error("Invalid namespace given: " + key);
+ }
+
+ // try to find this key in the database
+ var results = dojox.sql("SELECT * FROM " + this.TABLE_NAME
+ + " WHERE namespace = ? AND "
+ + " key = ?",
+ namespace, key);
+ if(!results.length){
+ return null;
+ }else{
+ results = results[0].value;
+ }
+
+ // destringify the content back into a
+ // real JavaScript object;
+ // handle strings differently so they have better performance
+ if(dojo.isString(results) && (/^string:/.test(results))){
+ results = results.substring("string:".length);
+ }else{
+ results = dojo.fromJson(results);
+ }
+
+ return results;
+ },
+
+ getNamespaces: function(){
+ this._initStorage();
+
+ var results = [ dojox.storage.DEFAULT_NAMESPACE ];
+
+ var rs = dojox.sql("SELECT namespace FROM " + this.TABLE_NAME
+ + " DESC GROUP BY namespace");
+ for(var i = 0; i < rs.length; i++){
+ if(rs[i].namespace != dojox.storage.DEFAULT_NAMESPACE){
+ results.push(rs[i].namespace);
+ }
+ }
+
+ return results;
+ },
+
+ getKeys: function(namespace){
+ this._initStorage();
+
+ namespace = namespace||this.DEFAULT_NAMESPACE;
+ if(!this.isValidKey(namespace)){
+ throw new Error("Invalid namespace given: " + namespace);
+ }
+
+ var rs = dojox.sql("SELECT key FROM " + this.TABLE_NAME
+ + " WHERE namespace = ?",
+ namespace);
+
+ var results = [];
+ for(var i = 0; i < rs.length; i++){
+ results.push(rs[i].key);
+ }
+
+ return results;
+ },
+
+ clear: function(namespace){
+ this._initStorage();
+
+ namespace = namespace||this.DEFAULT_NAMESPACE;
+ if(!this.isValidKey(namespace)){
+ throw new Error("Invalid namespace given: " + namespace);
+ }
+
+ dojox.sql("DELETE FROM " + this.TABLE_NAME
+ + " WHERE namespace = ?",
+ namespace);
+ },
+
+ remove: function(key, namespace){
+ this._initStorage();
+
+ if(!this.isValidKey(key)){
+ throw new Error("Invalid key given: " + key);
+ }
+
+ namespace = namespace||this.DEFAULT_NAMESPACE;
+ if(!this.isValidKey(namespace)){
+ throw new Error("Invalid namespace given: " + key);
+ }
+
+ dojox.sql("DELETE FROM " + this.TABLE_NAME
+ + " WHERE namespace = ? AND"
+ + " key = ?",
+ namespace,
+ key);
+ },
+
+ putMultiple: function(keys, values, resultsHandler, namespace) {
+ this._initStorage();
+
+ if(!this.isValidKeyArray(keys)
+ || ! values instanceof Array
+ || keys.length != values.length){
+ throw new Error("Invalid arguments: keys = ["
+ + keys + "], values = [" + values + "]");
+ }
+
+ if(namespace == null || typeof namespace == "undefined"){
+ namespace = dojox.storage.DEFAULT_NAMESPACE;
+ }
+ if(!this.isValidKey(namespace)){
+ throw new Error("Invalid namespace given: " + namespace);
+ }
+
+ this._statusHandler = resultsHandler;
+
+ // try to store the value
+ try{
+ dojox.sql.open();
+ dojox.sql.db.execute("BEGIN TRANSACTION");
+ var _stmt = "REPLACE INTO " + this.TABLE_NAME + " VALUES (?, ?, ?)";
+ for(var i=0;i<keys.length;i++) {
+ // serialize the value;
+ // handle strings differently so they have better performance
+ var value = values[i];
+ if(dojo.isString(value)){
+ value = "string:" + value;
+ }else{
+ value = dojo.toJson(value);
+ }
+
+ dojox.sql.db.execute( _stmt,
+ [namespace, keys[i], value]);
+ }
+ dojox.sql.db.execute("COMMIT TRANSACTION");
+ dojox.sql.close();
+ }catch(e){
+ // indicate we failed
+
+ if(resultsHandler){
+ resultsHandler(this.FAILED, keys, e.toString(), namespace);
+ }
+ return;
+ }
+
+ if(resultsHandler){
+ resultsHandler(dojox.storage.SUCCESS, keys, null, namespace);
+ }
+ },
+
+ getMultiple: function(keys, namespace){
+ // TODO: Maybe use SELECT IN instead
+ this._initStorage();
+
+ if(!this.isValidKeyArray(keys)){
+ throw new ("Invalid key array given: " + keys);
+ }
+
+ if(namespace == null || typeof namespace == "undefined"){
+ namespace = dojox.storage.DEFAULT_NAMESPACE;
+ }
+ if(!this.isValidKey(namespace)){
+ throw new Error("Invalid namespace given: " + namespace);
+ }
+
+ var _stmt = "SELECT * FROM " + this.TABLE_NAME
+ + " WHERE namespace = ? AND " + " key = ?";
+
+ var results = [];
+ for(var i=0;i<keys.length;i++){
+ var result = dojox.sql( _stmt, namespace, keys[i]);
+
+ if( ! result.length){
+ results[i] = null;
+ }else{
+ result = result[0].value;
+
+ // destringify the content back into a
+ // real JavaScript object;
+ // handle strings differently so they have better performance
+ if(dojo.isString(result) && (/^string:/.test(result))){
+ results[i] = result.substring("string:".length);
+ }else{
+ results[i] = dojo.fromJson(result);
+ }
+ }
+ }
+
+ return results;
+ },
+
+ removeMultiple: function(keys, namespace){
+ this._initStorage();
+
+ if(!this.isValidKeyArray(keys)){
+ throw new Error("Invalid arguments: keys = [" + keys + "]");
+ }
+
+ if(namespace == null || typeof namespace == "undefined"){
+ namespace = dojox.storage.DEFAULT_NAMESPACE;
+ }
+ if(!this.isValidKey(namespace)){
+ throw new Error("Invalid namespace given: " + namespace);
+ }
+
+ dojox.sql.open();
+ dojox.sql.db.execute("BEGIN TRANSACTION");
+ var _stmt = "DELETE FROM " + this.TABLE_NAME
+ + " WHERE namespace = ? AND key = ?";
+
+ for(var i=0;i<keys.length;i++){
+ dojox.sql.db.execute( _stmt,
+ [namespace, keys[i]]);
+ }
+ dojox.sql.db.execute("COMMIT TRANSACTION");
+ dojox.sql.close();
+ },
+
+ isPermanent: function(){ return true; },
+
+ getMaximumSize: function(){ return this.SIZE_NO_LIMIT; },
+
+ hasSettingsUI: function(){ return false; },
+
+ showSettingsUI: function(){
+ throw new Error(this.declaredClass
+ + " does not support a storage settings user-interface");
+ },
+
+ hideSettingsUI: function(){
+ throw new Error(this.declaredClass
+ + " does not support a storage settings user-interface");
+ },
+
+ _initStorage: function(){
+ // we delay creating the tables until an operation is actually
+ // called so that we don't give a Gears dialog right on page
+ // load (bug #7538)
+ if (this._storageReady) {
+ return;
+ }
+
+ if (!google.gears.factory.hasPermission) {
+ var siteName = null;
+ var icon = null;
+ var msg = 'This site would like to use Google Gears to enable '
+ + 'enhanced functionality.';
+ var allowed = google.gears.factory.getPermission(siteName, icon, msg);
+ if (!allowed) {
+ throw new Error('You must give permission to use Gears in order to '
+ + 'store data');
+ }
+ }
+
+ // create the table that holds our data
+ try{
+ dojox.sql("CREATE TABLE IF NOT EXISTS " + this.TABLE_NAME + "( "
+ + " namespace TEXT, "
+ + " key TEXT, "
+ + " value TEXT "
+ + ")"
+ );
+ dojox.sql("CREATE UNIQUE INDEX IF NOT EXISTS namespace_key_index"
+ + " ON " + this.TABLE_NAME
+ + " (namespace, key)");
+ }catch(e){
+
+ throw new Error('Unable to create storage tables for Gears in '
+ + 'Dojo Storage');
+ }
+
+ this._storageReady = true;
+ }
+ });
+
+ // register the existence of our storage providers
+ dojox.storage.manager.register("dojox.storage.GearsStorageProvider",
+ new dojox.storage.GearsStorageProvider());
+ })();
+}
+
+}
+
+if(!dojo._hasResource["dojox.storage.WhatWGStorageProvider"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
+dojo._hasResource["dojox.storage.WhatWGStorageProvider"] = true;
+dojo.provide("dojox.storage.WhatWGStorageProvider");
+
+
+
+dojo.declare("dojox.storage.WhatWGStorageProvider", [ dojox.storage.Provider ], {
+ // summary:
+ // Storage provider that uses WHAT Working Group features in Firefox 2
+ // to achieve permanent storage.
+ // description:
+ // The WHAT WG storage API is documented at
+ // http://www.whatwg.org/specs/web-apps/current-work/#scs-client-side
+ //
+ // You can disable this storage provider with the following djConfig
+ // variable:
+ // var djConfig = { disableWhatWGStorage: true };
+ //
+ // Authors of this storage provider-
+ // JB Boisseau, jb.boisseau@eutech-ssii.com
+ // Brad Neuberg, bkn3@columbia.edu
+
+ initialized: false,
+
+ _domain: null,
+ _available: null,
+ _statusHandler: null,
+ _allNamespaces: null,
+ _storageEventListener: null,
+
+ initialize: function(){
+ if(dojo.config["disableWhatWGStorage"] == true){
+ return;
+ }
+
+ // get current domain
+ this._domain = this._getDomain();
+ //
+
+ // indicate that this storage provider is now loaded
+ this.initialized = true;
+ dojox.storage.manager.loaded();
+ },
+
+ isAvailable: function(){
+ try{
+ var myStorage = globalStorage[this._getDomain()];
+ }catch(e){
+ this._available = false;
+ return this._available;
+ }
+
+ this._available = true;
+ return this._available;
+ },
+
+ put: function(key, value, resultsHandler, namespace){
+ if(this.isValidKey(key) == false){
+ throw new Error("Invalid key given: " + key);
+ }
+ namespace = namespace||this.DEFAULT_NAMESPACE;
+
+ // get our full key name, which is namespace + key
+ key = this.getFullKey(key, namespace);
+
+ this._statusHandler = resultsHandler;
+
+ // serialize the value;
+ // handle strings differently so they have better performance
+ if(dojo.isString(value)){
+ value = "string:" + value;
+ }else{
+ value = dojo.toJson(value);
+ }
+
+ // register for successful storage events.
+ var storageListener = dojo.hitch(this, function(evt){
+ // remove any old storage event listener we might have added
+ // to the window on old put() requests; Firefox has a bug
+ // where it can occassionaly go into infinite loops calling
+ // our storage event listener over and over -- this is a
+ // workaround
+ // FIXME: Simplify this into a test case and submit it
+ // to Firefox
+ window.removeEventListener("storage", storageListener, false);
+
+ // indicate we succeeded
+ if(resultsHandler){
+ resultsHandler.call(null, this.SUCCESS, key, null, namespace);
+ }
+ });
+
+ window.addEventListener("storage", storageListener, false);
+
+ // try to store the value
+ try{
+ var myStorage = globalStorage[this._domain];
+ myStorage.setItem(key, value);
+ }catch(e){
+ // indicate we failed
+ this._statusHandler.call(null, this.FAILED, key, e.toString(), namespace);
+ }
+ },
+
+ get: function(key, namespace){
+ if(this.isValidKey(key) == false){
+ throw new Error("Invalid key given: " + key);
+ }
+ namespace = namespace||this.DEFAULT_NAMESPACE;
+
+ // get our full key name, which is namespace + key
+ key = this.getFullKey(key, namespace);
+
+ // sometimes, even if a key doesn't exist, Firefox
+ // will return a blank string instead of a null --
+ // this _might_ be due to having underscores in the
+ // keyname, but I am not sure.
+
+ // FIXME: Simplify this bug into a testcase and
+ // submit it to Firefox
+ var myStorage = globalStorage[this._domain];
+ var results = myStorage.getItem(key);
+
+ if(results == null || results == ""){
+ return null;
+ }
+
+ results = results.value;
+
+ // destringify the content back into a
+ // real JavaScript object;
+ // handle strings differently so they have better performance
+ if(dojo.isString(results) && (/^string:/.test(results))){
+ results = results.substring("string:".length);
+ }else{
+ results = dojo.fromJson(results);
+ }
+
+ return results;
+ },
+
+ getNamespaces: function(){
+ var results = [ this.DEFAULT_NAMESPACE ];
+
+ // simply enumerate through our array and save any string
+ // that starts with __
+ var found = {};
+ var myStorage = globalStorage[this._domain];
+ var tester = /^__([^_]*)_/;
+ for(var i = 0; i < myStorage.length; i++){
+ var currentKey = myStorage.key(i);
+ if(tester.test(currentKey) == true){
+ var currentNS = currentKey.match(tester)[1];
+ // have we seen this namespace before?
+ if(typeof found[currentNS] == "undefined"){
+ found[currentNS] = true;
+ results.push(currentNS);
+ }
+ }
+ }
+
+ return results;
+ },
+
+ getKeys: function(namespace){
+ namespace = namespace||this.DEFAULT_NAMESPACE;
+
+ if(this.isValidKey(namespace) == false){
+ throw new Error("Invalid namespace given: " + namespace);
+ }
+
+ // create a regular expression to test the beginning
+ // of our key names to see if they match our namespace;
+ // if it is the default namespace then test for the presence
+ // of no namespace for compatibility with older versions
+ // of dojox.storage
+ var namespaceTester;
+ if(namespace == this.DEFAULT_NAMESPACE){
+ namespaceTester = new RegExp("^([^_]{2}.*)$");
+ }else{
+ namespaceTester = new RegExp("^__" + namespace + "_(.*)$");
+ }
+
+ var myStorage = globalStorage[this._domain];
+ var keysArray = [];
+ for(var i = 0; i < myStorage.length; i++){
+ var currentKey = myStorage.key(i);
+ if(namespaceTester.test(currentKey) == true){
+ // strip off the namespace portion
+ currentKey = currentKey.match(namespaceTester)[1];
+ keysArray.push(currentKey);
+ }
+ }
+
+ return keysArray;
+ },
+
+ clear: function(namespace){
+ namespace = namespace||this.DEFAULT_NAMESPACE;
+
+ if(this.isValidKey(namespace) == false){
+ throw new Error("Invalid namespace given: " + namespace);
+ }
+
+ // create a regular expression to test the beginning
+ // of our key names to see if they match our namespace;
+ // if it is the default namespace then test for the presence
+ // of no namespace for compatibility with older versions
+ // of dojox.storage
+ var namespaceTester;
+ if(namespace == this.DEFAULT_NAMESPACE){
+ namespaceTester = new RegExp("^[^_]{2}");
+ }else{
+ namespaceTester = new RegExp("^__" + namespace + "_");
+ }
+
+ var myStorage = globalStorage[this._domain];
+ var keys = [];
+ for(var i = 0; i < myStorage.length; i++){
+ if(namespaceTester.test(myStorage.key(i)) == true){
+ keys[keys.length] = myStorage.key(i);
+ }
+ }
+
+ dojo.forEach(keys, dojo.hitch(myStorage, "removeItem"));
+ },
+
+ remove: function(key, namespace){
+ // get our full key name, which is namespace + key
+ key = this.getFullKey(key, namespace);
+
+ var myStorage = globalStorage[this._domain];
+ myStorage.removeItem(key);
+ },
+
+ isPermanent: function(){
+ return true;
+ },
+
+ getMaximumSize: function(){
+ return this.SIZE_NO_LIMIT;
+ },
+
+ hasSettingsUI: function(){
+ return false;
+ },
+
+ showSettingsUI: function(){
+ throw new Error(this.declaredClass + " does not support a storage settings user-interface");
+ },
+
+ hideSettingsUI: function(){
+ throw new Error(this.declaredClass + " does not support a storage settings user-interface");
+ },
+
+ getFullKey: function(key, namespace){
+ namespace = namespace||this.DEFAULT_NAMESPACE;
+
+ if(this.isValidKey(namespace) == false){
+ throw new Error("Invalid namespace given: " + namespace);
+ }
+
+ // don't append a namespace string for the default namespace,
+ // for compatibility with older versions of dojox.storage
+ if(namespace == this.DEFAULT_NAMESPACE){
+ return key;
+ }else{
+ return "__" + namespace + "_" + key;
+ }
+ },
+
+ _getDomain: function(){
+ // see: https://bugzilla.mozilla.org/show_bug.cgi?id=357323
+ return ((location.hostname == "localhost" && dojo.isFF && dojo.isFF < 3) ? "localhost.localdomain" : location.hostname);
+ }
+});
+
+dojox.storage.manager.register("dojox.storage.WhatWGStorageProvider",
+ new dojox.storage.WhatWGStorageProvider());
+
+}
+
+if(!dojo._hasResource["dojo.AdapterRegistry"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
+dojo._hasResource["dojo.AdapterRegistry"] = true;
+dojo.provide("dojo.AdapterRegistry");
+
+dojo.AdapterRegistry = function(/*Boolean?*/ returnWrappers){
+ // summary:
+ // A registry to make contextual calling/searching easier.
+ // description:
+ // Objects of this class keep list of arrays in the form [name, check,
+ // wrap, directReturn] that are used to determine what the contextual
+ // result of a set of checked arguments is. All check/wrap functions
+ // in this registry should be of the same arity.
+ // example:
+ // | // create a new registry
+ // | var reg = new dojo.AdapterRegistry();
+ // | reg.register("handleString",
+ // | dojo.isString,
+ // | function(str){
+ // | // do something with the string here
+ // | }
+ // | );
+ // | reg.register("handleArr",
+ // | dojo.isArray,
+ // | function(arr){
+ // | // do something with the array here
+ // | }
+ // | );
+ // |
+ // | // now we can pass reg.match() *either* an array or a string and
+ // | // the value we pass will get handled by the right function
+ // | reg.match("someValue"); // will call the first function
+ // | reg.match(["someValue"]); // will call the second
+
+ this.pairs = [];
+ this.returnWrappers = returnWrappers || false; // Boolean
+}
+
+dojo.extend(dojo.AdapterRegistry, {
+ register: function(/*String*/ name, /*Function*/ check, /*Function*/ wrap, /*Boolean?*/ directReturn, /*Boolean?*/ override){
+ // summary:
+ // register a check function to determine if the wrap function or
+ // object gets selected
+ // name:
+ // a way to identify this matcher.
+ // check:
+ // a function that arguments are passed to from the adapter's
+ // match() function. The check function should return true if the
+ // given arguments are appropriate for the wrap function.
+ // directReturn:
+ // If directReturn is true, the value passed in for wrap will be
+ // returned instead of being called. Alternately, the
+ // AdapterRegistry can be set globally to "return not call" using
+ // the returnWrappers property. Either way, this behavior allows
+ // the registry to act as a "search" function instead of a
+ // function interception library.
+ // override:
+ // If override is given and true, the check function will be given
+ // highest priority. Otherwise, it will be the lowest priority
+ // adapter.
+ this.pairs[((override) ? "unshift" : "push")]([name, check, wrap, directReturn]);
+ },
+
+ match: function(/* ... */){
+ // summary:
+ // Find an adapter for the given arguments. If no suitable adapter
+ // is found, throws an exception. match() accepts any number of
+ // arguments, all of which are passed to all matching functions
+ // from the registered pairs.
+ for(var i = 0; i < this.pairs.length; i++){
+ var pair = this.pairs[i];
+ if(pair[1].apply(this, arguments)){
+ if((pair[3])||(this.returnWrappers)){
+ return pair[2];
+ }else{
+ return pair[2].apply(this, arguments);
+ }
+ }
+ }
+ throw new Error("No match found");
+ },
+
+ unregister: function(name){
+ // summary: Remove a named adapter from the registry
+
+ // FIXME: this is kind of a dumb way to handle this. On a large
+ // registry this will be slow-ish and we can use the name as a lookup
+ // should we choose to trade memory for speed.
+ for(var i = 0; i < this.pairs.length; i++){
+ var pair = this.pairs[i];
+ if(pair[0] == name){
+ this.pairs.splice(i, 1);
+ return true;
+ }
+ }
+ return false;
+ }
+});
+
+}
+
+if(!dojo._hasResource["dijit._base.place"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
+dojo._hasResource["dijit._base.place"] = true;
+dojo.provide("dijit._base.place");
+
+
+
+// ported from dojo.html.util
+
+dijit.getViewport = function(){
+ // summary:
+ // Returns the dimensions and scroll position of the viewable area of a browser window
+
+ var scrollRoot = (dojo.doc.compatMode == 'BackCompat')? dojo.body() : dojo.doc.documentElement;
+
+ // get scroll position
+ var scroll = dojo._docScroll(); // scrollRoot.scrollTop/Left should work
+ return { w: scrollRoot.clientWidth, h: scrollRoot.clientHeight, l: scroll.x, t: scroll.y };
+};
+
+/*=====
+dijit.__Position = function(){
+ // x: Integer
+ // horizontal coordinate in pixels, relative to document body
+ // y: Integer
+ // vertical coordinate in pixels, relative to document body
+
+ thix.x = x;
+ this.y = y;
+}
+=====*/
+
+
+dijit.placeOnScreen = function(
+ /* DomNode */ node,
+ /* dijit.__Position */ pos,
+ /* String[] */ corners,
+ /* dijit.__Position? */ padding){
+ // summary:
+ // Positions one of the node's corners at specified position
+ // such that node is fully visible in viewport.
+ // description:
+ // NOTE: node is assumed to be absolutely or relatively positioned.
+ // pos:
+ // Object like {x: 10, y: 20}
+ // corners:
+ // Array of Strings representing order to try corners in, like ["TR", "BL"].
+ // Possible values are:
+ // * "BL" - bottom left
+ // * "BR" - bottom right
+ // * "TL" - top left
+ // * "TR" - top right
+ // padding:
+ // set padding to put some buffer around the element you want to position.
+ // example:
+ // Try to place node's top right corner at (10,20).
+ // If that makes node go (partially) off screen, then try placing
+ // bottom left corner at (10,20).
+ // | placeOnScreen(node, {x: 10, y: 20}, ["TR", "BL"])
+
+ var choices = dojo.map(corners, function(corner){
+ var c = { corner: corner, pos: {x:pos.x,y:pos.y} };
+ if(padding){
+ c.pos.x += corner.charAt(1) == 'L' ? padding.x : -padding.x;
+ c.pos.y += corner.charAt(0) == 'T' ? padding.y : -padding.y;
+ }
+ return c;
+ });
+
+ return dijit._place(node, choices);
+}
+
+dijit._place = function(/*DomNode*/ node, /* Array */ choices, /* Function */ layoutNode){
+ // summary:
+ // Given a list of spots to put node, put it at the first spot where it fits,
+ // of if it doesn't fit anywhere then the place with the least overflow
+ // choices: Array
+ // Array of elements like: {corner: 'TL', pos: {x: 10, y: 20} }
+ // Above example says to put the top-left corner of the node at (10,20)
+ // layoutNode: Function(node, aroundNodeCorner, nodeCorner)
+ // for things like tooltip, they are displayed differently (and have different dimensions)
+ // based on their orientation relative to the parent. This adjusts the popup based on orientation.
+
+ // get {x: 10, y: 10, w: 100, h:100} type obj representing position of
+ // viewport over document
+ var view = dijit.getViewport();
+
+ // This won't work if the node is inside a <div style="position: relative">,
+ // so reattach it to dojo.doc.body. (Otherwise, the positioning will be wrong
+ // and also it might get cutoff)
+ if(!node.parentNode || String(node.parentNode.tagName).toLowerCase() != "body"){
+ dojo.body().appendChild(node);
+ }
+
+ var best = null;
+ dojo.some(choices, function(choice){
+ var corner = choice.corner;
+ var pos = choice.pos;
+
+ // configure node to be displayed in given position relative to button
+ // (need to do this in order to get an accurate size for the node, because
+ // a tooltips size changes based on position, due to triangle)
+ if(layoutNode){
+ layoutNode(node, choice.aroundCorner, corner);
+ }
+
+ // get node's size
+ var style = node.style;
+ var oldDisplay = style.display;
+ var oldVis = style.visibility;
+ style.visibility = "hidden";
+ style.display = "";
+ var mb = dojo.marginBox(node);
+ style.display = oldDisplay;
+ style.visibility = oldVis;
+
+ // coordinates and size of node with specified corner placed at pos,
+ // and clipped by viewport
+ var startX = (corner.charAt(1) == 'L' ? pos.x : Math.max(view.l, pos.x - mb.w)),
+ startY = (corner.charAt(0) == 'T' ? pos.y : Math.max(view.t, pos.y - mb.h)),
+ endX = (corner.charAt(1) == 'L' ? Math.min(view.l + view.w, startX + mb.w) : pos.x),
+ endY = (corner.charAt(0) == 'T' ? Math.min(view.t + view.h, startY + mb.h) : pos.y),
+ width = endX - startX,
+ height = endY - startY,
+ overflow = (mb.w - width) + (mb.h - height);
+
+ if(best == null || overflow < best.overflow){
+ best = {
+ corner: corner,
+ aroundCorner: choice.aroundCorner,
+ x: startX,
+ y: startY,
+ w: width,
+ h: height,
+ overflow: overflow
+ };
+ }
+ return !overflow;
+ });
+
+ node.style.left = best.x + "px";
+ node.style.top = best.y + "px";
+ if(best.overflow && layoutNode){
+ layoutNode(node, best.aroundCorner, best.corner);
+ }
+ return best;
+}
+
+dijit.placeOnScreenAroundNode = function(
+ /* DomNode */ node,
+ /* DomNode */ aroundNode,
+ /* Object */ aroundCorners,
+ /* Function? */ layoutNode){
+
+ // summary:
+ // Position node adjacent or kitty-corner to aroundNode
+ // such that it's fully visible in viewport.
+ //
+ // description:
+ // Place node such that corner of node touches a corner of
+ // aroundNode, and that node is fully visible.
+ //
+ // aroundCorners:
+ // Ordered list of pairs of corners to try matching up.
+ // Each pair of corners is represented as a key/value in the hash,
+ // where the key corresponds to the aroundNode's corner, and
+ // the value corresponds to the node's corner:
+ //
+ // | { aroundNodeCorner1: nodeCorner1, aroundNodeCorner2: nodeCorner2, ...}
+ //
+ // The following strings are used to represent the four corners:
+ // * "BL" - bottom left
+ // * "BR" - bottom right
+ // * "TL" - top left
+ // * "TR" - top right
+ //
+ // layoutNode: Function(node, aroundNodeCorner, nodeCorner)
+ // For things like tooltip, they are displayed differently (and have different dimensions)
+ // based on their orientation relative to the parent. This adjusts the popup based on orientation.
+ //
+ // example:
+ // | dijit.placeOnScreenAroundNode(node, aroundNode, {'BL':'TL', 'TR':'BR'});
+ // This will try to position node such that node's top-left corner is at the same position
+ // as the bottom left corner of the aroundNode (ie, put node below
+ // aroundNode, with left edges aligned). If that fails it will try to put
+ // the bottom-right corner of node where the top right corner of aroundNode is
+ // (ie, put node above aroundNode, with right edges aligned)
+ //
+
+ // get coordinates of aroundNode
+ aroundNode = dojo.byId(aroundNode);
+ var oldDisplay = aroundNode.style.display;
+ aroundNode.style.display="";
+ // #3172: use the slightly tighter border box instead of marginBox
+ var aroundNodeW = aroundNode.offsetWidth; //mb.w;
+ var aroundNodeH = aroundNode.offsetHeight; //mb.h;
+ var aroundNodePos = dojo.coords(aroundNode, true);
+ aroundNode.style.display=oldDisplay;
+
+ // place the node around the calculated rectangle
+ return dijit._placeOnScreenAroundRect(node,
+ aroundNodePos.x, aroundNodePos.y, aroundNodeW, aroundNodeH, // rectangle
+ aroundCorners, layoutNode);
+};
+
+/*=====
+dijit.__Rectangle = function(){
+ // x: Integer
+ // horizontal offset in pixels, relative to document body
+ // y: Integer
+ // vertical offset in pixels, relative to document body
[... 3582 lines stripped ...]