Subversion Repositories Applications.papyrus

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
1318 alexandre_ 1
/*
2
	Copyright (c) 2004-2006, The Dojo Foundation
3
	All Rights Reserved.
4
 
5
	Licensed under the Academic Free License version 2.1 or above OR the
6
	modified BSD license. For more information on Dojo licensing, see:
7
 
8
		http://dojotoolkit.org/community/licensing.shtml
9
*/
10
 
11
dojo.provide("dojo.io.BrowserIO");
12
dojo.require("dojo.io.common");
13
dojo.require("dojo.lang.array");
14
dojo.require("dojo.lang.func");
15
dojo.require("dojo.string.extras");
16
dojo.require("dojo.dom");
17
dojo.require("dojo.undo.browser");
18
if (!dj_undef("window")) {
19
	dojo.io.checkChildrenForFile = function (node) {
20
		var hasFile = false;
21
		var inputs = node.getElementsByTagName("input");
22
		dojo.lang.forEach(inputs, function (input) {
23
			if (hasFile) {
24
				return;
25
			}
26
			if (input.getAttribute("type") == "file") {
27
				hasFile = true;
28
			}
29
		});
30
		return hasFile;
31
	};
32
	dojo.io.formHasFile = function (formNode) {
33
		return dojo.io.checkChildrenForFile(formNode);
34
	};
35
	dojo.io.updateNode = function (node, urlOrArgs) {
36
		node = dojo.byId(node);
37
		var args = urlOrArgs;
38
		if (dojo.lang.isString(urlOrArgs)) {
39
			args = {url:urlOrArgs};
40
		}
41
		args.mimetype = "text/html";
42
		args.load = function (t, d, e) {
43
			while (node.firstChild) {
44
				dojo.dom.destroyNode(node.firstChild);
45
			}
46
			node.innerHTML = d;
47
		};
48
		dojo.io.bind(args);
49
	};
50
	dojo.io.formFilter = function (node) {
51
		var type = (node.type || "").toLowerCase();
52
		return !node.disabled && node.name && !dojo.lang.inArray(["file", "submit", "image", "reset", "button"], type);
53
	};
54
	dojo.io.encodeForm = function (formNode, encoding, formFilter) {
55
		if ((!formNode) || (!formNode.tagName) || (!formNode.tagName.toLowerCase() == "form")) {
56
			dojo.raise("Attempted to encode a non-form element.");
57
		}
58
		if (!formFilter) {
59
			formFilter = dojo.io.formFilter;
60
		}
61
		var enc = /utf/i.test(encoding || "") ? encodeURIComponent : dojo.string.encodeAscii;
62
		var values = [];
63
		for (var i = 0; i < formNode.elements.length; i++) {
64
			var elm = formNode.elements[i];
65
			if (!elm || elm.tagName.toLowerCase() == "fieldset" || !formFilter(elm)) {
66
				continue;
67
			}
68
			var name = enc(elm.name);
69
			var type = elm.type.toLowerCase();
70
			if (type == "select-multiple") {
71
				for (var j = 0; j < elm.options.length; j++) {
72
					if (elm.options[j].selected) {
73
						values.push(name + "=" + enc(elm.options[j].value));
74
					}
75
				}
76
			} else {
77
				if (dojo.lang.inArray(["radio", "checkbox"], type)) {
78
					if (elm.checked) {
79
						values.push(name + "=" + enc(elm.value));
80
					}
81
				} else {
82
					values.push(name + "=" + enc(elm.value));
83
				}
84
			}
85
		}
86
		var inputs = formNode.getElementsByTagName("input");
87
		for (var i = 0; i < inputs.length; i++) {
88
			var input = inputs[i];
89
			if (input.type.toLowerCase() == "image" && input.form == formNode && formFilter(input)) {
90
				var name = enc(input.name);
91
				values.push(name + "=" + enc(input.value));
92
				values.push(name + ".x=0");
93
				values.push(name + ".y=0");
94
			}
95
		}
96
		return values.join("&") + "&";
97
	};
98
	dojo.io.FormBind = function (args) {
99
		this.bindArgs = {};
100
		if (args && args.formNode) {
101
			this.init(args);
102
		} else {
103
			if (args) {
104
				this.init({formNode:args});
105
			}
106
		}
107
	};
108
	dojo.lang.extend(dojo.io.FormBind, {form:null, bindArgs:null, clickedButton:null, init:function (args) {
109
		var form = dojo.byId(args.formNode);
110
		if (!form || !form.tagName || form.tagName.toLowerCase() != "form") {
111
			throw new Error("FormBind: Couldn't apply, invalid form");
112
		} else {
113
			if (this.form == form) {
114
				return;
115
			} else {
116
				if (this.form) {
117
					throw new Error("FormBind: Already applied to a form");
118
				}
119
			}
120
		}
121
		dojo.lang.mixin(this.bindArgs, args);
122
		this.form = form;
123
		this.connect(form, "onsubmit", "submit");
124
		for (var i = 0; i < form.elements.length; i++) {
125
			var node = form.elements[i];
126
			if (node && node.type && dojo.lang.inArray(["submit", "button"], node.type.toLowerCase())) {
127
				this.connect(node, "onclick", "click");
128
			}
129
		}
130
		var inputs = form.getElementsByTagName("input");
131
		for (var i = 0; i < inputs.length; i++) {
132
			var input = inputs[i];
133
			if (input.type.toLowerCase() == "image" && input.form == form) {
134
				this.connect(input, "onclick", "click");
135
			}
136
		}
137
	}, onSubmit:function (form) {
138
		return true;
139
	}, submit:function (e) {
140
		e.preventDefault();
141
		if (this.onSubmit(this.form)) {
142
			dojo.io.bind(dojo.lang.mixin(this.bindArgs, {formFilter:dojo.lang.hitch(this, "formFilter")}));
143
		}
144
	}, click:function (e) {
145
		var node = e.currentTarget;
146
		if (node.disabled) {
147
			return;
148
		}
149
		this.clickedButton = node;
150
	}, formFilter:function (node) {
151
		var type = (node.type || "").toLowerCase();
152
		var accept = false;
153
		if (node.disabled || !node.name) {
154
			accept = false;
155
		} else {
156
			if (dojo.lang.inArray(["submit", "button", "image"], type)) {
157
				if (!this.clickedButton) {
158
					this.clickedButton = node;
159
				}
160
				accept = node == this.clickedButton;
161
			} else {
162
				accept = !dojo.lang.inArray(["file", "submit", "reset", "button"], type);
163
			}
164
		}
165
		return accept;
166
	}, connect:function (srcObj, srcFcn, targetFcn) {
167
		if (dojo.evalObjPath("dojo.event.connect")) {
168
			dojo.event.connect(srcObj, srcFcn, this, targetFcn);
169
		} else {
170
			var fcn = dojo.lang.hitch(this, targetFcn);
171
			srcObj[srcFcn] = function (e) {
172
				if (!e) {
173
					e = window.event;
174
				}
175
				if (!e.currentTarget) {
176
					e.currentTarget = e.srcElement;
177
				}
178
				if (!e.preventDefault) {
179
					e.preventDefault = function () {
180
						window.event.returnValue = false;
181
					};
182
				}
183
				fcn(e);
184
			};
185
		}
186
	}});
187
	dojo.io.XMLHTTPTransport = new function () {
188
		var _this = this;
189
		var _cache = {};
190
		this.useCache = false;
191
		this.preventCache = false;
192
		function getCacheKey(url, query, method) {
193
			return url + "|" + query + "|" + method.toLowerCase();
194
		}
195
		function addToCache(url, query, method, http) {
196
			_cache[getCacheKey(url, query, method)] = http;
197
		}
198
		function getFromCache(url, query, method) {
199
			return _cache[getCacheKey(url, query, method)];
200
		}
201
		this.clearCache = function () {
202
			_cache = {};
203
		};
204
		function doLoad(kwArgs, http, url, query, useCache) {
205
			if (((http.status >= 200) && (http.status < 300)) || (http.status == 304) || (location.protocol == "file:" && (http.status == 0 || http.status == undefined)) || (location.protocol == "chrome:" && (http.status == 0 || http.status == undefined))) {
206
				var ret;
207
				if (kwArgs.method.toLowerCase() == "head") {
208
					var headers = http.getAllResponseHeaders();
209
					ret = {};
210
					ret.toString = function () {
211
						return headers;
212
					};
213
					var values = headers.split(/[\r\n]+/g);
214
					for (var i = 0; i < values.length; i++) {
215
						var pair = values[i].match(/^([^:]+)\s*:\s*(.+)$/i);
216
						if (pair) {
217
							ret[pair[1]] = pair[2];
218
						}
219
					}
220
				} else {
221
					if (kwArgs.mimetype == "text/javascript") {
222
						try {
223
							ret = dj_eval(http.responseText);
224
						}
225
						catch (e) {
226
							dojo.debug(e);
227
							dojo.debug(http.responseText);
228
							ret = null;
229
						}
230
					} else {
231
						if (kwArgs.mimetype == "text/json" || kwArgs.mimetype == "application/json") {
232
							try {
233
								ret = dj_eval("(" + http.responseText + ")");
234
							}
235
							catch (e) {
236
								dojo.debug(e);
237
								dojo.debug(http.responseText);
238
								ret = false;
239
							}
240
						} else {
241
							if ((kwArgs.mimetype == "application/xml") || (kwArgs.mimetype == "text/xml")) {
242
								ret = http.responseXML;
243
								if (!ret || typeof ret == "string" || !http.getResponseHeader("Content-Type")) {
244
									ret = dojo.dom.createDocumentFromText(http.responseText);
245
								}
246
							} else {
247
								ret = http.responseText;
248
							}
249
						}
250
					}
251
				}
252
				if (useCache) {
253
					addToCache(url, query, kwArgs.method, http);
254
				}
255
				kwArgs[(typeof kwArgs.load == "function") ? "load" : "handle"]("load", ret, http, kwArgs);
256
			} else {
257
				var errObj = new dojo.io.Error("XMLHttpTransport Error: " + http.status + " " + http.statusText);
258
				kwArgs[(typeof kwArgs.error == "function") ? "error" : "handle"]("error", errObj, http, kwArgs);
259
			}
260
		}
261
		function setHeaders(http, kwArgs) {
262
			if (kwArgs["headers"]) {
263
				for (var header in kwArgs["headers"]) {
264
					if (header.toLowerCase() == "content-type" && !kwArgs["contentType"]) {
265
						kwArgs["contentType"] = kwArgs["headers"][header];
266
					} else {
267
						http.setRequestHeader(header, kwArgs["headers"][header]);
268
					}
269
				}
270
			}
271
		}
272
		this.inFlight = [];
273
		this.inFlightTimer = null;
274
		this.startWatchingInFlight = function () {
275
			if (!this.inFlightTimer) {
276
				this.inFlightTimer = setTimeout("dojo.io.XMLHTTPTransport.watchInFlight();", 10);
277
			}
278
		};
279
		this.watchInFlight = function () {
280
			var now = null;
281
			if (!dojo.hostenv._blockAsync && !_this._blockAsync) {
282
				for (var x = this.inFlight.length - 1; x >= 0; x--) {
283
					try {
284
						var tif = this.inFlight[x];
285
						if (!tif || tif.http._aborted || !tif.http.readyState) {
286
							this.inFlight.splice(x, 1);
287
							continue;
288
						}
289
						if (4 == tif.http.readyState) {
290
							this.inFlight.splice(x, 1);
291
							doLoad(tif.req, tif.http, tif.url, tif.query, tif.useCache);
292
						} else {
293
							if (tif.startTime) {
294
								if (!now) {
295
									now = (new Date()).getTime();
296
								}
297
								if (tif.startTime + (tif.req.timeoutSeconds * 1000) < now) {
298
									if (typeof tif.http.abort == "function") {
299
										tif.http.abort();
300
									}
301
									this.inFlight.splice(x, 1);
302
									tif.req[(typeof tif.req.timeout == "function") ? "timeout" : "handle"]("timeout", null, tif.http, tif.req);
303
								}
304
							}
305
						}
306
					}
307
					catch (e) {
308
						try {
309
							var errObj = new dojo.io.Error("XMLHttpTransport.watchInFlight Error: " + e);
310
							tif.req[(typeof tif.req.error == "function") ? "error" : "handle"]("error", errObj, tif.http, tif.req);
311
						}
312
						catch (e2) {
313
							dojo.debug("XMLHttpTransport error callback failed: " + e2);
314
						}
315
					}
316
				}
317
			}
318
			clearTimeout(this.inFlightTimer);
319
			if (this.inFlight.length == 0) {
320
				this.inFlightTimer = null;
321
				return;
322
			}
323
			this.inFlightTimer = setTimeout("dojo.io.XMLHTTPTransport.watchInFlight();", 10);
324
		};
325
		var hasXmlHttp = dojo.hostenv.getXmlhttpObject() ? true : false;
326
		this.canHandle = function (kwArgs) {
327
			return hasXmlHttp && dojo.lang.inArray(["text/plain", "text/html", "application/xml", "text/xml", "text/javascript", "text/json", "application/json"], (kwArgs["mimetype"].toLowerCase() || "")) && !(kwArgs["formNode"] && dojo.io.formHasFile(kwArgs["formNode"]));
328
		};
329
		this.multipartBoundary = "45309FFF-BD65-4d50-99C9-36986896A96F";
330
		this.bind = function (kwArgs) {
331
			if (!kwArgs["url"]) {
332
				if (!kwArgs["formNode"] && (kwArgs["backButton"] || kwArgs["back"] || kwArgs["changeUrl"] || kwArgs["watchForURL"]) && (!djConfig.preventBackButtonFix)) {
333
					dojo.deprecated("Using dojo.io.XMLHTTPTransport.bind() to add to browser history without doing an IO request", "Use dojo.undo.browser.addToHistory() instead.", "0.4");
334
					dojo.undo.browser.addToHistory(kwArgs);
335
					return true;
336
				}
337
			}
338
			var url = kwArgs.url;
339
			var query = "";
340
			if (kwArgs["formNode"]) {
341
				var ta = kwArgs.formNode.getAttribute("action");
342
				if ((ta) && (!kwArgs["url"])) {
343
					url = ta;
344
				}
345
				var tp = kwArgs.formNode.getAttribute("method");
346
				if ((tp) && (!kwArgs["method"])) {
347
					kwArgs.method = tp;
348
				}
349
				query += dojo.io.encodeForm(kwArgs.formNode, kwArgs.encoding, kwArgs["formFilter"]);
350
			}
351
			if (url.indexOf("#") > -1) {
352
				dojo.debug("Warning: dojo.io.bind: stripping hash values from url:", url);
353
				url = url.split("#")[0];
354
			}
355
			if (kwArgs["file"]) {
356
				kwArgs.method = "post";
357
			}
358
			if (!kwArgs["method"]) {
359
				kwArgs.method = "get";
360
			}
361
			if (kwArgs.method.toLowerCase() == "get") {
362
				kwArgs.multipart = false;
363
			} else {
364
				if (kwArgs["file"]) {
365
					kwArgs.multipart = true;
366
				} else {
367
					if (!kwArgs["multipart"]) {
368
						kwArgs.multipart = false;
369
					}
370
				}
371
			}
372
			if (kwArgs["backButton"] || kwArgs["back"] || kwArgs["changeUrl"]) {
373
				dojo.undo.browser.addToHistory(kwArgs);
374
			}
375
			var content = kwArgs["content"] || {};
376
			if (kwArgs.sendTransport) {
377
				content["dojo.transport"] = "xmlhttp";
378
			}
379
			do {
380
				if (kwArgs.postContent) {
381
					query = kwArgs.postContent;
382
					break;
383
				}
384
				if (content) {
385
					query += dojo.io.argsFromMap(content, kwArgs.encoding);
386
				}
387
				if (kwArgs.method.toLowerCase() == "get" || !kwArgs.multipart) {
388
					break;
389
				}
390
				var t = [];
391
				if (query.length) {
392
					var q = query.split("&");
393
					for (var i = 0; i < q.length; ++i) {
394
						if (q[i].length) {
395
							var p = q[i].split("=");
396
							t.push("--" + this.multipartBoundary, "Content-Disposition: form-data; name=\"" + p[0] + "\"", "", p[1]);
397
						}
398
					}
399
				}
400
				if (kwArgs.file) {
401
					if (dojo.lang.isArray(kwArgs.file)) {
402
						for (var i = 0; i < kwArgs.file.length; ++i) {
403
							var o = kwArgs.file[i];
404
							t.push("--" + this.multipartBoundary, "Content-Disposition: form-data; name=\"" + o.name + "\"; filename=\"" + ("fileName" in o ? o.fileName : o.name) + "\"", "Content-Type: " + ("contentType" in o ? o.contentType : "application/octet-stream"), "", o.content);
405
						}
406
					} else {
407
						var o = kwArgs.file;
408
						t.push("--" + this.multipartBoundary, "Content-Disposition: form-data; name=\"" + o.name + "\"; filename=\"" + ("fileName" in o ? o.fileName : o.name) + "\"", "Content-Type: " + ("contentType" in o ? o.contentType : "application/octet-stream"), "", o.content);
409
					}
410
				}
411
				if (t.length) {
412
					t.push("--" + this.multipartBoundary + "--", "");
413
					query = t.join("\r\n");
414
				}
415
			} while (false);
416
			var async = kwArgs["sync"] ? false : true;
417
			var preventCache = kwArgs["preventCache"] || (this.preventCache == true && kwArgs["preventCache"] != false);
418
			var useCache = kwArgs["useCache"] == true || (this.useCache == true && kwArgs["useCache"] != false);
419
			if (!preventCache && useCache) {
420
				var cachedHttp = getFromCache(url, query, kwArgs.method);
421
				if (cachedHttp) {
422
					doLoad(kwArgs, cachedHttp, url, query, false);
423
					return;
424
				}
425
			}
426
			var http = dojo.hostenv.getXmlhttpObject(kwArgs);
427
			var received = false;
428
			if (async) {
429
				var startTime = this.inFlight.push({"req":kwArgs, "http":http, "url":url, "query":query, "useCache":useCache, "startTime":kwArgs.timeoutSeconds ? (new Date()).getTime() : 0});
430
				this.startWatchingInFlight();
431
			} else {
432
				_this._blockAsync = true;
433
			}
434
			if (kwArgs.method.toLowerCase() == "post") {
435
				if (!kwArgs.user) {
436
					http.open("POST", url, async);
437
				} else {
438
					http.open("POST", url, async, kwArgs.user, kwArgs.password);
439
				}
440
				setHeaders(http, kwArgs);
441
				http.setRequestHeader("Content-Type", kwArgs.multipart ? ("multipart/form-data; boundary=" + this.multipartBoundary) : (kwArgs.contentType || "application/x-www-form-urlencoded"));
442
				try {
443
					http.send(query);
444
				}
445
				catch (e) {
446
					if (typeof http.abort == "function") {
447
						http.abort();
448
					}
449
					doLoad(kwArgs, {status:404}, url, query, useCache);
450
				}
451
			} else {
452
				var tmpUrl = url;
453
				if (query != "") {
454
					tmpUrl += (tmpUrl.indexOf("?") > -1 ? "&" : "?") + query;
455
				}
456
				if (preventCache) {
457
					tmpUrl += (dojo.string.endsWithAny(tmpUrl, "?", "&") ? "" : (tmpUrl.indexOf("?") > -1 ? "&" : "?")) + "dojo.preventCache=" + new Date().valueOf();
458
				}
459
				if (!kwArgs.user) {
460
					http.open(kwArgs.method.toUpperCase(), tmpUrl, async);
461
				} else {
462
					http.open(kwArgs.method.toUpperCase(), tmpUrl, async, kwArgs.user, kwArgs.password);
463
				}
464
				setHeaders(http, kwArgs);
465
				try {
466
					http.send(null);
467
				}
468
				catch (e) {
469
					if (typeof http.abort == "function") {
470
						http.abort();
471
					}
472
					doLoad(kwArgs, {status:404}, url, query, useCache);
473
				}
474
			}
475
			if (!async) {
476
				doLoad(kwArgs, http, url, query, useCache);
477
				_this._blockAsync = false;
478
			}
479
			kwArgs.abort = function () {
480
				try {
481
					http._aborted = true;
482
				}
483
				catch (e) {
484
				}
485
				return http.abort();
486
			};
487
			return;
488
		};
489
		dojo.io.transports.addTransport("XMLHTTPTransport");
490
	};
491
}
492