server/core/js/js.js

472 lines
12 KiB
JavaScript
Raw Normal View History

var oc_requesttoken = document.getElementsByTagName('head')[0].getAttribute('data-requesttoken');
/** @namespace OCP */
var OCP = Object.assign({}, window.OCP);
/**
* @namespace OC
*/
Object.assign(window.OC, {
2014-05-26 16:43:26 +00:00
/* jshint camelcase: false */
/**
* Capabilities
*
* @type array
*/
_capabilities: window.oc_capabilities || null,
2014-05-30 17:02:19 +00:00
theme: window.oc_defaults || {},
requestToken: oc_requesttoken,
/**
* Check if a user file is allowed to be handled.
* @param {string} file to check
*/
fileIsBlacklisted: function(file) {
return !!(file.match(OC.config.blacklist_files_regex));
},
/**
* Protocol that is used to access this Nextcloud instance
* @return {string} Used protocol
*/
getProtocol: function() {
return window.location.protocol.split(':')[0];
},
/**
* Returns the host used to access this Nextcloud instance
* Host is sometimes the same as the hostname but now always.
*
* Examples:
* http://example.com => example.com
* https://example.com => example.com
* http://example.com:8080 => example.com:8080
*
* @return {string} host
*
* @since 8.2
*/
getHost: function() {
return window.location.host;
},
/**
* Returns the hostname used to access this Nextcloud instance
* The hostname is always stripped of the port
*
* @return {string} hostname
* @since 9.0
*/
getHostName: function() {
return window.location.hostname;
},
/**
* Returns the port number used to access this Nextcloud instance
*
* @return {int} port number
*
* @since 8.2
*/
getPort: function() {
return window.location.port;
},
/**
* Returns the capabilities
*
* @return {array} capabilities
*
* @since 14.0
*/
getCapabilities: function() {
return OC._capabilities;
},
/**
* get the absolute path to an image file
* if no extension is given for the image, it will automatically decide
2014-04-21 11:46:33 +00:00
* 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}
2012-07-31 10:21:06 +00:00
*/
imagePath:function(app,file){
2016-06-23 10:15:16 +00:00
if(file.indexOf('.')==-1){//if no extension is given, use svg
file+='.svg';
}
return OC.filePath(app,'img',file);
},
/**
* URI-Encodes a file path but keep the path slashes.
*
* @param path path
* @return encoded path
*/
encodePath: function(path) {
if (!path) {
return path;
}
var parts = path.split('/');
var result = [];
for (var i = 0; i < parts.length; i++) {
result.push(encodeURIComponent(parts[i]));
}
return result.join('/');
},
/**
* Loads translations for the given app asynchronously.
*
* @param {String} app app name
* @param {Function} callback callback to call after loading
* @return {Promise}
*/
addTranslations: function(app, callback) {
return OC.L10N.load(app, callback);
},
2014-04-21 11:46:33 +00:00
/**
* Returns the base name of the given path.
* For example for "/abc/somefile.txt" it will return "somefile.txt"
*
* @param {String} path
* @return {String} base name
2014-04-21 11:46:33 +00:00
*/
basename: function(path) {
return path.replace(/\\/g,'/').replace( /.*\//, '' );
},
2014-04-21 11:46:33 +00:00
/**
* Returns the dir name of the given path.
* For example for "/abc/somefile.txt" it will return "/abc"
*
* @param {String} path
* @return {String} dir name
2014-04-21 11:46:33 +00:00
*/
dirname: function(path) {
2012-09-23 01:16:52 +00:00
return path.replace(/\\/g,'/').replace(/\/[^\/]*$/, '');
2012-09-08 22:35:02 +00:00
},
/**
* Returns whether the given paths are the same, without
* leading, trailing or doubled slashes and also removing
* the dot sections.
*
* @param {String} path1 first path
* @param {String} path2 second path
* @return {bool} true if the paths are the same
*
* @since 9.0
*/
isSamePath: function(path1, path2) {
var filterDot = function(p) {
return p !== '.';
};
var pathSections1 = _.filter((path1 || '').split('/'), filterDot);
var pathSections2 = _.filter((path2 || '').split('/'), filterDot);
path1 = OC.joinPaths.apply(OC, pathSections1);
path2 = OC.joinPaths.apply(OC, pathSections2);
return path1 === path2;
},
/**
* Join path sections
*
* @param {...String} path sections
*
* @return {String} joined path, any leading or trailing slash
* will be kept
*
* @since 8.2
*/
joinPaths: function() {
if (arguments.length < 1) {
return '';
}
var path = '';
// convert to array
var args = Array.prototype.slice.call(arguments);
// discard empty arguments
args = _.filter(args, function(arg) {
return arg.length > 0;
});
if (args.length < 1) {
return '';
}
var lastArg = args[args.length - 1];
var leadingSlash = args[0].charAt(0) === '/';
var trailingSlash = lastArg.charAt(lastArg.length - 1) === '/';
var sections = [];
var i;
for (i = 0; i < args.length; i++) {
sections = sections.concat(args[i].split('/'));
}
var first = !leadingSlash;
for (i = 0; i < sections.length; i++) {
if (sections[i] !== '') {
if (first) {
first = false;
} else {
path += '/';
}
path += sections[i];
}
}
if (trailingSlash) {
// add it back
path += '/';
}
return path;
},
/**
* Parses a URL query string into a JS map
2014-04-21 11:46:33 +00:00
* @param {string} queryString query string in the format param1=1234&param2=abcde&param3=xyz
* @return {Object.<string, string>} map containing key/values matching the URL parameters
*/
parseQueryString:function(queryString){
var parts,
pos,
components,
result = {},
key,
value;
if (!queryString){
return null;
}
pos = queryString.indexOf('?');
if (pos >= 0){
queryString = queryString.substr(pos + 1);
}
parts = queryString.replace(/\+/g, '%20').split('&');
for (var i = 0; i < parts.length; i++){
// split on first equal sign
2014-04-21 12:28:54 +00:00
var part = parts[i];
pos = part.indexOf('=');
if (pos >= 0) {
components = [
part.substr(0, pos),
part.substr(pos + 1)
];
}
else {
// key only
components = [part];
}
if (!components.length){
continue;
}
key = decodeURIComponent(components[0]);
if (!key){
continue;
}
// 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;
}
}
return result;
},
/**
* Builds a URL query from a JS map.
* @param {Object.<string, string>} params map containing key/values matching the URL parameters
2014-04-21 11:46:33 +00:00
* @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('&');
},
/**
* Opens a popup with the setting for an app.
2014-04-21 11:46:33 +00:00
* @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
* it will attempt to load a script by that name in the 'js' directory.
2014-04-21 11:46:33 +00:00
* @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
* 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);
2012-07-31 10:21:06 +00:00
var settings = $('#appsettings');
if(settings.length === 0) {
throw { name: 'MissingDOMElement', message: 'There has be be an element with id "appsettings" for the popup to show.' };
}
var popup = $('#appsettings_popup');
if(popup.length === 0) {
$('body').prepend('<div class="popup hidden" id="appsettings_popup"></div>');
2013-02-09 16:20:08 +00:00
popup = $('#appsettings_popup');
popup.addClass(settings.hasClass('topright') ? 'topright' : 'bottomleft');
}
if(popup.is(':visible')) {
popup.hide().remove();
2012-07-31 10:21:06 +00:00
} else {
var arrowclass = settings.hasClass('topright') ? 'up' : 'left';
var jqxhr = $.get(OC.filePath(props.appid, '', props.scriptName), function(data) {
popup.html(data).ready(function() {
2016-06-23 11:39:28 +00:00
popup.prepend('<span class="arrow '+arrowclass+'"></span><h2>'+t('core', 'Settings')+'</h2><a class="close"></a>').show();
popup.find('.close').bind('click', function() {
popup.remove();
2012-09-05 20:17:33 +00:00
});
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;
});
}
}).show();
}, 'html');
2012-07-31 10:21:06 +00:00
}
},
/**
* Returns the user's locale as a BCP 47 compliant language tag
*
* @return {String} locale string
*/
getCanonicalLocale: function() {
var locale = this.getLocale();
return typeof locale === 'string' ? locale.replace(/_/g, '-') : locale;
},
/**
* Returns the user's locale
*
* @return {String} locale string
*/
getLocale: function() {
return $('html').data('locale');
},
/**
* Returns the user's language
*
* @returns {String} language string
*/
getLanguage: function () {
return $('html').prop('lang');
},
/**
* Warn users that the connection to the server was lost temporarily
*
* This function is throttled to prevent stacked notfications.
* After 7sec the first notification is gone, then we can show another one
* if necessary.
*/
_ajaxConnectionLostHandler: _.throttle(function() {
OC.Notification.showTemporary(t('core', 'Connection to server lost'));
}, 7 * 1000, {trailing: false}),
2015-12-10 17:08:40 +00:00
/**
* Process ajax error, redirects to main page
* if an error/auth error status was returned.
*/
_processAjaxError: function(xhr) {
var self = this;
2015-12-10 17:08:40 +00:00
// purposefully aborted request ?
// this._userIsNavigatingAway needed to distinguish ajax calls cancelled by navigating away
// from calls cancelled by failed cross-domain ajax due to SSO redirect
if (xhr.status === 0 && (xhr.statusText === 'abort' || xhr.statusText === 'timeout' || self._reloadCalled)) {
2015-12-10 17:08:40 +00:00
return;
}
if (_.contains([302, 303, 307, 401], xhr.status) && OC.currentUser) {
// sometimes "beforeunload" happens later, so need to defer the reload a bit
setTimeout(function() {
if (!self._userIsNavigatingAway && !self._reloadCalled) {
var timer = 0;
var seconds = 5;
var interval = setInterval( function() {
OC.Notification.showUpdate(n('core', 'Problem loading page, reloading in %n second', 'Problem loading page, reloading in %n seconds', seconds - timer));
if (timer >= seconds) {
clearInterval(interval);
OC.reload();
}
timer++;
}, 1000 // 1 second interval
);
// only call reload once
self._reloadCalled = true;
}
}, 100);
} else if(xhr.status === 0) {
// Connection lost (e.g. WiFi disconnected or server is down)
setTimeout(function() {
if (!self._userIsNavigatingAway && !self._reloadCalled) {
self._ajaxConnectionLostHandler();
}
}, 100);
2015-12-10 17:08:40 +00:00
}
},
/**
* Registers XmlHttpRequest object for global error processing.
*
* This means that if this XHR object returns 401 or session timeout errors,
* the current page will automatically be reloaded.
*
* @param {XMLHttpRequest} xhr
*/
registerXHRForErrorProcessing: function(xhr) {
var loadCallback = function() {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
return;
}
// fire jquery global ajax error handler
$(document).trigger(new $.Event('ajaxError'), xhr);
};
var errorCallback = function() {
// fire jquery global ajax error handler
$(document).trigger(new $.Event('ajaxError'), xhr);
};
if (xhr.addEventListener) {
xhr.addEventListener('load', loadCallback);
xhr.addEventListener('error', errorCallback);
}
}
});
2014-04-21 11:46:33 +00:00