Subversion Repositories Applications.papyrus

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
2150 mathias 1
if(!dojo._hasResource["dojox._sql.common"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
2
dojo._hasResource["dojox._sql.common"] = true;
3
dojo.provide("dojox._sql.common");
4
 
5
dojo.require("dojox._sql._crypto");
6
 
7
// summary:
8
//	Executes a SQL expression.
9
// description:
10
// 	There are four ways to call this:
11
// 	1) Straight SQL: dojox.sql("SELECT * FROM FOOBAR");
12
// 	2) SQL with parameters: dojox.sql("INSERT INTO FOOBAR VALUES (?)", someParam)
13
// 	3) Encrypting particular values:
14
//			dojox.sql("INSERT INTO FOOBAR VALUES (ENCRYPT(?))", someParam, "somePassword", callback)
15
// 	4) Decrypting particular values:
16
//			dojox.sql("SELECT DECRYPT(SOMECOL1), DECRYPT(SOMECOL2) FROM
17
//					FOOBAR WHERE SOMECOL3 = ?", someParam,
18
//					"somePassword", callback)
19
//
20
// 	For encryption and decryption the last two values should be the the password for
21
// 	encryption/decryption, and the callback function that gets the result set.
22
//
23
// 	Note: We only support ENCRYPT(?) statements, and
24
// 	and DECRYPT(*) statements for now -- you can not have a literal string
25
// 	inside of these, such as ENCRYPT('foobar')
26
//
27
// 	Note: If you have multiple columns to encrypt and decrypt, you can use the following
28
// 	convenience form to not have to type ENCRYPT(?)/DECRYPT(*) many times:
29
//
30
// 	dojox.sql("INSERT INTO FOOBAR VALUES (ENCRYPT(?, ?, ?))",
31
//					someParam1, someParam2, someParam3,
32
//					"somePassword", callback)
33
//
34
// 	dojox.sql("SELECT DECRYPT(SOMECOL1, SOMECOL2) FROM
35
//					FOOBAR WHERE SOMECOL3 = ?", someParam,
36
//					"somePassword", callback)
37
dojox.sql = new Function("return dojox.sql._exec(arguments);");
38
 
39
dojo.mixin(dojox.sql, {
40
	dbName: null,
41
 
42
	// summary:
43
	//	If true, then we print out any SQL that is executed
44
	//	to the debug window
45
	debug: (dojo.exists("dojox.sql.debug")?dojox.sql.debug:false),
46
 
47
	open: function(dbName){
48
		if(this._dbOpen && (!dbName || dbName == this.dbName)){
49
			return;
50
		}
51
 
52
		if(!this.dbName){
53
			this.dbName = "dot_store_"
54
				+ window.location.href.replace(/[^0-9A-Za-z_]/g, "_");
55
			//console.debug("Using Google Gears database " + this.dbName);
56
		}
57
 
58
		if(!dbName){
59
			dbName = this.dbName;
60
		}
61
 
62
		try{
63
			this._initDb();
64
			this.db.open(dbName);
65
			this._dbOpen = true;
66
		}catch(exp){
67
			throw exp.message||exp;
68
		}
69
	},
70
 
71
	close: function(dbName){
72
		// on Internet Explorer, Google Gears throws an exception
73
		// "Object not a collection", when we try to close the
74
		// database -- just don't close it on this platform
75
		// since we are running into a Gears bug; the Gears team
76
		// said it's ok to not close a database connection
77
		if(dojo.isIE){ return; }
78
 
79
		if(!this._dbOpen && (!dbName || dbName == this.dbName)){
80
			return;
81
		}
82
 
83
		if(!dbName){
84
			dbName = this.dbName;
85
		}
86
 
87
		try{
88
			this.db.close(dbName);
89
			this._dbOpen = false;
90
		}catch(exp){
91
			throw exp.message||exp;
92
		}
93
	},
94
 
95
	_exec: function(params){
96
		try{
97
			// get the Gears Database object
98
			this._initDb();
99
 
100
			// see if we need to open the db; if programmer
101
			// manually called dojox.sql.open() let them handle
102
			// it; otherwise we open and close automatically on
103
			// each SQL execution
104
			if(!this._dbOpen){
105
				this.open();
106
				this._autoClose = true;
107
			}
108
 
109
			// determine our parameters
110
			var sql = null;
111
			var callback = null;
112
			var password = null;
113
 
114
			var args = dojo._toArray(params);
115
 
116
			sql = args.splice(0, 1)[0];
117
 
118
			// does this SQL statement use the ENCRYPT or DECRYPT
119
			// keywords? if so, extract our callback and crypto
120
			// password
121
			if(this._needsEncrypt(sql) || this._needsDecrypt(sql)){
122
				callback = args.splice(args.length - 1, 1)[0];
123
				password = args.splice(args.length - 1, 1)[0];
124
			}
125
 
126
			// 'args' now just has the SQL parameters
127
 
128
			// print out debug SQL output if the developer wants that
129
			if(this.debug){
130
				this._printDebugSQL(sql, args);
131
			}
132
 
133
			// handle SQL that needs encryption/decryption differently
134
			// do we have an ENCRYPT SQL statement? if so, handle that first
135
			if(this._needsEncrypt(sql)){
136
				var crypto = new dojox.sql._SQLCrypto("encrypt", sql,
137
													password, args,
138
													callback);
139
				return; // encrypted results will arrive asynchronously
140
			}else if(this._needsDecrypt(sql)){ // otherwise we have a DECRYPT statement
141
				var crypto = new dojox.sql._SQLCrypto("decrypt", sql,
142
													password, args,
143
													callback);
144
				return; // decrypted results will arrive asynchronously
145
			}
146
 
147
			// execute the SQL and get the results
148
			var rs = this.db.execute(sql, args);
149
 
150
			// Gears ResultSet object's are ugly -- normalize
151
			// these into something JavaScript programmers know
152
			// how to work with, basically an array of
153
			// JavaScript objects where each property name is
154
			// simply the field name for a column of data
155
			rs = this._normalizeResults(rs);
156
 
157
			if(this._autoClose){
158
				this.close();
159
			}
160
 
161
			return rs;
162
		}catch(exp){
163
			exp = exp.message||exp;
164
 
165
			console.debug("SQL Exception: " + exp);
166
 
167
			if(this._autoClose){
168
				try{
169
					this.close();
170
				}catch(e){
171
					console.debug("Error closing database: "
172
									+ e.message||e);
173
				}
174
			}
175
 
176
			throw exp;
177
		}
178
	},
179
 
180
	_initDb: function(){
181
		if(!this.db){
182
			try{
183
				this.db = google.gears.factory.create('beta.database', '1.0');
184
			}catch(exp){
185
				dojo.setObject("google.gears.denied", true);
186
				dojox.off.onFrameworkEvent("coreOperationFailed");
187
				throw "Google Gears must be allowed to run";
188
			}
189
		}
190
	},
191
 
192
	_printDebugSQL: function(sql, args){
193
		var msg = "dojox.sql(\"" + sql + "\"";
194
		for(var i = 0; i < args.length; i++){
195
			if(typeof args[i] == "string"){
196
				msg += ", \"" + args[i] + "\"";
197
			}else{
198
				msg += ", " + args[i];
199
			}
200
		}
201
		msg += ")";
202
 
203
		console.debug(msg);
204
	},
205
 
206
	_normalizeResults: function(rs){
207
		var results = [];
208
		if(!rs){ return []; }
209
 
210
		while(rs.isValidRow()){
211
			var row = {};
212
 
213
			for(var i = 0; i < rs.fieldCount(); i++){
214
				var fieldName = rs.fieldName(i);
215
				var fieldValue = rs.field(i);
216
				row[fieldName] = fieldValue;
217
			}
218
 
219
			results.push(row);
220
 
221
			rs.next();
222
		}
223
 
224
		rs.close();
225
 
226
		return results;
227
	},
228
 
229
	_needsEncrypt: function(sql){
230
		return /encrypt\([^\)]*\)/i.test(sql);
231
	},
232
 
233
	_needsDecrypt: function(sql){
234
		return /decrypt\([^\)]*\)/i.test(sql);
235
	}
236
});
237
 
238
// summary:
239
//	A private class encapsulating any cryptography that must be done
240
// 	on a SQL statement. We instantiate this class and have it hold
241
//	it's state so that we can potentially have several encryption
242
//	operations happening at the same time by different SQL statements.
243
dojo.declare("dojox.sql._SQLCrypto", null, {
244
	constructor: function(action, sql, password, args, callback){
245
		if(action == "encrypt"){
246
			this._execEncryptSQL(sql, password, args, callback);
247
		}else{
248
			this._execDecryptSQL(sql, password, args, callback);
249
		}
250
	},
251
 
252
	_execEncryptSQL: function(sql, password, args, callback){
253
		// strip the ENCRYPT/DECRYPT keywords from the SQL
254
		var strippedSQL = this._stripCryptoSQL(sql);
255
 
256
		// determine what arguments need encryption
257
		var encryptColumns = this._flagEncryptedArgs(sql, args);
258
 
259
		// asynchronously encrypt each argument that needs it
260
		var self = this;
261
		this._encrypt(strippedSQL, password, args, encryptColumns, function(finalArgs){
262
			// execute the SQL
263
			var error = false;
264
			var resultSet = [];
265
			var exp = null;
266
			try{
267
				resultSet = dojox.sql.db.execute(strippedSQL, finalArgs);
268
			}catch(execError){
269
				error = true;
270
				exp = execError.message||execError;
271
			}
272
 
273
			// was there an error during SQL execution?
274
			if(exp != null){
275
				if(dojox.sql._autoClose){
276
					try{ dojox.sql.close(); }catch(e){}
277
				}
278
 
279
				callback(null, true, exp.toString());
280
				return;
281
			}
282
 
283
			// normalize SQL results into a JavaScript object
284
			// we can work with
285
			resultSet = dojox.sql._normalizeResults(resultSet);
286
 
287
			if(dojox.sql._autoClose){
288
				dojox.sql.close();
289
			}
290
 
291
			// are any decryptions necessary on the result set?
292
			if(dojox.sql._needsDecrypt(sql)){
293
				// determine which of the result set columns needs decryption
294
	 			var needsDecrypt = self._determineDecryptedColumns(sql);
295
 
296
				// now decrypt columns asynchronously
297
				// decrypt columns that need it
298
				self._decrypt(resultSet, needsDecrypt, password, function(finalResultSet){
299
					callback(finalResultSet, false, null);
300
				});
301
			}else{
302
				callback(resultSet, false, null);
303
			}
304
		});
305
	},
306
 
307
	_execDecryptSQL: function(sql, password, args, callback){
308
		// strip the ENCRYPT/DECRYPT keywords from the SQL
309
		var strippedSQL = this._stripCryptoSQL(sql);
310
 
311
		// determine which columns needs decryption; this either
312
		// returns the value *, which means all result set columns will
313
		// be decrypted, or it will return the column names that need
314
		// decryption set on a hashtable so we can quickly test a given
315
		// column name; the key is the column name that needs
316
		// decryption and the value is 'true' (i.e. needsDecrypt["someColumn"]
317
		// would return 'true' if it needs decryption, and would be 'undefined'
318
		// or false otherwise)
319
		var needsDecrypt = this._determineDecryptedColumns(sql);
320
 
321
		// execute the SQL
322
		var error = false;
323
		var resultSet = [];
324
		var exp = null;
325
		try{
326
			resultSet = dojox.sql.db.execute(strippedSQL, args);
327
		}catch(execError){
328
			error = true;
329
			exp = execError.message||execError;
330
		}
331
 
332
		// was there an error during SQL execution?
333
		if(exp != null){
334
			if(dojox.sql._autoClose){
335
				try{ dojox.sql.close(); }catch(e){}
336
			}
337
 
338
			callback(resultSet, true, exp.toString());
339
			return;
340
		}
341
 
342
		// normalize SQL results into a JavaScript object
343
		// we can work with
344
		resultSet = dojox.sql._normalizeResults(resultSet);
345
 
346
		if(dojox.sql._autoClose){
347
			dojox.sql.close();
348
		}
349
 
350
		// decrypt columns that need it
351
		this._decrypt(resultSet, needsDecrypt, password, function(finalResultSet){
352
			callback(finalResultSet, false, null);
353
		});
354
	},
355
 
356
	_encrypt: function(sql, password, args, encryptColumns, callback){
357
		//console.debug("_encrypt, sql="+sql+", password="+password+", encryptColumns="+encryptColumns+", args="+args);
358
 
359
		this._totalCrypto = 0;
360
		this._finishedCrypto = 0;
361
		this._finishedSpawningCrypto = false;
362
		this._finalArgs = args;
363
 
364
		for(var i = 0; i < args.length; i++){
365
			if(encryptColumns[i]){
366
				// we have an encrypt() keyword -- get just the value inside
367
				// the encrypt() parantheses -- for now this must be a ?
368
				var sqlParam = args[i];
369
				var paramIndex = i;
370
 
371
				// update the total number of encryptions we know must be done asynchronously
372
				this._totalCrypto++;
373
 
374
				// FIXME: This currently uses DES as a proof-of-concept since the
375
				// DES code used is quite fast and was easy to work with. Modify dojox.sql
376
				// to be able to specify a different encryption provider through a
377
				// a SQL-like syntax, such as dojox.sql("SET ENCRYPTION BLOWFISH"),
378
				// and modify the dojox.crypto.Blowfish code to be able to work using
379
				// a Google Gears Worker Pool
380
 
381
				// do the actual encryption now, asychronously on a Gears worker thread
382
				dojox._sql._crypto.encrypt(sqlParam, password, dojo.hitch(this, function(results){
383
					// set the new encrypted value
384
					this._finalArgs[paramIndex] = results;
385
					this._finishedCrypto++;
386
					// are we done with all encryption?
387
					if(this._finishedCrypto >= this._totalCrypto
388
						&& this._finishedSpawningCrypto){
389
						callback(this._finalArgs);
390
					}
391
				}));
392
			}
393
		}
394
 
395
		this._finishedSpawningCrypto = true;
396
	},
397
 
398
	_decrypt: function(resultSet, needsDecrypt, password, callback){
399
		//console.debug("decrypt, resultSet="+resultSet+", needsDecrypt="+needsDecrypt+", password="+password);
400
 
401
		this._totalCrypto = 0;
402
		this._finishedCrypto = 0;
403
		this._finishedSpawningCrypto = false;
404
		this._finalResultSet = resultSet;
405
 
406
		for(var i = 0; i < resultSet.length; i++){
407
			var row = resultSet[i];
408
 
409
			// go through each of the column names in row,
410
			// seeing if they need decryption
411
			for(var columnName in row){
412
				if(needsDecrypt == "*" || needsDecrypt[columnName]){
413
					this._totalCrypto++;
414
					var columnValue = row[columnName];
415
 
416
					// forming a closure here can cause issues, with values not cleanly
417
					// saved on Firefox/Mac OS X for some of the values above that
418
					// are needed in the callback below; call a subroutine that will form
419
					// a closure inside of itself instead
420
					this._decryptSingleColumn(columnName, columnValue, password, i,
421
												function(finalResultSet){
422
						callback(finalResultSet);
423
					});
424
				}
425
			}
426
		}
427
 
428
		this._finishedSpawningCrypto = true;
429
	},
430
 
431
	_stripCryptoSQL: function(sql){
432
		// replace all DECRYPT(*) occurrences with a *
433
		sql = sql.replace(/DECRYPT\(\*\)/ig, "*");
434
 
435
		// match any ENCRYPT(?, ?, ?, etc) occurrences,
436
		// then replace with just the question marks in the
437
		// middle
438
		var matches = sql.match(/ENCRYPT\([^\)]*\)/ig);
439
		if(matches != null){
440
			for(var i = 0; i < matches.length; i++){
441
				var encryptStatement = matches[i];
442
				var encryptValue = encryptStatement.match(/ENCRYPT\(([^\)]*)\)/i)[1];
443
				sql = sql.replace(encryptStatement, encryptValue);
444
			}
445
		}
446
 
447
		// match any DECRYPT(COL1, COL2, etc) occurrences,
448
		// then replace with just the column names
449
		// in the middle
450
		matches = sql.match(/DECRYPT\([^\)]*\)/ig);
451
		if(matches != null){
452
			for(var i = 0; i < matches.length; i++){
453
				var decryptStatement = matches[i];
454
				var decryptValue = decryptStatement.match(/DECRYPT\(([^\)]*)\)/i)[1];
455
				sql = sql.replace(decryptStatement, decryptValue);
456
			}
457
		}
458
 
459
		return sql;
460
	},
461
 
462
	_flagEncryptedArgs: function(sql, args){
463
		// capture literal strings that have question marks in them,
464
		// and also capture question marks that stand alone
465
		var tester = new RegExp(/([\"][^\"]*\?[^\"]*[\"])|([\'][^\']*\?[^\']*[\'])|(\?)/ig);
466
		var matches;
467
		var currentParam = 0;
468
		var results = [];
469
		while((matches = tester.exec(sql)) != null){
470
			var currentMatch = RegExp.lastMatch+"";
471
 
472
			// are we a literal string? then ignore it
473
			if(/^[\"\']/.test(currentMatch)){
474
				continue;
475
			}
476
 
477
			// do we have an encrypt keyword to our left?
478
			var needsEncrypt = false;
479
			if(/ENCRYPT\([^\)]*$/i.test(RegExp.leftContext)){
480
				needsEncrypt = true;
481
			}
482
 
483
			// set the encrypted flag
484
			results[currentParam] = needsEncrypt;
485
 
486
			currentParam++;
487
		}
488
 
489
		return results;
490
	},
491
 
492
	_determineDecryptedColumns: function(sql){
493
		var results = {};
494
 
495
		if(/DECRYPT\(\*\)/i.test(sql)){
496
			results = "*";
497
		}else{
498
			var tester = /DECRYPT\((?:\s*\w*\s*\,?)*\)/ig;
499
			var matches;
500
			while(matches = tester.exec(sql)){
501
				var lastMatch = new String(RegExp.lastMatch);
502
				var columnNames = lastMatch.replace(/DECRYPT\(/i, "");
503
				columnNames = columnNames.replace(/\)/, "");
504
				columnNames = columnNames.split(/\s*,\s*/);
505
				dojo.forEach(columnNames, function(column){
506
					if(/\s*\w* AS (\w*)/i.test(column)){
507
						column = column.match(/\s*\w* AS (\w*)/i)[1];
508
					}
509
					results[column] = true;
510
				});
511
			}
512
		}
513
 
514
		return results;
515
	},
516
 
517
	_decryptSingleColumn: function(columnName, columnValue, password, currentRowIndex,
518
											callback){
519
		//console.debug("decryptSingleColumn, columnName="+columnName+", columnValue="+columnValue+", currentRowIndex="+currentRowIndex)
520
		dojox._sql._crypto.decrypt(columnValue, password, dojo.hitch(this, function(results){
521
			// set the new decrypted value
522
			this._finalResultSet[currentRowIndex][columnName] = results;
523
			this._finishedCrypto++;
524
 
525
			// are we done with all encryption?
526
			if(this._finishedCrypto >= this._totalCrypto
527
				&& this._finishedSpawningCrypto){
528
				//console.debug("done with all decrypts");
529
				callback(this._finalResultSet);
530
			}
531
		}));
532
	}
533
});
534
 
535
}