Blame view

sources/core/js/js.js 41.4 KB
03e52840d   Kload   Init
1
2
  /**
   * Disable console output unless DEBUG mode is enabled.
31b7f2792   Kload   Upgrade to ownclo...
3
   * Add
6d9380f96   Cédric Dupont   Update sources OC...
4
   *      define('DEBUG', true);
03e52840d   Kload   Init
5
6
7
8
9
10
11
12
   * To the end of config/config.php to enable debug mode.
   * The undefined checks fix the broken ie8 console
   */
  var oc_debug;
  var oc_webroot;
  
  var oc_current_user = document.getElementsByTagName('head')[0].getAttribute('data-user');
  var oc_requesttoken = document.getElementsByTagName('head')[0].getAttribute('data-requesttoken');
a293d369c   Kload   Update sources to...
13
  window.oc_config = window.oc_config || {};
03e52840d   Kload   Init
14
  if (typeof oc_webroot === "undefined") {
a293d369c   Kload   Update sources to...
15
16
17
18
19
20
21
22
  	oc_webroot = location.pathname;
  	var pos = oc_webroot.indexOf('/index.php/');
  	if (pos !== -1) {
  		oc_webroot = oc_webroot.substr(0, pos);
  	}
  	else {
  		oc_webroot = oc_webroot.substr(0, oc_webroot.lastIndexOf('/'));
  	}
03e52840d   Kload   Init
23
  }
6d9380f96   Cédric Dupont   Update sources OC...
24
25
26
27
  if (
  	oc_debug !== true || typeof console === "undefined" ||
  	typeof console.log === "undefined"
  ) {
03e52840d   Kload   Init
28
29
30
  	if (!window.console) {
  		window.console = {};
  	}
6d9380f96   Cédric Dupont   Update sources OC...
31
32
  	var noOp = function() { };
  	var methods = ['log', 'debug', 'warn', 'info', 'error', 'assert', 'time', 'timeEnd'];
03e52840d   Kload   Init
33
  	for (var i = 0; i < methods.length; i++) {
6d9380f96   Cédric Dupont   Update sources OC...
34
  		console[methods[i]] = noOp;
03e52840d   Kload   Init
35
36
  	}
  }
31b7f2792   Kload   Upgrade to ownclo...
37
38
39
  function initL10N(app) {
  	if (!( t.cache[app] )) {
  		$.ajax(OC.filePath('core', 'ajax', 'translations.php'), {
6d9380f96   Cédric Dupont   Update sources OC...
40
41
  			// TODO a proper solution for this without sync ajax calls
  			async: false,
31b7f2792   Kload   Upgrade to ownclo...
42
43
44
  			data: {'app': app},
  			type: 'POST',
  			success: function (jsondata) {
03e52840d   Kload   Init
45
  				t.cache[app] = jsondata.data;
31b7f2792   Kload   Upgrade to ownclo...
46
  				t.plural_form = jsondata.plural_form;
03e52840d   Kload   Init
47
48
49
50
  			}
  		});
  
  		// Bad answer ...
31b7f2792   Kload   Upgrade to ownclo...
51
  		if (!( t.cache[app] )) {
03e52840d   Kload   Init
52
53
54
  			t.cache[app] = [];
  		}
  	}
6d9380f96   Cédric Dupont   Update sources OC...
55
  	if (typeof t.plural_function[app] === 'undefined') {
a293d369c   Kload   Update sources to...
56
  		t.plural_function[app] = function (n) {
6d9380f96   Cédric Dupont   Update sources OC...
57
  			var p = (n !== 1) ? 1 : 0;
31b7f2792   Kload   Upgrade to ownclo...
58
59
60
61
62
63
64
65
  			return { 'nplural' : 2, 'plural' : p };
  		};
  
  		/**
  		 * code below has been taken from jsgettext - which is LGPL licensed
  		 * https://developer.berlios.de/projects/jsgettext/
  		 * http://cvs.berlios.de/cgi-bin/viewcvs.cgi/jsgettext/jsgettext/lib/Gettext.js
  		 */
6d9380f96   Cédric Dupont   Update sources OC...
66
  		var pf_re = new RegExp('^(\\s*nplurals\\s*=\\s*[0-9]+\\s*;\\s*plural\\s*=\\s*(?:\\s|[-\\?\\|&=!<>+*/%:;a-zA-Z0-9_\\(\\)])+)', 'm');
31b7f2792   Kload   Upgrade to ownclo...
67
68
69
70
71
72
73
  		if (pf_re.test(t.plural_form)) {
  			//ex english: "Plural-Forms: nplurals=2; plural=(n != 1);
  "
  			//pf = "nplurals=2; plural=(n != 1);";
  			//ex russian: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10< =4 && (n%100<10 or n%100>=20) ? 1 : 2)
  			//pf = "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2)";
  			var pf = t.plural_form;
6d9380f96   Cédric Dupont   Update sources OC...
74
75
76
  			if (! /;\s*$/.test(pf)) {
  				pf = pf.concat(';');
  			}
31b7f2792   Kload   Upgrade to ownclo...
77
78
79
  			/* We used to use eval, but it seems IE has issues with it.
  			 * We now use "new Function", though it carries a slightly
  			 * bigger performance hit.
6d9380f96   Cédric Dupont   Update sources OC...
80
81
  			var code = 'function (n) { var plural; var nplurals; '+pf+' return { "nplural" : nplurals, "plural" : (plural === true ? 1 : plural ? plural : 0) }; };';
  			Gettext._locale_data[domain].head.plural_func = eval("("+code+")");
31b7f2792   Kload   Upgrade to ownclo...
82
83
  			 */
  			var code = 'var plural; var nplurals; '+pf+' return { "nplural" : nplurals, "plural" : (plural === true ? 1 : plural ? plural : 0) };';
a293d369c   Kload   Update sources to...
84
  			t.plural_function[app] = new Function("n", code);
31b7f2792   Kload   Upgrade to ownclo...
85
86
87
88
89
90
91
  		} else {
  			console.log("Syntax error in language file. Plural-Forms header is invalid ["+t.plural_forms+"]");
  		}
  	}
  }
  /**
   * translate a string
6d9380f96   Cédric Dupont   Update sources OC...
92
93
94
95
96
   * @param {string} app the id of the app for which to translate the string
   * @param {string} text the string to translate
   * @param [vars] FIXME
   * @param {number} [count] number to replace %n with
   * @return {string}
31b7f2792   Kload   Upgrade to ownclo...
97
98
99
100
101
   */
  function t(app, text, vars, count){
  	initL10N(app);
  	var _build = function (text, vars, count) {
  		return text.replace(/%n/g, count).replace(/{([^{}]*)}/g,
03e52840d   Kload   Init
102
103
104
105
106
107
  			function (a, b) {
  				var r = vars[b];
  				return typeof r === 'string' || typeof r === 'number' ? r : a;
  			}
  		);
  	};
31b7f2792   Kload   Upgrade to ownclo...
108
  	var translation = text;
03e52840d   Kload   Init
109
  	if( typeof( t.cache[app][text] ) !== 'undefined' ){
31b7f2792   Kload   Upgrade to ownclo...
110
111
112
113
114
115
116
117
118
119
  		translation = t.cache[app][text];
  	}
  
  	if(typeof vars === 'object' || count !== undefined ) {
  		return _build(translation, vars, count);
  	} else {
  		return translation;
  	}
  }
  t.cache = {};
a293d369c   Kload   Update sources to...
120
121
122
123
  // different apps might or might not redefine the nplurals function correctly
  // this is to make sure that a "broken" app doesn't mess up with the
  // other app's plural function
  t.plural_function = {};
31b7f2792   Kload   Upgrade to ownclo...
124
125
126
  
  /**
   * translate a string
6d9380f96   Cédric Dupont   Update sources OC...
127
128
129
130
131
132
   * @param {string} app the id of the app for which to translate the string
   * @param {string} text_singular the string to translate for exactly one object
   * @param {string} text_plural the string to translate for n objects
   * @param {number} count number to determine whether to use singular or plural
   * @param [vars] FIXME
   * @return {string} Translated string
31b7f2792   Kload   Upgrade to ownclo...
133
134
135
   */
  function n(app, text_singular, text_plural, count, vars) {
  	initL10N(app);
923852aa1   Kload   Official Owncloud...
136
  	var identifier = '_' + text_singular + '_::_' + text_plural + '_';
31b7f2792   Kload   Upgrade to ownclo...
137
138
139
  	if( typeof( t.cache[app][identifier] ) !== 'undefined' ){
  		var translation = t.cache[app][identifier];
  		if ($.isArray(translation)) {
a293d369c   Kload   Update sources to...
140
  			var plural = t.plural_function[app](count);
31b7f2792   Kload   Upgrade to ownclo...
141
  			return t(app, translation[plural.plural], vars, count);
03e52840d   Kload   Init
142
143
  		}
  	}
31b7f2792   Kload   Upgrade to ownclo...
144
145
146
147
  
  	if(count === 1) {
  		return t(app, text_singular, vars, count);
  	}
03e52840d   Kload   Init
148
  	else{
31b7f2792   Kload   Upgrade to ownclo...
149
  		return t(app, text_plural, vars, count);
03e52840d   Kload   Init
150
151
  	}
  }
03e52840d   Kload   Init
152

31b7f2792   Kload   Upgrade to ownclo...
153
  /**
6d9380f96   Cédric Dupont   Update sources OC...
154
155
156
  * Sanitizes a HTML string by replacing all potential dangerous characters with HTML entities
  * @param {string} s String to sanitize
  * @return {string} Sanitized string
03e52840d   Kload   Init
157
158
  */
  function escapeHTML(s) {
6d9380f96   Cédric Dupont   Update sources OC...
159
  	return s.toString().split('&').join('&amp;').split('<').join('&lt;').split('>').join('&gt;').split('"').join('&quot;').split('\'').join('&#039;');
03e52840d   Kload   Init
160
161
162
163
  }
  
  /**
  * Get the path to download a file
6d9380f96   Cédric Dupont   Update sources OC...
164
165
166
167
  * @param {string} file The filename
  * @param {string} dir The directory the file is in - e.g. $('#dir').val()
  * @return {string} Path to download the file
  * @deprecated use Files.getDownloadURL() instead
03e52840d   Kload   Init
168
169
170
171
172
173
174
175
176
177
178
  */
  function fileDownloadPath(dir, file) {
  	return OC.filePath('files', 'ajax', 'download.php')+'?files='+encodeURIComponent(file)+'&dir='+encodeURIComponent(dir);
  }
  
  var OC={
  	PERMISSION_CREATE:4,
  	PERMISSION_READ:1,
  	PERMISSION_UPDATE:2,
  	PERMISSION_DELETE:8,
  	PERMISSION_SHARE:16,
31b7f2792   Kload   Upgrade to ownclo...
179
  	PERMISSION_ALL:31,
6d9380f96   Cédric Dupont   Update sources OC...
180
  	/* jshint camelcase: false */
03e52840d   Kload   Init
181
182
183
  	webroot:oc_webroot,
  	appswebroots:(typeof oc_appswebroots !== 'undefined') ? oc_appswebroots:false,
  	currentUser:(typeof oc_current_user!=='undefined')?oc_current_user:false,
6d9380f96   Cédric Dupont   Update sources OC...
184
185
186
  	config: window.oc_config,
  	appConfig: window.oc_appconfig || {},
  	theme: window.oc_defaults || {},
03e52840d   Kload   Init
187
  	coreApps:['', 'admin','log','search','settings','core','3rdparty'],
6d9380f96   Cédric Dupont   Update sources OC...
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
  	menuSpeed: 100,
  
  	/**
  	 * Get an absolute url to a file in an app
  	 * @param {string} app the id of the app the file belongs to
  	 * @param {string} file the file path relative to the app folder
  	 * @return {string} Absolute URL to a file
  	 */
  	linkTo:function(app,file){
  		return OC.filePath(app,'',file);
  	},
  	
  	/**
  	 * Creates a relative url for remote use
  	 * @param {string} service id
  	 * @return {string} the url
  	 */
  	linkToRemoteBase:function(service) {
  		return OC.webroot + '/remote.php/' + service;
  	},
  
  	/**
  	 * @brief Creates an absolute url for remote use
  	 * @param {string} service id
  	 * @return {string} the url
  	 */
  	linkToRemote:function(service) {
  		return window.location.protocol + '//' + window.location.host + OC.linkToRemoteBase(service);
  	},
  
  	/**
  	 * Gets the base path for the given OCS API service.
  	 * @param {string} service name
  	 * @return {string} OCS API base path
  	 */
  	linkToOCS: function(service) {
  		return window.location.protocol + '//' + window.location.host + OC.webroot + '/ocs/v1.php/' + service + '/';
  	},
837968727   Kload   [enh] Upgrade to ...
226
227
228
  
  	/**
  	 * Generates the absolute url for the given relative url, which can contain parameters.
837968727   Kload   [enh] Upgrade to ...
229
230
  	 * @param {string} url
  	 * @param params
6d9380f96   Cédric Dupont   Update sources OC...
231
  	 * @return {string} Absolute URL for the given relative URL
837968727   Kload   [enh] Upgrade to ...
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
  	 */
  	generateUrl: function(url, params) {
  		var _build = function (text, vars) {
  			return text.replace(/{([^{}]*)}/g,
  				function (a, b) {
  					var r = vars[b];
  					return typeof r === 'string' || typeof r === 'number' ? r : a;
  				}
  			);
  		};
  		if (url.charAt(0) !== '/') {
  			url = '/' + url;
  
  		}
  		return OC.webroot + '/index.php' + _build(url, params);
  	},
03e52840d   Kload   Init
248
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
249
250
251
252
253
  	 * Get the absolute url for a file in an app
  	 * @param {string} app the id of the app
  	 * @param {string} type the type of the file to link to (e.g. css,img,ajax.template)
  	 * @param {string} file the filename
  	 * @return {string} Absolute URL for a file in an app
03e52840d   Kload   Init
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
  	 */
  	filePath:function(app,type,file){
  		var isCore=OC.coreApps.indexOf(app)!==-1,
  			link=OC.webroot;
  		if((file.substring(file.length-3) === 'php' || file.substring(file.length-3) === 'css') && !isCore){
  			link+='/index.php/apps/' + app;
  			if (file != 'index.php') {
  				link+='/';
  				if(type){
  					link+=encodeURI(type + '/');
  				}
  				link+= file;
  			}
  		}else if(file.substring(file.length-3) !== 'php' && !isCore){
  			link=OC.appswebroots[app];
  			if(type){
  				link+= '/'+type+'/';
  			}
  			if(link.substring(link.length-1) !== '/'){
  				link+='/';
  			}
  			link+=file;
  		}else{
  			if ((app == 'settings' || app == 'core' || app == 'search') && type == 'ajax') {
  				link+='/index.php/';
  			}
  			else {
  				link+='/';
  			}
  			if(!isCore){
  				link+='apps/';
  			}
  			if (app !== '') {
  				app+='/';
  				link+=app;
  			}
  			if(type){
  				link+=type+'/';
  			}
  			link+=file;
  		}
  		return link;
  	},
6d9380f96   Cédric Dupont   Update sources OC...
297
298
299
300
301
302
303
304
305
  	
  	/**
  	 * Redirect to the target URL, can also be used for downloads.
  	 * @param {string} targetURL URL to redirect to
  	 */
  	redirect: function(targetURL) {
  		window.location = targetURL;
  	},
  	
03e52840d   Kload   Init
306
307
  	/**
  	 * get the absolute path to an image file
6d9380f96   Cédric Dupont   Update sources OC...
308
309
310
311
312
  	 * if no extension is given for the image, it will automatically decide 
  	 * between .png and .svg based on what the browser supports
  	 * @param {string} app the app id to which the image belongs
  	 * @param {string} file the name of the image file
  	 * @return {string}
03e52840d   Kload   Init
313
314
315
  	 */
  	imagePath:function(app,file){
  		if(file.indexOf('.')==-1){//if no extension is given, use png or svg depending on browser support
6d9380f96   Cédric Dupont   Update sources OC...
316
  			file+=(OC.Util.hasSVGSupport())?'.svg':'.png';
03e52840d   Kload   Init
317
318
319
  		}
  		return OC.filePath(app,'img',file);
  	},
6d9380f96   Cédric Dupont   Update sources OC...
320
  	
03e52840d   Kload   Init
321
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
322
323
324
325
326
  	 * Load a script for the server and load it. If the script is already loaded, 
  	 * the event handler will be called directly
  	 * @param {string} app the app id to which the script belongs
  	 * @param {string} script the filename of the script
  	 * @param ready event handler to be called when the script is loaded
03e52840d   Kload   Init
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
  	 */
  	addScript:function(app,script,ready){
  		var deferred, path=OC.filePath(app,'js',script+'.js');
  		if(!OC.addScript.loaded[path]){
  			if(ready){
  				deferred=$.getScript(path,ready);
  			}else{
  				deferred=$.getScript(path);
  			}
  			OC.addScript.loaded[path]=deferred;
  		}else{
  			if(ready){
  				ready();
  			}
  		}
  		return OC.addScript.loaded[path];
  	},
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
345
346
347
  	 * Loads a CSS file
  	 * @param {string} app the app id to which the css style belongs
  	 * @param {string} style the filename of the css file
03e52840d   Kload   Init
348
349
350
351
352
353
354
355
356
357
358
359
360
  	 */
  	addStyle:function(app,style){
  		var path=OC.filePath(app,'css',style+'.css');
  		if(OC.addStyle.loaded.indexOf(path)===-1){
  			OC.addStyle.loaded.push(path);
  			if (document.createStyleSheet) {
  				document.createStyleSheet(path);
  			} else {
  				style=$('<link rel="stylesheet" type="text/css" href="'+path+'"/>');
  				$('head').append(style);
  			}
  		}
  	},
6d9380f96   Cédric Dupont   Update sources OC...
361
362
363
364
  	
  	/**
  	 * @todo Write the documentation
  	 */
03e52840d   Kload   Init
365
366
367
  	basename: function(path) {
  		return path.replace(/\\/g,'/').replace( /.*\//, '' );
  	},
6d9380f96   Cédric Dupont   Update sources OC...
368
369
370
371
  	
  	/**
  	 *  @todo Write the documentation
  	 */
03e52840d   Kload   Init
372
373
374
  	dirname: function(path) {
  		return path.replace(/\\/g,'/').replace(/\/[^\/]*$/, '');
  	},
6d9380f96   Cédric Dupont   Update sources OC...
375
  	
03e52840d   Kload   Init
376
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
377
378
  	 * Do a search query and display the results
  	 * @param {string} query the search query
03e52840d   Kload   Init
379
  	 */
6d9380f96   Cédric Dupont   Update sources OC...
380
  	search: _.debounce(function(query){
03e52840d   Kload   Init
381
382
383
384
385
386
387
  		if(query){
  			OC.addStyle('search','results');
  			$.getJSON(OC.filePath('search','ajax','search.php')+'?query='+encodeURIComponent(query), function(results){
  				OC.search.lastResults=results;
  				OC.search.showResults(results);
  			});
  		}
6d9380f96   Cédric Dupont   Update sources OC...
388
  	}, 500),
03e52840d   Kload   Init
389
390
391
392
393
394
  	dialogs:OCdialogs,
  	mtime2date:function(mtime) {
  		mtime = parseInt(mtime,10);
  		var date = new Date(1000*mtime);
  		return date.getDate()+'.'+(date.getMonth()+1)+'.'+date.getFullYear()+', '+date.getHours()+':'+date.getMinutes();
  	},
6d9380f96   Cédric Dupont   Update sources OC...
395
  	
03e52840d   Kload   Init
396
  	/**
31b7f2792   Kload   Upgrade to ownclo...
397
  	 * Parses a URL query string into a JS map
6d9380f96   Cédric Dupont   Update sources OC...
398
  	 * @param {string} queryString query string in the format param1=1234&param2=abcde&param3=xyz
31b7f2792   Kload   Upgrade to ownclo...
399
400
401
402
  	 * @return map containing key/values matching the URL parameters
  	 */
  	parseQueryString:function(queryString){
  		var parts,
6d9380f96   Cédric Dupont   Update sources OC...
403
  			pos,
31b7f2792   Kload   Upgrade to ownclo...
404
405
406
407
408
409
410
  			components,
  			result = {},
  			key,
  			value;
  		if (!queryString){
  			return null;
  		}
6d9380f96   Cédric Dupont   Update sources OC...
411
412
413
  		pos = queryString.indexOf('?');
  		if (pos >= 0){
  			queryString = queryString.substr(pos + 1);
31b7f2792   Kload   Upgrade to ownclo...
414
  		}
6d9380f96   Cédric Dupont   Update sources OC...
415
  		parts = queryString.replace(/\+/g, '%20').split('&');
31b7f2792   Kload   Upgrade to ownclo...
416
  		for (var i = 0; i < parts.length; i++){
6d9380f96   Cédric Dupont   Update sources OC...
417
418
419
420
421
422
423
424
425
426
427
428
429
  			// split on first equal sign
  			var part = parts[i];
  			pos = part.indexOf('=');
  			if (pos >= 0) {
  				components = [
  					part.substr(0, pos),
  					part.substr(pos + 1)
  				];
  			}
  			else {
  				// key only
  				components = [part];
  			}
31b7f2792   Kload   Upgrade to ownclo...
430
431
432
433
434
435
436
  			if (!components.length){
  				continue;
  			}
  			key = decodeURIComponent(components[0]);
  			if (!key){
  				continue;
  			}
6d9380f96   Cédric Dupont   Update sources OC...
437
438
439
440
441
442
443
444
  			// if equal sign was there, return string
  			if (components.length > 1) {
  				result[key] = decodeURIComponent(components[1]);
  			}
  			// no equal sign => null value
  			else {
  				result[key] = null;
  			}
31b7f2792   Kload   Upgrade to ownclo...
445
446
447
  		}
  		return result;
  	},
6d9380f96   Cédric Dupont   Update sources OC...
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
  
  	/**
  	 * Builds a URL query from a JS map.
  	 * @param params parameter map
  	 * @return {string} String containing a URL query (without question) mark
  	 */
  	buildQueryString: function(params) {
  		if (!params) {
  			return '';
  		}
  		return $.map(params, function(value, key) {
  			var s = encodeURIComponent(key);
  			if (value !== null && typeof(value) !== 'undefined') {
  				s += '=' + encodeURIComponent(value);
  			}
  			return s;
  		}).join('&');
  	},
31b7f2792   Kload   Upgrade to ownclo...
466
  	/**
03e52840d   Kload   Init
467
  	 * Opens a popup with the setting for an app.
6d9380f96   Cédric Dupont   Update sources OC...
468
469
  	 * @param {string} appid The ID of the app e.g. 'calendar', 'contacts' or 'files'.
  	 * @param {boolean|string} loadJS If true 'js/settings.js' is loaded. If it's a string
03e52840d   Kload   Init
470
  	 * it will attempt to load a script by that name in the 'js' directory.
6d9380f96   Cédric Dupont   Update sources OC...
471
472
  	 * @param {boolean} [cache] If true the javascript file won't be forced refreshed. Defaults to true.
  	 * @param {string} [scriptName] The name of the PHP file to load. Defaults to 'settings.php' in
03e52840d   Kload   Init
473
474
475
476
477
478
479
480
481
  	 * the root of the app directory hierarchy.
  	 */
  	appSettings:function(args) {
  		if(typeof args === 'undefined' || typeof args.appid === 'undefined') {
  			throw { name: 'MissingParameter', message: 'The parameter appid is missing' };
  		}
  		var props = {scriptName:'settings.php', cache:true};
  		$.extend(props, args);
  		var settings = $('#appsettings');
6d9380f96   Cédric Dupont   Update sources OC...
482
  		if(settings.length === 0) {
03e52840d   Kload   Init
483
484
485
  			throw { name: 'MissingDOMElement', message: 'There has be be an element with id "appsettings" for the popup to show.' };
  		}
  		var popup = $('#appsettings_popup');
6d9380f96   Cédric Dupont   Update sources OC...
486
  		if(popup.length === 0) {
03e52840d   Kload   Init
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
  			$('body').prepend('<div class="popup hidden" id="appsettings_popup"></div>');
  			popup = $('#appsettings_popup');
  			popup.addClass(settings.hasClass('topright') ? 'topright' : 'bottomleft');
  		}
  		if(popup.is(':visible')) {
  			popup.hide().remove();
  		} else {
  			var arrowclass = settings.hasClass('topright') ? 'up' : 'left';
  			var jqxhr = $.get(OC.filePath(props.appid, '', props.scriptName), function(data) {
  				popup.html(data).ready(function() {
  					popup.prepend('<span class="arrow '+arrowclass+'"></span><h2>'+t('core', 'Settings')+'</h2><a class="close svg"></a>').show();
  					popup.find('.close').bind('click', function() {
  						popup.remove();
  					});
  					if(typeof props.loadJS !== 'undefined') {
  						var scriptname;
  						if(props.loadJS === true) {
  							scriptname = 'settings.js';
  						} else if(typeof props.loadJS === 'string') {
  							scriptname = props.loadJS;
  						} else {
  							throw { name: 'InvalidParameter', message: 'The "loadJS" parameter must be either boolean or a string.' };
  						}
  						if(props.cache) {
  							$.ajaxSetup({cache: true});
  						}
  						$.getScript(OC.filePath(props.appid, 'js', scriptname))
  						.fail(function(jqxhr, settings, e) {
  							throw e;
  						});
  					}
6d9380f96   Cédric Dupont   Update sources OC...
518
519
520
  					if(!OC.Util.hasSVGSupport()) {
  						OC.Util.replaceSVG();
  					}
03e52840d   Kload   Init
521
522
523
  				}).show();
  			}, 'html');
  		}
6d9380f96   Cédric Dupont   Update sources OC...
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
  	},
  
  	/**
  	 * For menu toggling
  	 * @todo Write documentation
  	 */
  	registerMenu: function($toggle, $menuEl) {
  		$menuEl.addClass('menu');
  		$toggle.on('click.menu', function(event) {
  			if ($menuEl.is(OC._currentMenu)) {
  				$menuEl.slideUp(OC.menuSpeed);
  				OC._currentMenu = null;
  				OC._currentMenuToggle = null;
  				return false;
  			}
  			// another menu was open?
  			else if (OC._currentMenu) {
  				// close it
  				OC._currentMenu.hide();
  			}
  			$menuEl.slideToggle(OC.menuSpeed);
  			OC._currentMenu = $menuEl;
  			OC._currentMenuToggle = $toggle;
  			return false;
  		});
  	},
  
  	/**
  	 *  @todo Write documentation
  	 */
  	unregisterMenu: function($toggle, $menuEl) {
  		// close menu if opened
  		if ($menuEl.is(OC._currentMenu)) {
  			$menuEl.slideUp(OC.menuSpeed);
  			OC._currentMenu = null;
  			OC._currentMenuToggle = null;
  		}
  		$toggle.off('click.menu').removeClass('menutoggle');
  		$menuEl.removeClass('menu');
  	},
  
  	/**
  	 * Wrapper for matchMedia
  	 *
  	 * This is makes it possible for unit tests to
  	 * stub matchMedia (which doesn't work in PhantomJS)
  	 * @todo Write documentation
  	 */
  	_matchMedia: function(media) {
  		if (window.matchMedia) {
  			return window.matchMedia(media);
  		}
  		return false;
03e52840d   Kload   Init
577
578
  	}
  };
6d9380f96   Cédric Dupont   Update sources OC...
579

03e52840d   Kload   Init
580
581
582
583
  OC.search.customResults={};
  OC.search.currentResult=-1;
  OC.search.lastQuery='';
  OC.search.lastResults={};
6d9380f96   Cédric Dupont   Update sources OC...
584
585
586
587
588
589
590
  //translations for result type ids, can be extended by apps
  OC.search.resultTypes={
  	file: t('core','File'),
  	folder: t('core','Folder'),
  	image: t('core','Image'),
  	audio: t('core','Audio')
  };
03e52840d   Kload   Init
591
592
  OC.addStyle.loaded=[];
  OC.addScript.loaded=[];
6d9380f96   Cédric Dupont   Update sources OC...
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
  /**
   * @todo Write documentation
   */
  OC.msg={
  	/**
  	 * @param selector
  	 * @todo Write documentation
  	 */
  	startSaving:function(selector){
  		OC.msg.startAction(selector, t('core', 'Saving...'));
  	},
  	
  	/**
  	 * @param selector
  	 * @param data
  	 * @todo Write documentation
  	 */
  	finishedSaving:function(selector, data){
  		OC.msg.finishedAction(selector, data);
  	},
  	
  	/**
  	 * @param selector
  	 * @param {string} message Message to display
  	 * @todo WRite documentation
  	 */
  	startAction:function(selector, message){
  		$(selector)
  			.html( message )
  			.removeClass('success')
  			.removeClass('error')
  			.stop(true, true)
  			.show();
  	},
  	
  	/**
  	 * @param selector
  	 * @param data
  	 * @todo Write documentation
  	 */
  	finishedAction:function(selector, data){
  		if( data.status === "success" ){
  			$(selector).html( data.data.message )
  				.addClass('success')
  				.stop(true, true)
  				.delay(3000)
  				.fadeOut(900);
  		}else{
  			$(selector).html( data.data.message ).addClass('error');
  		}
  	}
  };
  
  /**
   * @todo Write documentation
   */
03e52840d   Kload   Init
649
650
651
  OC.Notification={
  	queuedNotifications: [],
  	getDefaultNotificationFunction: null,
6d9380f96   Cédric Dupont   Update sources OC...
652
653
654
655
656
  	
  	/**
  	 * @param callback
  	 * @todo Write documentation
  	 */
03e52840d   Kload   Init
657
658
659
  	setDefault: function(callback) {
  		OC.Notification.getDefaultNotificationFunction = callback;
  	},
6d9380f96   Cédric Dupont   Update sources OC...
660
661
662
663
664
665
  	
  	/**
  	 * Hides a notification
  	 * @param callback
  	 * @todo Write documentation
  	 */
03e52840d   Kload   Init
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
  	hide: function(callback) {
  		$('#notification').fadeOut('400', function(){
  			if (OC.Notification.isHidden()) {
  				if (OC.Notification.getDefaultNotificationFunction) {
  					OC.Notification.getDefaultNotificationFunction.call();
  				}
  			}
  			if (callback) {
  				callback.call();
  			}
  			$('#notification').empty();
  			if(OC.Notification.queuedNotifications.length > 0){
  				OC.Notification.showHtml(OC.Notification.queuedNotifications[0]);
  				OC.Notification.queuedNotifications.shift();
  			}
  		});
  	},
6d9380f96   Cédric Dupont   Update sources OC...
683
684
685
686
687
688
689
  	
  	/**
  	 * Shows a notification as HTML without being sanitized before.
  	 * If you pass unsanitized user input this may lead to a XSS vulnerability.
  	 * Consider using show() instead of showHTML()
  	 * @param {string} html Message to display
  	 */
03e52840d   Kload   Init
690
  	showHtml: function(html) {
6d9380f96   Cédric Dupont   Update sources OC...
691
692
693
694
  		var notification = $('#notification');
  		if((notification.filter('span.undo').length == 1) || OC.Notification.isHidden()){
  			notification.html(html);
  			notification.fadeIn().css('display','inline-block');
03e52840d   Kload   Init
695
696
697
698
  		}else{
  			OC.Notification.queuedNotifications.push(html);
  		}
  	},
6d9380f96   Cédric Dupont   Update sources OC...
699
700
701
702
703
  	
  	/**
  	 * Shows a sanitized notification
  	 * @param {string} text Message to display
  	 */
03e52840d   Kload   Init
704
  	show: function(text) {
6d9380f96   Cédric Dupont   Update sources OC...
705
706
707
708
  		var notification = $('#notification');
  		if((notification.filter('span.undo').length == 1) || OC.Notification.isHidden()){
  			notification.text(text);
  			notification.fadeIn().css('display','inline-block');
03e52840d   Kload   Init
709
  		}else{
31b7f2792   Kload   Upgrade to ownclo...
710
  			OC.Notification.queuedNotifications.push($('<div/>').text(text).html());
03e52840d   Kload   Init
711
712
  		}
  	},
6d9380f96   Cédric Dupont   Update sources OC...
713
714
715
716
717
  	
  	/**
  	 * Returns whether a notification is hidden. 
  	 * @return {boolean}
  	 */
03e52840d   Kload   Init
718
719
720
721
  	isHidden: function() {
  		return ($("#notification").text() === '');
  	}
  };
6d9380f96   Cédric Dupont   Update sources OC...
722
723
724
  /**
   * @todo Write documentation
   */
03e52840d   Kload   Init
725
726
  OC.Breadcrumb={
  	container:null,
6d9380f96   Cédric Dupont   Update sources OC...
727
728
729
730
731
732
733
  	/**
  	 * @todo Write documentation
  	 * @param dir
  	 * @param leafName
  	 * @param leafLink
  	 */
  	show:function(dir, leafName, leafLink){
31b7f2792   Kload   Upgrade to ownclo...
734
735
736
  		if(!this.container){//default
  			this.container=$('#controls');
  		}
6d9380f96   Cédric Dupont   Update sources OC...
737
  		this._show(this.container, dir, leafName, leafLink);
31b7f2792   Kload   Upgrade to ownclo...
738
739
740
  	},
  	_show:function(container, dir, leafname, leaflink){
  		var self = this;
a293d369c   Kload   Update sources to...
741

31b7f2792   Kload   Upgrade to ownclo...
742
  		this._clear(container);
a293d369c   Kload   Update sources to...
743

03e52840d   Kload   Init
744
  		// show home + path in subdirectories
a293d369c   Kload   Update sources to...
745
  		if (dir) {
03e52840d   Kload   Init
746
747
748
749
750
751
752
753
754
755
756
757
758
  			//add home
  			var link = OC.linkTo('files','index.php');
  
  			var crumb=$('<div/>');
  			crumb.addClass('crumb');
  
  			var crumbLink=$('<a/>');
  			crumbLink.attr('href',link);
  
  			var crumbImg=$('<img/>');
  			crumbImg.attr('src',OC.imagePath('core','places/home'));
  			crumbLink.append(crumbImg);
  			crumb.append(crumbLink);
31b7f2792   Kload   Upgrade to ownclo...
759
  			container.prepend(crumb);
03e52840d   Kload   Init
760
761
762
763
764
765
766
767
  
  			//add path parts
  			var segments = dir.split('/');
  			var pathurl = '';
  			jQuery.each(segments, function(i,name) {
  				if (name !== '') {
  					pathurl = pathurl+'/'+name;
  					var link = OC.linkTo('files','index.php')+'?dir='+encodeURIComponent(pathurl);
31b7f2792   Kload   Upgrade to ownclo...
768
  					self._push(container, name, link);
03e52840d   Kload   Init
769
770
771
  				}
  			});
  		}
a293d369c   Kload   Update sources to...
772

03e52840d   Kload   Init
773
774
  		//add leafname
  		if (leafname && leaflink) {
31b7f2792   Kload   Upgrade to ownclo...
775
  			this._push(container, leafname, leaflink);
03e52840d   Kload   Init
776
777
  		}
  	},
6d9380f96   Cédric Dupont   Update sources OC...
778
779
780
781
782
783
  	
  	/**
  	 * @todo Write documentation
  	 * @param {string} name
  	 * @param {string} link
  	 */
03e52840d   Kload   Init
784
  	push:function(name, link){
31b7f2792   Kload   Upgrade to ownclo...
785
786
  		if(!this.container){//default
  			this.container=$('#controls');
03e52840d   Kload   Init
787
  		}
31b7f2792   Kload   Upgrade to ownclo...
788
789
790
  		return this._push(OC.Breadcrumb.container, name, link);
  	},
  	_push:function(container, name, link){
03e52840d   Kload   Init
791
792
793
794
795
796
797
  		var crumb=$('<div/>');
  		crumb.addClass('crumb').addClass('last');
  
  		var crumbLink=$('<a/>');
  		crumbLink.attr('href',link);
  		crumbLink.text(name);
  		crumb.append(crumbLink);
31b7f2792   Kload   Upgrade to ownclo...
798
  		var existing=container.find('div.crumb');
03e52840d   Kload   Init
799
800
801
802
  		if(existing.length){
  			existing.removeClass('last');
  			existing.last().after(crumb);
  		}else{
31b7f2792   Kload   Upgrade to ownclo...
803
  			container.prepend(crumb);
03e52840d   Kload   Init
804
  		}
03e52840d   Kload   Init
805
806
  		return crumb;
  	},
6d9380f96   Cédric Dupont   Update sources OC...
807
808
809
810
  	
  	/**
  	 * @todo Write documentation
  	 */
03e52840d   Kload   Init
811
  	pop:function(){
31b7f2792   Kload   Upgrade to ownclo...
812
813
  		if(!this.container){//default
  			this.container=$('#controls');
03e52840d   Kload   Init
814
  		}
31b7f2792   Kload   Upgrade to ownclo...
815
816
  		this.container.find('div.crumb').last().remove();
  		this.container.find('div.crumb').last().addClass('last');
03e52840d   Kload   Init
817
  	},
6d9380f96   Cédric Dupont   Update sources OC...
818
819
820
821
  	
  	/**
  	 * @todo Write documentation
  	 */
03e52840d   Kload   Init
822
  	clear:function(){
31b7f2792   Kload   Upgrade to ownclo...
823
824
  		if(!this.container){//default
  			this.container=$('#controls');
03e52840d   Kload   Init
825
  		}
31b7f2792   Kload   Upgrade to ownclo...
826
827
828
829
  		this._clear(this.container);
  	},
  	_clear:function(container) {
  		container.find('div.crumb').remove();
03e52840d   Kload   Init
830
831
832
833
  	}
  };
  
  if(typeof localStorage !=='undefined' && localStorage !== null){
6d9380f96   Cédric Dupont   Update sources OC...
834
835
836
  	/**
  	 * User and instance aware localstorage
  	 */
03e52840d   Kload   Init
837
838
  	OC.localStorage={
  		namespace:'oc_'+OC.currentUser+'_'+OC.webroot+'_',
6d9380f96   Cédric Dupont   Update sources OC...
839
840
841
842
843
844
  		
  		/**
  		 * Whether the storage contains items
  		 * @param {string} name
  		 * @return {boolean}
  		 */
03e52840d   Kload   Init
845
846
847
  		hasItem:function(name){
  			return OC.localStorage.getItem(name)!==null;
  		},
6d9380f96   Cédric Dupont   Update sources OC...
848
849
850
851
852
853
  		
  		/**
  		 * Add an item to the storage
  		 * @param {string} name
  		 * @param {string} item
  		 */
03e52840d   Kload   Init
854
855
856
  		setItem:function(name,item){
  			return localStorage.setItem(OC.localStorage.namespace+name,JSON.stringify(item));
  		},
6d9380f96   Cédric Dupont   Update sources OC...
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
  		
  		/**
  		 * Removes an item from the storage
  		 * @param {string} name
  		 * @param {string} item
  		 */
  		removeItem:function(name,item){
  			return localStorage.removeItem(OC.localStorage.namespace+name);
  		},
  		
  		/**
  		 * Get an item from the storage
  		 * @param {string} name
  		 * @return {null|string}
  		 */
03e52840d   Kload   Init
872
873
  		getItem:function(name){
  			var item = localStorage.getItem(OC.localStorage.namespace+name);
6d9380f96   Cédric Dupont   Update sources OC...
874
  			if(item === null) {
03e52840d   Kload   Init
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
  				return null;
  			} else if (typeof JSON === 'undefined') {
  				//fallback to jquery for IE6/7/8
  				return $.parseJSON(item);
  			} else {
  				return JSON.parse(item);
  			}
  		}
  	};
  }else{
  	//dummy localstorage
  	OC.localStorage={
  		hasItem:function(){
  			return false;
  		},
  		setItem:function(){
  			return false;
  		},
  		getItem:function(){
  			return null;
  		}
  	};
  }
  
  /**
03e52840d   Kload   Init
900
   * check if the browser support svg images
6d9380f96   Cédric Dupont   Update sources OC...
901
   * @return {boolean}
03e52840d   Kload   Init
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
   */
  function SVGSupport() {
  	return SVGSupport.checkMimeType.correct && !!document.createElementNS && !!document.createElementNS('http://www.w3.org/2000/svg', "svg").createSVGRect;
  }
  SVGSupport.checkMimeType=function(){
  	$.ajax({
  		url: OC.imagePath('core','breadcrumb.svg'),
  		success:function(data,text,xhr){
  			var headerParts=xhr.getAllResponseHeaders().split("
  ");
  			var headers={};
  			$.each(headerParts,function(i,text){
  				if(text){
  					var parts=text.split(':',2);
  					if(parts.length===2){
  						var value=parts[1].trim();
  						if(value[0]==='"'){
  							value=value.substr(1,value.length-2);
  						}
6d9380f96   Cédric Dupont   Update sources OC...
921
  						headers[parts[0].toLowerCase()]=value;
03e52840d   Kload   Init
922
923
924
  					}
  				}
  			});
6d9380f96   Cédric Dupont   Update sources OC...
925
926
  			if(headers["content-type"]!=='image/svg+xml'){
  				OC.Util.replaceSVG();
03e52840d   Kload   Init
927
928
929
930
931
932
  				SVGSupport.checkMimeType.correct=false;
  			}
  		}
  	});
  };
  SVGSupport.checkMimeType.correct=true;
6d9380f96   Cédric Dupont   Update sources OC...
933
934
935
936
937
938
939
  /**
   * Replace all svg images with png for browser compatibility
   * @param $el
   * @deprecated use OC.Util.replaceSVG instead
   */
  function replaceSVG($el){
  	return OC.Util.replaceSVG($el);
03e52840d   Kload   Init
940
941
942
  }
  
  /**
6d9380f96   Cédric Dupont   Update sources OC...
943
944
   * prototypical inheritance functions
   * @todo Write documentation
03e52840d   Kload   Init
945
946
947
948
949
950
951
952
953
954
   * usage:
   * MySubObject=object(MyObject)
   */
  function object(o) {
  	function F() {}
  	F.prototype = o;
  	return new F();
  }
  
  /**
a293d369c   Kload   Update sources to...
955
956
957
958
959
   * Initializes core
   */
  function initCore() {
  
  	/**
6d9380f96   Cédric Dupont   Update sources OC...
960
  	 * Calls the server periodically to ensure that session doesn't
a293d369c   Kload   Update sources to...
961
962
963
  	 * time out
  	 */
  	function initSessionHeartBeat(){
6d9380f96   Cédric Dupont   Update sources OC...
964
965
  		// max interval in seconds set to 24 hours
  		var maxInterval = 24 * 3600;
a293d369c   Kload   Update sources to...
966
967
968
969
970
971
972
973
974
  		// interval in seconds
  		var interval = 900;
  		if (oc_config.session_lifetime) {
  			interval = Math.floor(oc_config.session_lifetime / 2);
  		}
  		// minimum one minute
  		if (interval < 60) {
  			interval = 60;
  		}
6d9380f96   Cédric Dupont   Update sources OC...
975
976
977
978
979
980
981
  		if (interval > maxInterval) {
  			interval = maxInterval;
  		}
  		var url = OC.generateUrl('/heartbeat');
  		setInterval(function(){
  			$.post(url);
  		}, interval * 1000);
a293d369c   Kload   Update sources to...
982
  	}
6d9380f96   Cédric Dupont   Update sources OC...
983
  	// session heartbeat (defaults to enabled)
a293d369c   Kload   Update sources to...
984
985
986
987
988
  	if (typeof(oc_config.session_keepalive) === 'undefined' ||
  		!!oc_config.session_keepalive) {
  
  		initSessionHeartBeat();
  	}
03e52840d   Kload   Init
989

6d9380f96   Cédric Dupont   Update sources OC...
990
991
  	if(!OC.Util.hasSVGSupport()){ //replace all svg images with png images for browser that dont support svg
  		OC.Util.replaceSVG();
03e52840d   Kload   Init
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
  	}else{
  		SVGSupport.checkMimeType();
  	}
  	$('form.searchbox').submit(function(event){
  		event.preventDefault();
  	});
  	$('#searchbox').keyup(function(event){
  		if(event.keyCode===13){//enter
  			if(OC.search.currentResult>-1){
  				var result=$('#searchresults tr.result a')[OC.search.currentResult];
  				window.location = $(result).attr('href');
  			}
  		}else if(event.keyCode===38){//up
  			if(OC.search.currentResult>0){
  				OC.search.currentResult--;
  				OC.search.renderCurrent();
  			}
  		}else if(event.keyCode===40){//down
  			if(OC.search.lastResults.length>OC.search.currentResult+1){
  				OC.search.currentResult++;
  				OC.search.renderCurrent();
  			}
  		}else if(event.keyCode===27){//esc
  			OC.search.hide();
31b7f2792   Kload   Upgrade to ownclo...
1016
1017
1018
  			if (FileList && typeof FileList.unfilter === 'function') { //TODO add hook system
  				FileList.unfilter();
  			}
03e52840d   Kload   Init
1019
1020
1021
1022
1023
  		}else{
  			var query=$('#searchbox').val();
  			if(OC.search.lastQuery!==query){
  				OC.search.lastQuery=query;
  				OC.search.currentResult=-1;
31b7f2792   Kload   Upgrade to ownclo...
1024
1025
1026
  				if (FileList && typeof FileList.filter === 'function') { //TODO add hook system
  						FileList.filter(query);
  				}
03e52840d   Kload   Init
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
  				if(query.length>2){
  					OC.search(query);
  				}else{
  					if(OC.search.hide){
  						OC.search.hide();
  					}
  				}
  			}
  		}
  	});
31b7f2792   Kload   Upgrade to ownclo...
1037
1038
1039
1040
1041
1042
  	var setShowPassword = function(input, label) {
  		input.showPassword().keyup();
  	};
  	setShowPassword($('#adminpass'), $('label[for=show]'));
  	setShowPassword($('#pass2'), $('label[for=personal-show]'));
  	setShowPassword($('#dbpass'), $('label[for=dbpassword]'));
03e52840d   Kload   Init
1043

03e52840d   Kload   Init
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
  	var checkShowCredentials = function() {
  		var empty = false;
  		$('input#user, input#password').each(function() {
  			if ($(this).val() === '') {
  				empty = true;
  			}
  		});
  		if(empty) {
  			$('#submit').fadeOut();
  			$('#remember_login').hide();
  			$('#remember_login+label').fadeOut();
  		} else {
  			$('#submit').fadeIn();
  			$('#remember_login').show();
  			$('#remember_login+label').fadeIn();
  		}
  	};
  	// hide log in button etc. when form fields not filled
  	// commented out due to some browsers having issues with it
  	// checkShowCredentials();
  	// $('input#user, input#password').keyup(checkShowCredentials);
6d9380f96   Cédric Dupont   Update sources OC...
1065
  	// user menu
03e52840d   Kload   Init
1066
1067
  	$('#settings #expand').keydown(function(event) {
  		if (event.which === 13 || event.which === 32) {
6d9380f96   Cédric Dupont   Update sources OC...
1068
  			$('#expand').click();
03e52840d   Kload   Init
1069
1070
1071
  		}
  	});
  	$('#settings #expand').click(function(event) {
6d9380f96   Cédric Dupont   Update sources OC...
1072
  		$('#settings #expanddiv').slideToggle(OC.menuSpeed);
03e52840d   Kload   Init
1073
1074
1075
1076
1077
  		event.stopPropagation();
  	});
  	$('#settings #expanddiv').click(function(event){
  		event.stopPropagation();
  	});
6d9380f96   Cédric Dupont   Update sources OC...
1078
1079
1080
  	//hide the user menu when clicking outside it
  	$(document).click(function(){
  		$('#settings #expanddiv').slideUp(OC.menuSpeed);
03e52840d   Kload   Init
1081
1082
1083
  	});
  
  	// all the tipsy stuff needs to be here (in reverse order) to work
03e52840d   Kload   Init
1084
1085
1086
1087
  	$('.displayName .action').tipsy({gravity:'se', fade:true, live:true});
  	$('.password .action').tipsy({gravity:'se', fade:true, live:true});
  	$('#upload').tipsy({gravity:'w', fade:true});
  	$('.selectedActions a').tipsy({gravity:'s', fade:true, live:true});
31b7f2792   Kload   Upgrade to ownclo...
1088
  	$('a.action.delete').tipsy({gravity:'e', fade:true, live:true});
03e52840d   Kload   Init
1089
  	$('a.action').tipsy({gravity:'s', fade:true, live:true});
03e52840d   Kload   Init
1090
  	$('td .modified').tipsy({gravity:'s', fade:true, live:true});
6d9380f96   Cédric Dupont   Update sources OC...
1091
  	$('td.lastLogin').tipsy({gravity:'s', fade:true, html:true});
03e52840d   Kload   Init
1092
  	$('input').tipsy({gravity:'w', fade:true});
6d9380f96   Cédric Dupont   Update sources OC...
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
  
  	// toggle for menus
  	$(document).on('mouseup.closemenus', function(event) {
  		var $el = $(event.target);
  		if ($el.closest('.menu').length || $el.closest('.menutoggle').length) {
  			// don't close when clicking on the menu directly or a menu toggle
  			return false;
  		}
  		if (OC._currentMenu) {
  			OC._currentMenu.slideUp(OC.menuSpeed);
  		}
  		OC._currentMenu = null;
  		OC._currentMenuToggle = null;
03e52840d   Kload   Init
1106
  	});
6d9380f96   Cédric Dupont   Update sources OC...
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
  
  
  	/**
  	 * Set up the main menu toggle to react to media query changes.
  	 * If the screen is small enough, the main menu becomes a toggle.
  	 * If the screen is bigger, the main menu is not a toggle any more.
  	 */
  	function setupMainMenu() {
  		// toggle the navigation
  		var $toggle = $('#header .menutoggle');
  		var $navigation = $('#navigation');
  
  		// init the menu
  		OC.registerMenu($toggle, $navigation);
  		$toggle.data('oldhref', $toggle.attr('href'));
  		$toggle.attr('href', '#');
  		$navigation.hide();
  
  		// show loading feedback
  		$navigation.delegate('a', 'click', function(event) {
  			var $app = $(event.target);
  			if(!$app.is('a')) {
  				$app = $app.closest('a');
  			}
  			if(!event.ctrlKey) {
  				$app.addClass('app-loading');
  			}
  		});
  	}
  
  	setupMainMenu();
  
  	// just add snapper for logged in users
  	if($('#app-navigation').length && !$('html').hasClass('lte9')) {
  
  		// App sidebar on mobile
  		var snapper = new Snap({
  			element: document.getElementById('app-content'),
  			disable: 'right',
  			maxPosition: 250
  		});
  		$('#app-content').prepend('<div id="app-navigation-toggle" class="icon-menu" style="display:none;"></div>');
  		$('#app-navigation-toggle').click(function(){
  			if(snapper.state().state == 'left'){
  				snapper.close();
  			} else {
  				snapper.open('left');
  			}
  		});
  		// close sidebar when switching navigation entry
  		var $appNavigation = $('#app-navigation');
  		$appNavigation.delegate('a', 'click', function(event) {
  			var $target = $(event.target);
  			// don't hide navigation when changing settings or adding things
  			if($target.is('.app-navigation-noclose') ||
  				$target.closest('.app-navigation-noclose').length) {
  				return;
  			}
  			if($target.is('.add-new') ||
  				$target.closest('.add-new').length) {
  				return;
  			}
  			if($target.is('#app-settings') ||
  				$target.closest('#app-settings').length) {
  				return;
  			}
  			snapper.close();
  		});
  
  		var toggleSnapperOnSize = function() {
  			if($(window).width() > 768) {
  				snapper.close();
  				snapper.disable();
  			} else {
  				snapper.enable();
  			}
  		};
  
  		$(window).resize(_.debounce(toggleSnapperOnSize, 250));
  
  		// initial call
  		toggleSnapperOnSize();
  
  	}
a293d369c   Kload   Update sources to...
1191
1192
1193
  }
  
  $(document).ready(initCore);
03e52840d   Kload   Init
1194

03e52840d   Kload   Init
1195
1196
1197
1198
1199
1200
  /**
   * Filter Jquery selector by attribute value
   */
  $.fn.filterAttr = function(attr_name, attr_value) {
  	return this.filter(function() { return $(this).attr(attr_name) === attr_value; });
  };
6d9380f96   Cédric Dupont   Update sources OC...
1201
1202
1203
1204
1205
1206
1207
  /**
   * Returns a human readable file size
   * @param {number} size Size in bytes
   * @param {boolean} skipSmallSizes return '< 1 kB' for small files
   * @return {string}
   */
  function humanFileSize(size, skipSmallSizes) {
03e52840d   Kload   Init
1208
1209
1210
1211
1212
1213
1214
  	var humanList = ['B', 'kB', 'MB', 'GB', 'TB'];
  	// Calculate Log with base 1024: size = 1024 ** order
  	var order = size?Math.floor(Math.log(size) / Math.log(1024)):0;
  	// Stay in range of the byte sizes that are defined
  	order = Math.min(humanList.length - 1, order);
  	var readableFormat = humanList[order];
  	var relativeSize = (size / Math.pow(1024, order)).toFixed(1);
6d9380f96   Cédric Dupont   Update sources OC...
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
  	if(skipSmallSizes === true && order === 0) {
  		if(relativeSize !== "0.0"){
  			return '< 1 kB';
  		} else {
  			return '0 kB';
  		}
  	}
  	if(order < 2){
  		relativeSize = parseFloat(relativeSize).toFixed(0);
  	}
  	else if(relativeSize.substr(relativeSize.length-2,2)==='.0'){
03e52840d   Kload   Init
1226
1227
1228
1229
  		relativeSize=relativeSize.substr(0,relativeSize.length-2);
  	}
  	return relativeSize + ' ' + readableFormat;
  }
6d9380f96   Cédric Dupont   Update sources OC...
1230
1231
1232
1233
1234
  /**
   * Format an UNIX timestamp to a human understandable format
   * @param {number} date UNIX timestamp
   * @return {string} Human readable format
   */
03e52840d   Kload   Init
1235
1236
1237
1238
1239
1240
  function formatDate(date){
  	if(typeof date=='number'){
  		date=new Date(date);
  	}
  	return $.datepicker.formatDate(datepickerFormatDate, date)+' '+date.getHours()+':'+((date.getMinutes()<10)?'0':'')+date.getMinutes();
  }
6d9380f96   Cédric Dupont   Update sources OC...
1241
1242
1243
1244
1245
1246
1247
  // 
  /**
   * Get the value of a URL parameter
   * @link http://stackoverflow.com/questions/1403888/get-url-parameter-with-jquery
   * @param {string} name URL parameter
   * @return {string}
   */
31b7f2792   Kload   Upgrade to ownclo...
1248
1249
1250
1251
1252
  function getURLParameter(name) {
  	return decodeURI(
  			(RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, null])[1]
  			);
  }
03e52840d   Kload   Init
1253
  /**
6d9380f96   Cédric Dupont   Update sources OC...
1254
1255
   * Takes an absolute timestamp and return a string with a human-friendly relative date
   * @param {number} timestamp A Unix timestamp
03e52840d   Kload   Init
1256
1257
   */
  function relative_modified_date(timestamp) {
6d9380f96   Cédric Dupont   Update sources OC...
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
  	var timeDiff = Math.round((new Date()).getTime() / 1000) - timestamp;
  	var diffMinutes = Math.round(timeDiff/60);
  	var diffHours = Math.round(diffMinutes/60);
  	var diffDays = Math.round(diffHours/24);
  	var diffMonths = Math.round(diffDays/31);
  	if(timeDiff < 60) { return t('core','seconds ago'); }
  	else if(timeDiff < 3600) { return n('core','%n minute ago', '%n minutes ago', diffMinutes); }
  	else if(timeDiff < 86400) { return n('core', '%n hour ago', '%n hours ago', diffHours); }
  	else if(timeDiff < 86400) { return t('core','today'); }
  	else if(timeDiff < 172800) { return t('core','yesterday'); }
  	else if(timeDiff < 2678400) { return n('core', '%n day ago', '%n days ago', diffDays); }
  	else if(timeDiff < 5184000) { return t('core','last month'); }
  	else if(timeDiff < 31556926) { return n('core', '%n month ago', '%n months ago', diffMonths); }
  	else if(timeDiff < 63113852) { return t('core','last year'); }
03e52840d   Kload   Init
1272
1273
1274
1275
  	else { return t('core','years ago'); }
  }
  
  /**
6d9380f96   Cédric Dupont   Update sources OC...
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
   * Utility functions
   */
  OC.Util = {
  	// TODO: remove original functions from global namespace
  	humanFileSize: humanFileSize,
  	formatDate: formatDate,
  	/**
  	 * Returns whether the browser supports SVG
  	 * @return {boolean} true if the browser supports SVG, false otherwise
  	 */
  	// TODO: replace with original function
  	hasSVGSupport: SVGSupport,
  	/**
  	 * If SVG is not supported, replaces the given icon's extension
  	 * from ".svg" to ".png".
  	 * If SVG is supported, return the image path as is.
  	 * @param {string} file image path with svg extension
  	 * @return {string} fixed image path with png extension if SVG is not supported
  	 */
  	replaceSVGIcon: function(file) {
  		if (file && !OC.Util.hasSVGSupport()) {
  			var i = file.lastIndexOf('.svg');
  			if (i >= 0) {
  				file = file.substr(0, i) + '.png' + file.substr(i+4);
  			}
  		}
  		return file;
  	},
  	/**
  	 * Replace SVG images in all elements that have the "svg" class set
  	 * with PNG images.
  	 *
  	 * @param $el root element from which to search, defaults to $('body')
  	 */
  	replaceSVG: function($el) {
  		if (!$el) {
  			$el = $('body');
  		}
  		$el.find('img.svg').each(function(index,element){
  			element=$(element);
  			var src=element.attr('src');
  			element.attr('src',src.substr(0, src.length-3) + 'png');
  		});
  		$el.find('.svg').each(function(index,element){
  			element = $(element);
  			var background = element.css('background-image');
  			if (background){
  				var i = background.lastIndexOf('.svg');
  				if (i >= 0){
  					background = background.substr(0,i) + '.png' + background.substr(i + 4);
  					element.css('background-image', background);
  				}
  			}
  			element.find('*').each(function(index, element) {
  				element = $(element);
  				var background = element.css('background-image');
  				if (background) {
  					var i = background.lastIndexOf('.svg');
  					if(i >= 0){
  						background = background.substr(0,i) + '.png' + background.substr(i + 4);
  						element.css('background-image', background);
  					}
  				}
  			});
  		});
  	},
  
  	/**
  	 * Remove the time component from a given date
  	 *
  	 * @param {Date} date date
  	 * @return {Date} date with stripped time
  	 */
  	stripTime: function(date) {
  		// FIXME: likely to break when crossing DST
  		// would be better to use a library like momentJS
  		return new Date(date.getFullYear(), date.getMonth(), date.getDate());
  	}
  };
  
  /**
   * Utility class for the history API,
   * includes fallback to using the URL hash when
   * the browser doesn't support the history API.
   */
  OC.Util.History = {
  	_handlers: [],
  
  	/**
  	 * Push the current URL parameters to the history stack
  	 * and change the visible URL.
  	 * Note: this includes a workaround for IE8/IE9 that uses
  	 * the hash part instead of the search part.
  	 *
  	 * @param params to append to the URL, can be either a string
  	 * or a map
  	 */
  	pushState: function(params) {
  		var strParams;
  		if (typeof(params) === 'string') {
  			strParams = params;
  		}
  		else {
  			strParams = OC.buildQueryString(params);
  		}
  		if (window.history.pushState) {
  			var url = location.pathname + '?' + strParams;
  			window.history.pushState(params, '', url);
  		}
  		// use URL hash for IE8
  		else {
  			window.location.hash = '?' + strParams;
  			// inhibit next onhashchange that just added itself
  			// to the event queue
  			this._cancelPop = true;
  		}
  	},
  
  	/**
  	 * Add a popstate handler
  	 *
  	 * @param handler function
  	 */
  	addOnPopStateHandler: function(handler) {
  		this._handlers.push(handler);
  	},
  
  	/**
  	 * Parse a query string from the hash part of the URL.
  	 * (workaround for IE8 / IE9)
  	 */
  	_parseHashQuery: function() {
  		var hash = window.location.hash,
  			pos = hash.indexOf('?');
  		if (pos >= 0) {
  			return hash.substr(pos + 1);
  		}
  		if (hash.length) {
  			// remove hash sign
  			return hash.substr(1);
  		}
  		return '';
  	},
  
  	_decodeQuery: function(query) {
  		return query.replace(/\+/g, ' ');
  	},
  
  	/**
  	 * Parse the query/search part of the URL.
  	 * Also try and parse it from the URL hash (for IE8)
  	 *
  	 * @return map of parameters
  	 */
  	parseUrlQuery: function() {
  		var query = this._parseHashQuery(),
  			params;
  		// try and parse from URL hash first
  		if (query) {
  			params = OC.parseQueryString(this._decodeQuery(query));
  		}
  		// else read from query attributes
  		if (!params) {
  			params = OC.parseQueryString(this._decodeQuery(location.search));
  		}
  		return params || {};
  	},
  
  	_onPopState: function(e) {
  		if (this._cancelPop) {
  			this._cancelPop = false;
  			return;
  		}
  		var params;
  		if (!this._handlers.length) {
  			return;
  		}
  		params = (e && e.state) || this.parseUrlQuery() || {};
  		for (var i = 0; i < this._handlers.length; i++) {
  			this._handlers[i](params);
  		}
  	}
  };
  
  // fallback to hashchange when no history support
  if (window.history.pushState) {
  	window.onpopstate = _.bind(OC.Util.History._onPopState, OC.Util.History);
  }
  else {
  	$(window).on('hashchange', _.bind(OC.Util.History._onPopState, OC.Util.History));
  }
  
  /**
   * Get a variable by name
   * @param {string} name
   * @return {*}
03e52840d   Kload   Init
1472
1473
1474
1475
1476
   */
  OC.get=function(name) {
  	var namespaces = name.split(".");
  	var tail = namespaces.pop();
  	var context=window;
31b7f2792   Kload   Upgrade to ownclo...
1477

03e52840d   Kload   Init
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
  	for(var i = 0; i < namespaces.length; i++) {
  		context = context[namespaces[i]];
  		if(!context){
  			return false;
  		}
  	}
  	return context[tail];
  };
  
  /**
6d9380f96   Cédric Dupont   Update sources OC...
1488
1489
1490
   * Set a variable by name
   * @param {string} name
   * @param {*} value
03e52840d   Kload   Init
1491
1492
1493
1494
1495
   */
  OC.set=function(name, value) {
  	var namespaces = name.split(".");
  	var tail = namespaces.pop();
  	var context=window;
31b7f2792   Kload   Upgrade to ownclo...
1496

03e52840d   Kload   Init
1497
1498
1499
1500
1501
1502
1503
1504
  	for(var i = 0; i < namespaces.length; i++) {
  		if(!context[namespaces[i]]){
  			context[namespaces[i]]={};
  		}
  		context = context[namespaces[i]];
  	}
  	context[tail]=value;
  };
6d9380f96   Cédric Dupont   Update sources OC...
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
  // fix device width on windows phone
  (function() {
  	if ("-ms-user-select" in document.documentElement.style && navigator.userAgent.match(/IEMobile\/10\.0/)) {
  		var msViewportStyle = document.createElement("style");
  		msViewportStyle.appendChild(
  			document.createTextNode("@-ms-viewport{width:auto!important}")
  		);
  		document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
  	}
  })();
  
  /**
   * Namespace for apps
   */
  window.OCA = {};
03e52840d   Kload   Init
1520
1521
1522
1523
1524
1525
  /**
   * select a range in an input field
   * @link http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area
   * @param {type} start
   * @param {type} end
   */
31b7f2792   Kload   Upgrade to ownclo...
1526
  jQuery.fn.selectRange = function(start, end) {
03e52840d   Kload   Init
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
  	return this.each(function() {
  		if (this.setSelectionRange) {
  			this.focus();
  			this.setSelectionRange(start, end);
  		} else if (this.createTextRange) {
  			var range = this.createTextRange();
  			range.collapse(true);
  			range.moveEnd('character', end);
  			range.moveStart('character', start);
  			range.select();
  		}
  	});
  };
  
  /**
31b7f2792   Kload   Upgrade to ownclo...
1542
1543
1544
1545
1546
1547
1548
   * check if an element exists.
   * allows you to write if ($('#myid').exists()) to increase readability
   * @link http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery
   */
  jQuery.fn.exists = function(){
  	return this.length > 0;
  };