You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407
  1. /**
  2. * Disable console output unless DEBUG mode is enabled.
  3. * Add
  4. * 'debug' => true,
  5. * To the definition of $CONFIG in config/config.php to enable debug mode.
  6. * The undefined checks fix the broken ie8 console
  7. */
  8. /* global oc_isadmin */
  9. var oc_debug;
  10. var oc_webroot;
  11. var oc_current_user = document.getElementsByTagName('head')[0].getAttribute('data-user');
  12. var oc_requesttoken = document.getElementsByTagName('head')[0].getAttribute('data-requesttoken');
  13. window.oc_config = window.oc_config || {};
  14. if (typeof oc_webroot === "undefined") {
  15. oc_webroot = location.pathname;
  16. var pos = oc_webroot.indexOf('/index.php/');
  17. if (pos !== -1) {
  18. oc_webroot = oc_webroot.substr(0, pos);
  19. }
  20. else {
  21. oc_webroot = oc_webroot.substr(0, oc_webroot.lastIndexOf('/'));
  22. }
  23. }
  24. if (typeof console === "undefined" || typeof console.log === "undefined") {
  25. if (!window.console) {
  26. window.console = {};
  27. }
  28. var noOp = function() { };
  29. var methods = ['log', 'debug', 'warn', 'info', 'error', 'assert', 'time', 'timeEnd'];
  30. for (var i = 0; i < methods.length; i++) {
  31. console[methods[i]] = noOp;
  32. }
  33. }
  34. /**
  35. * Sanitizes a HTML string by replacing all potential dangerous characters with HTML entities
  36. * @param {string} s String to sanitize
  37. * @return {string} Sanitized string
  38. */
  39. function escapeHTML(s) {
  40. return s.toString().split('&').join('&amp;').split('<').join('&lt;').split('>').join('&gt;').split('"').join('&quot;').split('\'').join('&#039;');
  41. }
  42. /**
  43. * Get the path to download a file
  44. * @param {string} file The filename
  45. * @param {string} dir The directory the file is in - e.g. $('#dir').val()
  46. * @return {string} Path to download the file
  47. * @deprecated use Files.getDownloadURL() instead
  48. */
  49. function fileDownloadPath(dir, file) {
  50. return OC.filePath('files', 'ajax', 'download.php')+'?files='+encodeURIComponent(file)+'&dir='+encodeURIComponent(dir);
  51. }
  52. /** @namespace */
  53. var OCP = {},
  54. OC = {
  55. PERMISSION_NONE:0,
  56. PERMISSION_CREATE:4,
  57. PERMISSION_READ:1,
  58. PERMISSION_UPDATE:2,
  59. PERMISSION_DELETE:8,
  60. PERMISSION_SHARE:16,
  61. PERMISSION_ALL:31,
  62. TAG_FAVORITE: '_$!<Favorite>!$_',
  63. /* jshint camelcase: false */
  64. /**
  65. * Relative path to Nextcloud root.
  66. * For example: "/nextcloud"
  67. *
  68. * @type string
  69. *
  70. * @deprecated since 8.2, use OC.getRootPath() instead
  71. * @see OC#getRootPath
  72. */
  73. webroot:oc_webroot,
  74. appswebroots:(typeof oc_appswebroots !== 'undefined') ? oc_appswebroots:false,
  75. /**
  76. * Currently logged in user or null if none
  77. *
  78. * @type String
  79. * @deprecated use {@link OC.getCurrentUser} instead
  80. */
  81. currentUser:(typeof oc_current_user!=='undefined')?oc_current_user:false,
  82. config: window.oc_config,
  83. appConfig: window.oc_appconfig || {},
  84. theme: window.oc_defaults || {},
  85. coreApps:['', 'admin','log','core/search','settings','core','3rdparty'],
  86. requestToken: oc_requesttoken,
  87. menuSpeed: 50,
  88. /**
  89. * Get an absolute url to a file in an app
  90. * @param {string} app the id of the app the file belongs to
  91. * @param {string} file the file path relative to the app folder
  92. * @return {string} Absolute URL to a file
  93. */
  94. linkTo:function(app,file){
  95. return OC.filePath(app,'',file);
  96. },
  97. /**
  98. * Creates a relative url for remote use
  99. * @param {string} service id
  100. * @return {string} the url
  101. */
  102. linkToRemoteBase:function(service) {
  103. return OC.webroot + '/remote.php/' + service;
  104. },
  105. /**
  106. * @brief Creates an absolute url for remote use
  107. * @param {string} service id
  108. * @return {string} the url
  109. */
  110. linkToRemote:function(service) {
  111. return window.location.protocol + '//' + window.location.host + OC.linkToRemoteBase(service);
  112. },
  113. /**
  114. * Gets the base path for the given OCS API service.
  115. * @param {string} service name
  116. * @param {int} version OCS API version
  117. * @return {string} OCS API base path
  118. */
  119. linkToOCS: function(service, version) {
  120. version = (version !== 2) ? 1 : 2;
  121. return window.location.protocol + '//' + window.location.host + OC.webroot + '/ocs/v' + version + '.php/' + service + '/';
  122. },
  123. /**
  124. * Generates the absolute url for the given relative url, which can contain parameters.
  125. * Parameters will be URL encoded automatically.
  126. * @param {string} url
  127. * @param [params] params
  128. * @param [options] options
  129. * @param {bool} [options.escape=true] enable/disable auto escape of placeholders (by default enabled)
  130. * @return {string} Absolute URL for the given relative URL
  131. */
  132. generateUrl: function(url, params, options) {
  133. var defaultOptions = {
  134. escape: true
  135. },
  136. allOptions = options || {};
  137. _.defaults(allOptions, defaultOptions);
  138. var _build = function (text, vars) {
  139. vars = vars || [];
  140. return text.replace(/{([^{}]*)}/g,
  141. function (a, b) {
  142. var r = (vars[b]);
  143. if(allOptions.escape) {
  144. return (typeof r === 'string' || typeof r === 'number') ? encodeURIComponent(r) : encodeURIComponent(a);
  145. } else {
  146. return (typeof r === 'string' || typeof r === 'number') ? r : a;
  147. }
  148. }
  149. );
  150. };
  151. if (url.charAt(0) !== '/') {
  152. url = '/' + url;
  153. }
  154. if(oc_config.modRewriteWorking == true) {
  155. return OC.webroot + _build(url, params);
  156. }
  157. return OC.webroot + '/index.php' + _build(url, params);
  158. },
  159. /**
  160. * Get the absolute url for a file in an app
  161. * @param {string} app the id of the app
  162. * @param {string} type the type of the file to link to (e.g. css,img,ajax.template)
  163. * @param {string} file the filename
  164. * @return {string} Absolute URL for a file in an app
  165. */
  166. filePath:function(app,type,file){
  167. var isCore=OC.coreApps.indexOf(app)!==-1,
  168. link=OC.webroot;
  169. if(file.substring(file.length-3) === 'php' && !isCore){
  170. link+='/index.php/apps/' + app;
  171. if (file != 'index.php') {
  172. link+='/';
  173. if(type){
  174. link+=encodeURI(type + '/');
  175. }
  176. link+= file;
  177. }
  178. }else if(file.substring(file.length-3) !== 'php' && !isCore){
  179. link=OC.appswebroots[app];
  180. if(type){
  181. link+= '/'+type+'/';
  182. }
  183. if(link.substring(link.length-1) !== '/'){
  184. link+='/';
  185. }
  186. link+=file;
  187. }else{
  188. if ((app == 'settings' || app == 'core' || app == 'search') && type == 'ajax') {
  189. link+='/index.php/';
  190. }
  191. else {
  192. link+='/';
  193. }
  194. if(!isCore){
  195. link+='apps/';
  196. }
  197. if (app !== '') {
  198. app+='/';
  199. link+=app;
  200. }
  201. if(type){
  202. link+=type+'/';
  203. }
  204. link+=file;
  205. }
  206. return link;
  207. },
  208. /**
  209. * Check if a user file is allowed to be handled.
  210. * @param {string} file to check
  211. */
  212. fileIsBlacklisted: function(file) {
  213. return !!(file.match(oc_config.blacklist_files_regex));
  214. },
  215. /**
  216. * Redirect to the target URL, can also be used for downloads.
  217. * @param {string} targetURL URL to redirect to
  218. */
  219. redirect: function(targetURL) {
  220. window.location = targetURL;
  221. },
  222. /**
  223. * Reloads the current page
  224. */
  225. reload: function() {
  226. window.location.reload();
  227. },
  228. /**
  229. * Protocol that is used to access this Nextcloud instance
  230. * @return {string} Used protocol
  231. */
  232. getProtocol: function() {
  233. return window.location.protocol.split(':')[0];
  234. },
  235. /**
  236. * Returns the host used to access this Nextcloud instance
  237. * Host is sometimes the same as the hostname but now always.
  238. *
  239. * Examples:
  240. * http://example.com => example.com
  241. * https://example.com => example.com
  242. * http://example.com:8080 => example.com:8080
  243. *
  244. * @return {string} host
  245. *
  246. * @since 8.2
  247. */
  248. getHost: function() {
  249. return window.location.host;
  250. },
  251. /**
  252. * Returns the hostname used to access this Nextcloud instance
  253. * The hostname is always stripped of the port
  254. *
  255. * @return {string} hostname
  256. * @since 9.0
  257. */
  258. getHostName: function() {
  259. return window.location.hostname;
  260. },
  261. /**
  262. * Returns the port number used to access this Nextcloud instance
  263. *
  264. * @return {int} port number
  265. *
  266. * @since 8.2
  267. */
  268. getPort: function() {
  269. return window.location.port;
  270. },
  271. /**
  272. * Returns the web root path where this Nextcloud instance
  273. * is accessible, with a leading slash.
  274. * For example "/nextcloud".
  275. *
  276. * @return {string} web root path
  277. *
  278. * @since 8.2
  279. */
  280. getRootPath: function() {
  281. return OC.webroot;
  282. },
  283. /**
  284. * Returns the currently logged in user or null if there is no logged in
  285. * user (public page mode)
  286. *
  287. * @return {OC.CurrentUser} user spec
  288. * @since 9.0.0
  289. */
  290. getCurrentUser: function() {
  291. if (_.isUndefined(this._currentUserDisplayName)) {
  292. this._currentUserDisplayName = document.getElementsByTagName('head')[0].getAttribute('data-user-displayname');
  293. }
  294. return {
  295. uid: this.currentUser,
  296. displayName: this._currentUserDisplayName
  297. };
  298. },
  299. /**
  300. * get the absolute path to an image file
  301. * if no extension is given for the image, it will automatically decide
  302. * between .png and .svg based on what the browser supports
  303. * @param {string} app the app id to which the image belongs
  304. * @param {string} file the name of the image file
  305. * @return {string}
  306. */
  307. imagePath:function(app,file){
  308. if(file.indexOf('.')==-1){//if no extension is given, use svg
  309. file+='.svg';
  310. }
  311. return OC.filePath(app,'img',file);
  312. },
  313. /**
  314. * URI-Encodes a file path but keep the path slashes.
  315. *
  316. * @param path path
  317. * @return encoded path
  318. */
  319. encodePath: function(path) {
  320. if (!path) {
  321. return path;
  322. }
  323. var parts = path.split('/');
  324. var result = [];
  325. for (var i = 0; i < parts.length; i++) {
  326. result.push(encodeURIComponent(parts[i]));
  327. }
  328. return result.join('/');
  329. },
  330. /**
  331. * Load a script for the server and load it. If the script is already loaded,
  332. * the event handler will be called directly
  333. * @param {string} app the app id to which the script belongs
  334. * @param {string} script the filename of the script
  335. * @param ready event handler to be called when the script is loaded
  336. */
  337. addScript:function(app,script,ready){
  338. var deferred, path=OC.filePath(app,'js',script+'.js');
  339. if(!OC.addScript.loaded[path]) {
  340. deferred = jQuery.ajax({
  341. url: path,
  342. cache: true,
  343. success: function (content) {
  344. window.eval(content);
  345. if(ready) {
  346. ready();
  347. }
  348. }
  349. });
  350. OC.addScript.loaded[path] = deferred;
  351. } else {
  352. if (ready) {
  353. ready();
  354. }
  355. }
  356. return OC.addScript.loaded[path];
  357. },
  358. /**
  359. * Loads a CSS file
  360. * @param {string} app the app id to which the css style belongs
  361. * @param {string} style the filename of the css file
  362. */
  363. addStyle:function(app,style){
  364. var path=OC.filePath(app,'css',style+'.css');
  365. if(OC.addStyle.loaded.indexOf(path)===-1){
  366. OC.addStyle.loaded.push(path);
  367. if (document.createStyleSheet) {
  368. document.createStyleSheet(path);
  369. } else {
  370. style=$('<link rel="stylesheet" type="text/css" href="'+path+'"/>');
  371. $('head').append(style);
  372. }
  373. }
  374. },
  375. /**
  376. * Loads translations for the given app asynchronously.
  377. *
  378. * @param {String} app app name
  379. * @param {Function} callback callback to call after loading
  380. * @return {Promise}
  381. */
  382. addTranslations: function(app, callback) {
  383. return OC.L10N.load(app, callback);
  384. },
  385. /**
  386. * Returns the base name of the given path.
  387. * For example for "/abc/somefile.txt" it will return "somefile.txt"
  388. *
  389. * @param {String} path
  390. * @return {String} base name
  391. */
  392. basename: function(path) {
  393. return path.replace(/\\/g,'/').replace( /.*\//, '' );
  394. },
  395. /**
  396. * Returns the dir name of the given path.
  397. * For example for "/abc/somefile.txt" it will return "/abc"
  398. *
  399. * @param {String} path
  400. * @return {String} dir name
  401. */
  402. dirname: function(path) {
  403. return path.replace(/\\/g,'/').replace(/\/[^\/]*$/, '');
  404. },
  405. /**
  406. * Returns whether the given paths are the same, without
  407. * leading, trailing or doubled slashes and also removing
  408. * the dot sections.
  409. *
  410. * @param {String} path1 first path
  411. * @param {String} path2 second path
  412. * @return {bool} true if the paths are the same
  413. *
  414. * @since 9.0
  415. */
  416. isSamePath: function(path1, path2) {
  417. var filterDot = function(p) {
  418. return p !== '.';
  419. };
  420. var pathSections1 = _.filter((path1 || '').split('/'), filterDot);
  421. var pathSections2 = _.filter((path2 || '').split('/'), filterDot);
  422. path1 = OC.joinPaths.apply(OC, pathSections1);
  423. path2 = OC.joinPaths.apply(OC, pathSections2);
  424. return path1 === path2;
  425. },
  426. /**
  427. * Join path sections
  428. *
  429. * @param {...String} path sections
  430. *
  431. * @return {String} joined path, any leading or trailing slash
  432. * will be kept
  433. *
  434. * @since 8.2
  435. */
  436. joinPaths: function() {
  437. if (arguments.length < 1) {
  438. return '';
  439. }
  440. var path = '';
  441. // convert to array
  442. var args = Array.prototype.slice.call(arguments);
  443. // discard empty arguments
  444. args = _.filter(args, function(arg) {
  445. return arg.length > 0;
  446. });
  447. if (args.length < 1) {
  448. return '';
  449. }
  450. var lastArg = args[args.length - 1];
  451. var leadingSlash = args[0].charAt(0) === '/';
  452. var trailingSlash = lastArg.charAt(lastArg.length - 1) === '/';
  453. var sections = [];
  454. var i;
  455. for (i = 0; i < args.length; i++) {
  456. sections = sections.concat(args[i].split('/'));
  457. }
  458. var first = !leadingSlash;
  459. for (i = 0; i < sections.length; i++) {
  460. if (sections[i] !== '') {
  461. if (first) {
  462. first = false;
  463. } else {
  464. path += '/';
  465. }
  466. path += sections[i];
  467. }
  468. }
  469. if (trailingSlash) {
  470. // add it back
  471. path += '/';
  472. }
  473. return path;
  474. },
  475. /**
  476. * Do a search query and display the results
  477. * @param {string} query the search query
  478. */
  479. search: function (query) {
  480. OC.Search.search(query, null, 0, 30);
  481. },
  482. /**
  483. * Dialog helper for jquery dialogs.
  484. *
  485. * @namespace OC.dialogs
  486. */
  487. dialogs:OCdialogs,
  488. /**
  489. * Parses a URL query string into a JS map
  490. * @param {string} queryString query string in the format param1=1234&param2=abcde&param3=xyz
  491. * @return {Object.<string, string>} map containing key/values matching the URL parameters
  492. */
  493. parseQueryString:function(queryString){
  494. var parts,
  495. pos,
  496. components,
  497. result = {},
  498. key,
  499. value;
  500. if (!queryString){
  501. return null;
  502. }
  503. pos = queryString.indexOf('?');
  504. if (pos >= 0){
  505. queryString = queryString.substr(pos + 1);
  506. }
  507. parts = queryString.replace(/\+/g, '%20').split('&');
  508. for (var i = 0; i < parts.length; i++){
  509. // split on first equal sign
  510. var part = parts[i];
  511. pos = part.indexOf('=');
  512. if (pos >= 0) {
  513. components = [
  514. part.substr(0, pos),
  515. part.substr(pos + 1)
  516. ];
  517. }
  518. else {
  519. // key only
  520. components = [part];
  521. }
  522. if (!components.length){
  523. continue;
  524. }
  525. key = decodeURIComponent(components[0]);
  526. if (!key){
  527. continue;
  528. }
  529. // if equal sign was there, return string
  530. if (components.length > 1) {
  531. result[key] = decodeURIComponent(components[1]);
  532. }
  533. // no equal sign => null value
  534. else {
  535. result[key] = null;
  536. }
  537. }
  538. return result;
  539. },
  540. /**
  541. * Builds a URL query from a JS map.
  542. * @param {Object.<string, string>} params map containing key/values matching the URL parameters
  543. * @return {string} String containing a URL query (without question) mark
  544. */
  545. buildQueryString: function(params) {
  546. if (!params) {
  547. return '';
  548. }
  549. return $.map(params, function(value, key) {
  550. var s = encodeURIComponent(key);
  551. if (value !== null && typeof(value) !== 'undefined') {
  552. s += '=' + encodeURIComponent(value);
  553. }
  554. return s;
  555. }).join('&');
  556. },
  557. /**
  558. * Opens a popup with the setting for an app.
  559. * @param {string} appid The ID of the app e.g. 'calendar', 'contacts' or 'files'.
  560. * @param {boolean|string} loadJS If true 'js/settings.js' is loaded. If it's a string
  561. * it will attempt to load a script by that name in the 'js' directory.
  562. * @param {boolean} [cache] If true the javascript file won't be forced refreshed. Defaults to true.
  563. * @param {string} [scriptName] The name of the PHP file to load. Defaults to 'settings.php' in
  564. * the root of the app directory hierarchy.
  565. */
  566. appSettings:function(args) {
  567. if(typeof args === 'undefined' || typeof args.appid === 'undefined') {
  568. throw { name: 'MissingParameter', message: 'The parameter appid is missing' };
  569. }
  570. var props = {scriptName:'settings.php', cache:true};
  571. $.extend(props, args);
  572. var settings = $('#appsettings');
  573. if(settings.length === 0) {
  574. throw { name: 'MissingDOMElement', message: 'There has be be an element with id "appsettings" for the popup to show.' };
  575. }
  576. var popup = $('#appsettings_popup');
  577. if(popup.length === 0) {
  578. $('body').prepend('<div class="popup hidden" id="appsettings_popup"></div>');
  579. popup = $('#appsettings_popup');
  580. popup.addClass(settings.hasClass('topright') ? 'topright' : 'bottomleft');
  581. }
  582. if(popup.is(':visible')) {
  583. popup.hide().remove();
  584. } else {
  585. var arrowclass = settings.hasClass('topright') ? 'up' : 'left';
  586. var jqxhr = $.get(OC.filePath(props.appid, '', props.scriptName), function(data) {
  587. popup.html(data).ready(function() {
  588. popup.prepend('<span class="arrow '+arrowclass+'"></span><h2>'+t('core', 'Settings')+'</h2><a class="close"></a>').show();
  589. popup.find('.close').bind('click', function() {
  590. popup.remove();
  591. });
  592. if(typeof props.loadJS !== 'undefined') {
  593. var scriptname;
  594. if(props.loadJS === true) {
  595. scriptname = 'settings.js';
  596. } else if(typeof props.loadJS === 'string') {
  597. scriptname = props.loadJS;
  598. } else {
  599. throw { name: 'InvalidParameter', message: 'The "loadJS" parameter must be either boolean or a string.' };
  600. }
  601. if(props.cache) {
  602. $.ajaxSetup({cache: true});
  603. }
  604. $.getScript(OC.filePath(props.appid, 'js', scriptname))
  605. .fail(function(jqxhr, settings, e) {
  606. throw e;
  607. });
  608. }
  609. }).show();
  610. }, 'html');
  611. }
  612. },
  613. /**
  614. * For menu toggling
  615. * @todo Write documentation
  616. *
  617. * @param {jQuery} $toggle
  618. * @param {jQuery} $menuEl
  619. * @param {function|undefined} toggle callback invoked everytime the menu is opened
  620. * @returns {undefined}
  621. */
  622. registerMenu: function($toggle, $menuEl, toggle) {
  623. var self = this;
  624. $menuEl.addClass('menu');
  625. $toggle.on('click.menu', function(event) {
  626. // prevent the link event (append anchor to URL)
  627. event.preventDefault();
  628. if ($menuEl.is(OC._currentMenu)) {
  629. self.hideMenus();
  630. return;
  631. }
  632. // another menu was open?
  633. else if (OC._currentMenu) {
  634. // close it
  635. self.hideMenus();
  636. }
  637. $menuEl.slideToggle(OC.menuSpeed, toggle);
  638. OC._currentMenu = $menuEl;
  639. OC._currentMenuToggle = $toggle;
  640. });
  641. },
  642. /**
  643. * @todo Write documentation
  644. */
  645. unregisterMenu: function($toggle, $menuEl) {
  646. // close menu if opened
  647. if ($menuEl.is(OC._currentMenu)) {
  648. this.hideMenus();
  649. }
  650. $toggle.off('click.menu').removeClass('menutoggle');
  651. $menuEl.removeClass('menu');
  652. },
  653. /**
  654. * Hides any open menus
  655. *
  656. * @param {Function} complete callback when the hiding animation is done
  657. */
  658. hideMenus: function(complete) {
  659. if (OC._currentMenu) {
  660. var lastMenu = OC._currentMenu;
  661. OC._currentMenu.trigger(new $.Event('beforeHide'));
  662. OC._currentMenu.slideUp(OC.menuSpeed, function() {
  663. lastMenu.trigger(new $.Event('afterHide'));
  664. if (complete) {
  665. complete.apply(this, arguments);
  666. }
  667. });
  668. }
  669. OC._currentMenu = null;
  670. OC._currentMenuToggle = null;
  671. },
  672. /**
  673. * Shows a given element as menu
  674. *
  675. * @param {Object} [$toggle=null] menu toggle
  676. * @param {Object} $menuEl menu element
  677. * @param {Function} complete callback when the showing animation is done
  678. */
  679. showMenu: function($toggle, $menuEl, complete) {
  680. if ($menuEl.is(OC._currentMenu)) {
  681. return;
  682. }
  683. this.hideMenus();
  684. OC._currentMenu = $menuEl;
  685. OC._currentMenuToggle = $toggle;
  686. $menuEl.trigger(new $.Event('beforeShow'));
  687. $menuEl.show();
  688. $menuEl.trigger(new $.Event('afterShow'));
  689. // no animation
  690. if (_.isFunction(complete)) {
  691. complete();
  692. }
  693. },
  694. /**
  695. * Wrapper for matchMedia
  696. *
  697. * This is makes it possible for unit tests to
  698. * stub matchMedia (which doesn't work in PhantomJS)
  699. * @private
  700. */
  701. _matchMedia: function(media) {
  702. if (window.matchMedia) {
  703. return window.matchMedia(media);
  704. }
  705. return false;
  706. },
  707. /**
  708. * Returns the user's locale
  709. *
  710. * @return {String} locale string
  711. */
  712. getLocale: function() {
  713. return $('html').prop('lang');
  714. },
  715. /**
  716. * Returns whether the current user is an administrator
  717. *
  718. * @return {bool} true if the user is an admin, false otherwise
  719. * @since 9.0.0
  720. */
  721. isUserAdmin: function() {
  722. return oc_isadmin;
  723. },
  724. /**
  725. * Warn users that the connection to the server was lost temporarily
  726. *
  727. * This function is throttled to prevent stacked notfications.
  728. * After 7sec the first notification is gone, then we can show another one
  729. * if necessary.
  730. */
  731. _ajaxConnectionLostHandler: _.throttle(function() {
  732. OC.Notification.showTemporary(t('core', 'Connection to server lost'));
  733. }, 7 * 1000, {trailing: false}),
  734. /**
  735. * Process ajax error, redirects to main page
  736. * if an error/auth error status was returned.
  737. */
  738. _processAjaxError: function(xhr) {
  739. var self = this;
  740. // purposefully aborted request ?
  741. // this._userIsNavigatingAway needed to distinguish ajax calls cancelled by navigating away
  742. // from calls cancelled by failed cross-domain ajax due to SSO redirect
  743. if (xhr.status === 0 && (xhr.statusText === 'abort' || xhr.statusText === 'timeout' || self._reloadCalled)) {
  744. return;
  745. }
  746. if (_.contains([302, 303, 307, 401], xhr.status) && OC.currentUser) {
  747. // sometimes "beforeunload" happens later, so need to defer the reload a bit
  748. setTimeout(function() {
  749. if (!self._userIsNavigatingAway && !self._reloadCalled) {
  750. var timer = 0;
  751. var seconds = 5;
  752. var interval = setInterval( function() {
  753. OC.Notification.showUpdate(n('core', 'Problem loading page, reloading in %n second', 'Problem loading page, reloading in %n seconds', seconds - timer));
  754. if (timer >= seconds) {
  755. clearInterval(interval);
  756. OC.reload();
  757. }
  758. timer++;
  759. }, 1000 // 1 second interval
  760. );
  761. // only call reload once
  762. self._reloadCalled = true;
  763. }
  764. }, 100);
  765. } else if(xhr.status === 0) {
  766. // Connection lost (e.g. WiFi disconnected or server is down)
  767. setTimeout(function() {
  768. if (!self._userIsNavigatingAway && !self._reloadCalled) {
  769. self._ajaxConnectionLostHandler();
  770. }
  771. }, 100);
  772. }
  773. },
  774. /**
  775. * Registers XmlHttpRequest object for global error processing.
  776. *
  777. * This means that if this XHR object returns 401 or session timeout errors,
  778. * the current page will automatically be reloaded.
  779. *
  780. * @param {XMLHttpRequest} xhr
  781. */
  782. registerXHRForErrorProcessing: function(xhr) {
  783. var loadCallback = function() {
  784. if (xhr.readyState !== 4) {
  785. return;
  786. }
  787. if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
  788. return;
  789. }
  790. // fire jquery global ajax error handler
  791. $(document).trigger(new $.Event('ajaxError'), xhr);
  792. };
  793. var errorCallback = function() {
  794. // fire jquery global ajax error handler
  795. $(document).trigger(new $.Event('ajaxError'), xhr);
  796. };
  797. if (xhr.addEventListener) {
  798. xhr.addEventListener('load', loadCallback);
  799. xhr.addEventListener('error', errorCallback);
  800. }
  801. }
  802. };
  803. /**
  804. * Current user attributes
  805. *
  806. * @typedef {Object} OC.CurrentUser
  807. *
  808. * @property {String} uid user id
  809. * @property {String} displayName display name
  810. */
  811. /**
  812. * @namespace OC.Plugins
  813. */
  814. OC.Plugins = {
  815. /**
  816. * @type Array.<OC.Plugin>
  817. */
  818. _plugins: {},
  819. /**
  820. * Register plugin
  821. *
  822. * @param {String} targetName app name / class name to hook into
  823. * @param {OC.Plugin} plugin
  824. */
  825. register: function(targetName, plugin) {
  826. var plugins = this._plugins[targetName];
  827. if (!plugins) {
  828. plugins = this._plugins[targetName] = [];
  829. }
  830. plugins.push(plugin);
  831. },
  832. /**
  833. * Returns all plugin registered to the given target
  834. * name / app name / class name.
  835. *
  836. * @param {String} targetName app name / class name to hook into
  837. * @return {Array.<OC.Plugin>} array of plugins
  838. */
  839. getPlugins: function(targetName) {
  840. return this._plugins[targetName] || [];
  841. },
  842. /**
  843. * Call attach() on all plugins registered to the given target name.
  844. *
  845. * @param {String} targetName app name / class name
  846. * @param {Object} object to be extended
  847. * @param {Object} [options] options
  848. */
  849. attach: function(targetName, targetObject, options) {
  850. var plugins = this.getPlugins(targetName);
  851. for (var i = 0; i < plugins.length; i++) {
  852. if (plugins[i].attach) {
  853. plugins[i].attach(targetObject, options);
  854. }
  855. }
  856. },
  857. /**
  858. * Call detach() on all plugins registered to the given target name.
  859. *
  860. * @param {String} targetName app name / class name
  861. * @param {Object} object to be extended
  862. * @param {Object} [options] options
  863. */
  864. detach: function(targetName, targetObject, options) {
  865. var plugins = this.getPlugins(targetName);
  866. for (var i = 0; i < plugins.length; i++) {
  867. if (plugins[i].detach) {
  868. plugins[i].detach(targetObject, options);
  869. }
  870. }
  871. },
  872. /**
  873. * Plugin
  874. *
  875. * @todo make this a real class in the future
  876. * @typedef {Object} OC.Plugin
  877. *
  878. * @property {String} name plugin name
  879. * @property {Function} attach function that will be called when the
  880. * plugin is attached
  881. * @property {Function} [detach] function that will be called when the
  882. * plugin is detached
  883. */
  884. };
  885. /**
  886. * @namespace OC.search
  887. */
  888. OC.search.customResults = {};
  889. /**
  890. * @deprecated use get/setFormatter() instead
  891. */
  892. OC.search.resultTypes = {};
  893. OC.addStyle.loaded=[];
  894. OC.addScript.loaded=[];
  895. /**
  896. * A little class to manage a status field for a "saving" process.
  897. * It can be used to display a starting message (e.g. "Saving...") and then
  898. * replace it with a green success message or a red error message.
  899. *
  900. * @namespace OC.msg
  901. */
  902. OC.msg = {
  903. /**
  904. * Displayes a "Saving..." message in the given message placeholder
  905. *
  906. * @param {Object} selector Placeholder to display the message in
  907. */
  908. startSaving: function(selector) {
  909. this.startAction(selector, t('core', 'Saving...'));
  910. },
  911. /**
  912. * Displayes a custom message in the given message placeholder
  913. *
  914. * @param {Object} selector Placeholder to display the message in
  915. * @param {string} message Plain text message to display (no HTML allowed)
  916. */
  917. startAction: function(selector, message) {
  918. $(selector).text(message)
  919. .removeClass('success')
  920. .removeClass('error')
  921. .stop(true, true)
  922. .show();
  923. },
  924. /**
  925. * Displayes an success/error message in the given selector
  926. *
  927. * @param {Object} selector Placeholder to display the message in
  928. * @param {Object} response Response of the server
  929. * @param {Object} response.data Data of the servers response
  930. * @param {string} response.data.message Plain text message to display (no HTML allowed)
  931. * @param {string} response.status is being used to decide whether the message
  932. * is displayed as an error/success
  933. */
  934. finishedSaving: function(selector, response) {
  935. this.finishedAction(selector, response);
  936. },
  937. /**
  938. * Displayes an success/error message in the given selector
  939. *
  940. * @param {Object} selector Placeholder to display the message in
  941. * @param {Object} response Response of the server
  942. * @param {Object} response.data Data of the servers response
  943. * @param {string} response.data.message Plain text message to display (no HTML allowed)
  944. * @param {string} response.status is being used to decide whether the message
  945. * is displayed as an error/success
  946. */
  947. finishedAction: function(selector, response) {
  948. if (response.status === "success") {
  949. this.finishedSuccess(selector, response.data.message);
  950. } else {
  951. this.finishedError(selector, response.data.message);
  952. }
  953. },
  954. /**
  955. * Displayes an success message in the given selector
  956. *
  957. * @param {Object} selector Placeholder to display the message in
  958. * @param {string} message Plain text success message to display (no HTML allowed)
  959. */
  960. finishedSuccess: function(selector, message) {
  961. $(selector).text(message)
  962. .addClass('success')
  963. .removeClass('error')
  964. .stop(true, true)
  965. .delay(3000)
  966. .fadeOut(900)
  967. .show();
  968. },
  969. /**
  970. * Displayes an error message in the given selector
  971. *
  972. * @param {Object} selector Placeholder to display the message in
  973. * @param {string} message Plain text error message to display (no HTML allowed)
  974. */
  975. finishedError: function(selector, message) {
  976. $(selector).text(message)
  977. .addClass('error')
  978. .removeClass('success')
  979. .show();
  980. }
  981. };
  982. /**
  983. * @todo Write documentation
  984. * @namespace
  985. */
  986. OC.Notification={
  987. queuedNotifications: [],
  988. getDefaultNotificationFunction: null,
  989. /**
  990. * @type Array.<int> array of notification timers
  991. */
  992. notificationTimers: [],
  993. /**
  994. * @param callback
  995. * @todo Write documentation
  996. */
  997. setDefault: function(callback) {
  998. OC.Notification.getDefaultNotificationFunction = callback;
  999. },
  1000. /**
  1001. * Hides a notification.
  1002. *
  1003. * If a row is given, only hide that one.
  1004. * If no row is given, hide all notifications.
  1005. *
  1006. * @param {jQuery} [$row] notification row
  1007. * @param {Function} [callback] callback
  1008. */
  1009. hide: function($row, callback) {
  1010. var self = this;
  1011. var $notification = $('#notification');
  1012. if (_.isFunction($row)) {
  1013. // first arg is the callback
  1014. callback = $row;
  1015. $row = undefined;
  1016. }
  1017. if (!$row) {
  1018. console.warn('Missing argument $row in OC.Notification.hide() call, caller needs to be adjusted to only dismiss its own notification');
  1019. // assume that the row to be hidden is the first one
  1020. $row = $notification.find('.row:first');
  1021. }
  1022. if ($row && $notification.find('.row').length > 1) {
  1023. // remove the row directly
  1024. $row.remove();
  1025. if (callback) {
  1026. callback.call();
  1027. }
  1028. return;
  1029. }
  1030. _.defer(function() {
  1031. // fade out is supposed to only fade when there is a single row
  1032. // however, some code might call hide() and show() directly after,
  1033. // which results in more than one element
  1034. // in this case, simply delete that one element that was supposed to
  1035. // fade out
  1036. //
  1037. // FIXME: remove once all callers are adjusted to only hide their own notifications
  1038. if ($notification.find('.row').length > 1) {
  1039. $row.remove();
  1040. return;
  1041. }
  1042. // else, fade out whatever was present
  1043. $notification.fadeOut('400', function(){
  1044. if (self.isHidden()) {
  1045. if (self.getDefaultNotificationFunction) {
  1046. self.getDefaultNotificationFunction.call();
  1047. }
  1048. }
  1049. if (callback) {
  1050. callback.call();
  1051. }
  1052. $notification.empty();
  1053. });
  1054. });
  1055. },
  1056. /**
  1057. * Shows a notification as HTML without being sanitized before.
  1058. * If you pass unsanitized user input this may lead to a XSS vulnerability.
  1059. * Consider using show() instead of showHTML()
  1060. *
  1061. * @param {string} html Message to display
  1062. * @param {Object} [options] options
  1063. * @param {string} [options.type] notification type
  1064. * @param {int} [options.timeout=0] timeout value, defaults to 0 (permanent)
  1065. * @return {jQuery} jQuery element for notification row
  1066. */
  1067. showHtml: function(html, options) {
  1068. options = options || {};
  1069. _.defaults(options, {
  1070. timeout: 0
  1071. });
  1072. var self = this;
  1073. var $notification = $('#notification');
  1074. if (this.isHidden()) {
  1075. $notification.fadeIn().css('display','inline-block');
  1076. }
  1077. var $row = $('<div class="row"></div>');
  1078. if (options.type) {
  1079. $row.addClass('type-' + options.type);
  1080. }
  1081. if (options.type === 'error') {
  1082. // add a close button
  1083. var $closeButton = $('<a class="action close icon-close" href="#"></a>');
  1084. $closeButton.attr('alt', t('core', 'Dismiss'));
  1085. $row.append($closeButton);
  1086. $closeButton.one('click', function() {
  1087. self.hide($row);
  1088. return false;
  1089. });
  1090. $row.addClass('closeable');
  1091. }
  1092. $row.prepend(html);
  1093. $notification.append($row);
  1094. if(options.timeout > 0) {
  1095. // register timeout to vanish notification
  1096. this.notificationTimers.push(setTimeout(function() {
  1097. self.hide($row);
  1098. }, (options.timeout * 1000)));
  1099. }
  1100. return $row;
  1101. },
  1102. /**
  1103. * Shows a sanitized notification
  1104. *
  1105. * @param {string} text Message to display
  1106. * @param {Object} [options] options
  1107. * @param {string} [options.type] notification type
  1108. * @param {int} [options.timeout=0] timeout value, defaults to 0 (permanent)
  1109. * @return {jQuery} jQuery element for notification row
  1110. */
  1111. show: function(text, options) {
  1112. return this.showHtml($('<div/>').text(text).html(), options);
  1113. },
  1114. /**
  1115. * Updates (replaces) a sanitized notification.
  1116. *
  1117. * @param {string} text Message to display
  1118. * @return {jQuery} JQuery element for notificaiton row
  1119. */
  1120. showUpdate: function(text) {
  1121. var $notification = $('#notification');
  1122. // sanitise
  1123. var $html = $('<div/>').text(text).html();
  1124. // new notification
  1125. if (text && $notification.find('.row').length == 0) {
  1126. return this.showHtml($html);
  1127. }
  1128. var $row = $('<div class="row"></div>').prepend($html);
  1129. // just update html in notification
  1130. $notification.html($row);
  1131. return $row;
  1132. },
  1133. /**
  1134. * Shows a notification that disappears after x seconds, default is
  1135. * 7 seconds
  1136. *
  1137. * @param {string} text Message to show
  1138. * @param {array} [options] options array
  1139. * @param {int} [options.timeout=7] timeout in seconds, if this is 0 it will show the message permanently
  1140. * @param {boolean} [options.isHTML=false] an indicator for HTML notifications (true) or text (false)
  1141. * @param {string} [options.type] notification type
  1142. */
  1143. showTemporary: function(text, options) {
  1144. var defaults = {
  1145. isHTML: false,
  1146. timeout: 7
  1147. };
  1148. options = options || {};
  1149. // merge defaults with passed in options
  1150. _.defaults(options, defaults);
  1151. var $row;
  1152. if(options.isHTML) {
  1153. $row = this.showHtml(text, options);
  1154. } else {
  1155. $row = this.show(text, options);
  1156. }
  1157. return $row;
  1158. },
  1159. /**
  1160. * Returns whether a notification is hidden.
  1161. * @return {boolean}
  1162. */
  1163. isHidden: function() {
  1164. return !$("#notification").find('.row').length;
  1165. }
  1166. };
  1167. /**
  1168. * Initializes core
  1169. */
  1170. function initCore() {
  1171. /**
  1172. * Disable automatic evaluation of responses for $.ajax() functions (and its
  1173. * higher-level alternatives like $.get() and $.post()).
  1174. *
  1175. * If a response to a $.ajax() request returns a content type of "application/javascript"
  1176. * JQuery would previously execute the response body. This is a pretty unexpected
  1177. * behaviour and can result in a bypass of our Content-Security-Policy as well as
  1178. * multiple unexpected XSS vectors.
  1179. */
  1180. $.ajaxSetup({
  1181. contents: {
  1182. script: false
  1183. }
  1184. });
  1185. /**
  1186. * Disable execution of eval in jQuery. We do require an allowed eval CSP
  1187. * configuration at the moment for handlebars et al. But for jQuery there is
  1188. * not much of a reason to execute JavaScript directly via eval.
  1189. *
  1190. * This thus mitigates some unexpected XSS vectors.
  1191. */
  1192. jQuery.globalEval = function(){};
  1193. /**
  1194. * Set users locale to moment.js as soon as possible
  1195. */
  1196. moment.locale(OC.getLocale());
  1197. var userAgent = window.navigator.userAgent;
  1198. var msie = userAgent.indexOf('MSIE ');
  1199. var trident = userAgent.indexOf('Trident/');
  1200. var edge = userAgent.indexOf('Edge/');
  1201. if (msie > 0 || trident > 0) {
  1202. // (IE 10 or older) || IE 11
  1203. $('html').addClass('ie');
  1204. } else if (edge > 0) {
  1205. // for edge
  1206. $('html').addClass('edge');
  1207. }
  1208. $(window).on('unload.main', function() {
  1209. OC._unloadCalled = true;
  1210. });
  1211. $(window).on('beforeunload.main', function() {
  1212. // super-trick thanks to http://stackoverflow.com/a/4651049
  1213. // in case another handler displays a confirmation dialog (ex: navigating away
  1214. // during an upload), there are two possible outcomes: user clicked "ok" or
  1215. // "cancel"
  1216. // first timeout handler is called after unload dialog is closed
  1217. setTimeout(function() {
  1218. OC._userIsNavigatingAway = true;
  1219. // second timeout event is only called if user cancelled (Chrome),
  1220. // but in other browsers it might still be triggered, so need to
  1221. // set a higher delay...
  1222. setTimeout(function() {
  1223. if (!OC._unloadCalled) {
  1224. OC._userIsNavigatingAway = false;
  1225. }
  1226. }, 10000);
  1227. },1);
  1228. });
  1229. $(document).on('ajaxError.main', function( event, request, settings ) {
  1230. if (settings && settings.allowAuthErrors) {
  1231. return;
  1232. }
  1233. OC._processAjaxError(request);
  1234. });
  1235. /**
  1236. * Calls the server periodically to ensure that session doesn't
  1237. * time out
  1238. */
  1239. function initSessionHeartBeat(){
  1240. // max interval in seconds set to 24 hours
  1241. var maxInterval = 24 * 3600;
  1242. // interval in seconds
  1243. var interval = 900;
  1244. if (oc_config.session_lifetime) {
  1245. interval = Math.floor(oc_config.session_lifetime / 2);
  1246. }
  1247. // minimum one minute
  1248. if (interval < 60) {
  1249. interval = 60;
  1250. }
  1251. if (interval > maxInterval) {
  1252. interval = maxInterval;
  1253. }
  1254. var url = OC.generateUrl('/heartbeat');
  1255. var heartBeatTimeout = null;
  1256. var heartBeat = function() {
  1257. clearInterval(heartBeatTimeout);
  1258. heartBeatTimeout = setInterval(function() {
  1259. $.post(url);
  1260. }, interval * 1000);
  1261. };
  1262. $(document).ajaxComplete(heartBeat);
  1263. heartBeat();
  1264. }
  1265. // session heartbeat (defaults to enabled)
  1266. if (typeof(oc_config.session_keepalive) === 'undefined' ||
  1267. !!oc_config.session_keepalive) {
  1268. initSessionHeartBeat();
  1269. }
  1270. OC.registerMenu($('#expand'), $('#expanddiv'));
  1271. // toggle for menus
  1272. $(document).on('mouseup.closemenus', function(event) {
  1273. var $el = $(event.target);
  1274. if ($el.closest('.menu').length || $el.closest('.menutoggle').length) {
  1275. // don't close when clicking on the menu directly or a menu toggle
  1276. return false;
  1277. }
  1278. OC.hideMenus();
  1279. });
  1280. /**
  1281. * Set up the main menu toggle to react to media query changes.
  1282. * If the screen is small enough, the main menu becomes a toggle.
  1283. * If the screen is bigger, the main menu is not a toggle any more.
  1284. */
  1285. function setupMainMenu() {
  1286. // init the more-apps menu
  1287. OC.registerMenu($('#more-apps'), $('#navigation'));
  1288. // toggle the navigation
  1289. var $toggle = $('#header .header-appname-container');
  1290. var $navigation = $('#navigation');
  1291. var $appmenu = $('#appmenu');
  1292. // init the menu
  1293. OC.registerMenu($toggle, $navigation);
  1294. $toggle.data('oldhref', $toggle.attr('href'));
  1295. $toggle.attr('href', '#');
  1296. $navigation.hide();
  1297. // show loading feedback
  1298. $navigation.delegate('a', 'click', function(event) {
  1299. var $app = $(event.target);
  1300. if(!$app.is('a')) {
  1301. $app = $app.closest('a');
  1302. }
  1303. if(event.which === 1 && !event.ctrlKey && !event.metaKey) {
  1304. $app.addClass('app-loading');
  1305. } else {
  1306. // Close navigation when opening app in
  1307. // a new tab
  1308. OC.hideMenus(function(){return false;});
  1309. }
  1310. });
  1311. $navigation.delegate('a', 'mouseup', function(event) {
  1312. if(event.which === 2) {
  1313. // Close navigation when opening app in
  1314. // a new tab via middle click
  1315. OC.hideMenus(function(){return false;});
  1316. }
  1317. });
  1318. $appmenu.delegate('a', 'click', function(event) {
  1319. var $app = $(event.target);
  1320. if(!$app.is('a')) {
  1321. $app = $app.closest('a');
  1322. }
  1323. if(event.which === 1 && !event.ctrlKey && !event.metaKey) {
  1324. $app.addClass('app-loading');
  1325. } else {
  1326. // Close navigation when opening app in
  1327. // a new tab
  1328. OC.hideMenus(function(){return false;});
  1329. }
  1330. });
  1331. }
  1332. function setupUserMenu() {
  1333. var $menu = $('#header #settings');
  1334. // show loading feedback
  1335. $menu.delegate('a', 'click', function(event) {
  1336. var $page = $(event.target);
  1337. if (!$page.is('a')) {
  1338. $page = $page.closest('a');
  1339. }
  1340. if(event.which === 1 && !event.ctrlKey && !event.metaKey) {
  1341. $page.find('img').remove();
  1342. $page.find('div').remove(); // prevent odd double-clicks
  1343. $page.prepend($('<div/>').addClass('icon-loading-small-dark'));
  1344. } else {
  1345. // Close navigation when opening menu entry in
  1346. // a new tab
  1347. OC.hideMenus(function(){return false;});
  1348. }
  1349. });
  1350. $menu.delegate('a', 'mouseup', function(event) {
  1351. if(event.which === 2) {
  1352. // Close navigation when opening app in
  1353. // a new tab via middle click
  1354. OC.hideMenus(function(){return false;});
  1355. }
  1356. });
  1357. }
  1358. function setupContactsMenu() {
  1359. new OC.ContactsMenu({
  1360. el: $('#contactsmenu .menu'),
  1361. trigger: $('#contactsmenu .menutoggle')
  1362. });
  1363. }
  1364. setupMainMenu();
  1365. setupUserMenu();
  1366. setupContactsMenu();
  1367. // move triangle of apps dropdown to align with app name triangle
  1368. // 2 is the additional offset between the triangles
  1369. if($('#navigation').length) {
  1370. $('#header #nextcloud + .menutoggle').on('click', function(){
  1371. $('#menu-css-helper').remove();
  1372. var caretPosition = $('.header-appname + .icon-caret').offset().left - 2;
  1373. if(caretPosition > 255) {
  1374. // if the app name is longer than the menu, just put the triangle in the middle
  1375. return;
  1376. } else {
  1377. $('head').append('<style id="menu-css-helper">#navigation:after { left: '+ caretPosition +'px; }</style>');
  1378. }
  1379. });
  1380. $('#header #appmenu .menutoggle').on('click', function() {
  1381. $('#appmenu').toggleClass('menu-open');
  1382. if($('#appmenu').is(':visible')) {
  1383. $('#menu-css-helper').remove();
  1384. }
  1385. });
  1386. }
  1387. var resizeMenu = function() {
  1388. var appList = $('#appmenu li');
  1389. var headerWidth = $('.header-left').width() - $('#nextcloud').width();
  1390. var usePercentualAppMenuLimit = 0.33;
  1391. var minAppsDesktop = 8;
  1392. var availableWidth = headerWidth - $(appList).width();
  1393. var isMobile = $(window).width() < 768;
  1394. if (!isMobile) {
  1395. availableWidth = headerWidth * usePercentualAppMenuLimit;
  1396. }
  1397. var appCount = Math.floor((availableWidth / $(appList).width()));
  1398. if (isMobile && appCount > minAppsDesktop) {
  1399. appCount = minAppsDesktop;
  1400. }
  1401. if (!isMobile && appCount < minAppsDesktop) {
  1402. appCount = minAppsDesktop;
  1403. }
  1404. // show at least 2 apps in the popover
  1405. if(appList.length-1-appCount >= 1) {
  1406. appCount--;
  1407. }
  1408. // show at least one icon
  1409. if(appCount < 1) {
  1410. appCount = 1;
  1411. }
  1412. $('#more-apps a').removeClass('active');
  1413. var lastShownApp;
  1414. for (var k = 0; k < appList.length-1; k++) {
  1415. var name = $(appList[k]).data('id');
  1416. if(k < appCount) {
  1417. $(appList[k]).removeClass('hidden');
  1418. $('#apps li[data-id=' + name + ']').addClass('in-header');
  1419. lastShownApp = appList[k];
  1420. } else {
  1421. $(appList[k]).addClass('hidden');
  1422. $('#apps li[data-id=' + name + ']').removeClass('in-header');
  1423. // move active app to last position if it is active
  1424. if(appCount > 0 && $(appList[k]).children('a').hasClass('active')) {
  1425. $(lastShownApp).addClass('hidden');
  1426. $('#apps li[data-id=' + $(lastShownApp).data('id') + ']').removeClass('in-header');
  1427. $(appList[k]).removeClass('hidden');
  1428. $('#apps li[data-id=' + name + ']').addClass('in-header');
  1429. }
  1430. }
  1431. }
  1432. // show/hide more apps icon
  1433. if($('#apps li:not(.in-header)').length === 0) {
  1434. $('#more-apps').hide();
  1435. $('#navigation').hide();
  1436. } else {
  1437. $('#more-apps').show();
  1438. }
  1439. };
  1440. $(window).resize(resizeMenu);
  1441. resizeMenu();
  1442. // just add snapper for logged in users
  1443. if($('#app-navigation').length && !$('html').hasClass('lte9')) {
  1444. // App sidebar on mobile
  1445. var snapper = new Snap({
  1446. element: document.getElementById('app-content'),
  1447. disable: 'right',
  1448. maxPosition: 250,
  1449. minDragDistance: 100
  1450. });
  1451. $('#app-content').prepend('<div id="app-navigation-toggle" class="icon-menu" style="display:none;"></div>');
  1452. $('#app-navigation-toggle').click(function(){
  1453. if(snapper.state().state == 'left'){
  1454. snapper.close();
  1455. } else {
  1456. snapper.open('left');
  1457. }
  1458. });
  1459. // close sidebar when switching navigation entry
  1460. var $appNavigation = $('#app-navigation');
  1461. $appNavigation.delegate('a, :button', 'click', function(event) {
  1462. var $target = $(event.target);
  1463. // don't hide navigation when changing settings or adding things
  1464. if($target.is('.app-navigation-noclose') ||
  1465. $target.closest('.app-navigation-noclose').length) {
  1466. return;
  1467. }
  1468. if($target.is('.app-navigation-entry-utils-menu-button') ||
  1469. $target.closest('.app-navigation-entry-utils-menu-button').length) {
  1470. return;
  1471. }
  1472. if($target.is('.add-new') ||
  1473. $target.closest('.add-new').length) {
  1474. return;
  1475. }
  1476. if($target.is('#app-settings') ||
  1477. $target.closest('#app-settings').length) {
  1478. return;
  1479. }
  1480. snapper.close();
  1481. });
  1482. var navigationBarSlideGestureEnabled = false;
  1483. var navigationBarSlideGestureAllowed = true;
  1484. var navigationBarSlideGestureEnablePending = false;
  1485. OC.allowNavigationBarSlideGesture = function() {
  1486. navigationBarSlideGestureAllowed = true;
  1487. if (navigationBarSlideGestureEnablePending) {
  1488. snapper.enable();
  1489. navigationBarSlideGestureEnabled = true;
  1490. navigationBarSlideGestureEnablePending = false;
  1491. }
  1492. };
  1493. OC.disallowNavigationBarSlideGesture = function() {
  1494. navigationBarSlideGestureAllowed = false;
  1495. if (navigationBarSlideGestureEnabled) {
  1496. var endCurrentDrag = true;
  1497. snapper.disable(endCurrentDrag);
  1498. navigationBarSlideGestureEnabled = false;
  1499. navigationBarSlideGestureEnablePending = true;
  1500. }
  1501. };
  1502. var toggleSnapperOnSize = function() {
  1503. if($(window).width() > 768) {
  1504. snapper.close();
  1505. snapper.disable();
  1506. navigationBarSlideGestureEnabled = false;
  1507. navigationBarSlideGestureEnablePending = false;
  1508. } else if (navigationBarSlideGestureAllowed) {
  1509. snapper.enable();
  1510. navigationBarSlideGestureEnabled = true;
  1511. navigationBarSlideGestureEnablePending = false;
  1512. } else {
  1513. navigationBarSlideGestureEnablePending = true;
  1514. }
  1515. };
  1516. $(window).resize(_.debounce(toggleSnapperOnSize, 250));
  1517. // initial call
  1518. toggleSnapperOnSize();
  1519. }
  1520. // Update live timestamps every 30 seconds
  1521. setInterval(function() {
  1522. $('.live-relative-timestamp').each(function() {
  1523. $(this).text(OC.Util.relativeModifiedDate(parseInt($(this).attr('data-timestamp'), 10)));
  1524. });
  1525. }, 30 * 1000);
  1526. OC.PasswordConfirmation.init();
  1527. }
  1528. OC.PasswordConfirmation = {
  1529. callback: null,
  1530. pageLoadTime: null,
  1531. init: function() {
  1532. $('.password-confirm-required').on('click', _.bind(this.requirePasswordConfirmation, this));
  1533. this.pageLoadTime = moment.now();
  1534. },
  1535. requiresPasswordConfirmation: function() {
  1536. var serverTimeDiff = this.pageLoadTime - (nc_pageLoad * 1000);
  1537. var timeSinceLogin = moment.now() - (serverTimeDiff + (nc_lastLogin * 1000));
  1538. // if timeSinceLogin > 30 minutes and user backend allows password confirmation
  1539. return (backendAllowsPasswordConfirmation && timeSinceLogin > 30 * 60 * 1000);
  1540. },
  1541. /**
  1542. * @param {function} callback
  1543. */
  1544. requirePasswordConfirmation: function(callback) {
  1545. var self = this;
  1546. if (this.requiresPasswordConfirmation()) {
  1547. OC.dialogs.prompt(
  1548. t(
  1549. 'core',
  1550. 'This action requires you to confirm your password'
  1551. ),
  1552. t('core','Authentication required'),
  1553. function (result, password) {
  1554. if (result && password !== '') {
  1555. self._confirmPassword(password);
  1556. }
  1557. },
  1558. true,
  1559. t('core','Password'),
  1560. true
  1561. ).then(function() {
  1562. var $dialog = $('.oc-dialog:visible');
  1563. $dialog.find('.ui-icon').remove();
  1564. var $buttons = $dialog.find('button');
  1565. $buttons.eq(0).text(t('core', 'Cancel'));
  1566. $buttons.eq(1).text(t('core', 'Confirm'));
  1567. });
  1568. }
  1569. this.callback = callback;
  1570. },
  1571. _confirmPassword: function(password) {
  1572. var self = this;
  1573. $.ajax({
  1574. url: OC.generateUrl('/login/confirm'),
  1575. data: {
  1576. password: password
  1577. },
  1578. type: 'POST',
  1579. success: function(response) {
  1580. nc_lastLogin = response.lastLogin;
  1581. if (_.isFunction(self.callback)) {
  1582. self.callback();
  1583. }
  1584. },
  1585. error: function() {
  1586. OC.PasswordConfirmation.requirePasswordConfirmation(self.callback);
  1587. OC.Notification.showTemporary(t('core', 'Failed to authenticate, try again'));
  1588. }
  1589. });
  1590. }
  1591. };
  1592. $(document).ready(initCore);
  1593. /**
  1594. * Filter Jquery selector by attribute value
  1595. */
  1596. $.fn.filterAttr = function(attr_name, attr_value) {
  1597. return this.filter(function() { return $(this).attr(attr_name) === attr_value; });
  1598. };
  1599. /**
  1600. * Returns a human readable file size
  1601. * @param {number} size Size in bytes
  1602. * @param {boolean} skipSmallSizes return '< 1 kB' for small files
  1603. * @return {string}
  1604. */
  1605. function humanFileSize(size, skipSmallSizes) {
  1606. var humanList = ['B', 'KB', 'MB', 'GB', 'TB'];
  1607. // Calculate Log with base 1024: size = 1024 ** order
  1608. var order = size > 0 ? Math.floor(Math.log(size) / Math.log(1024)) : 0;
  1609. // Stay in range of the byte sizes that are defined
  1610. order = Math.min(humanList.length - 1, order);
  1611. var readableFormat = humanList[order];
  1612. var relativeSize = (size / Math.pow(1024, order)).toFixed(1);
  1613. if(skipSmallSizes === true && order === 0) {
  1614. if(relativeSize !== "0.0"){
  1615. return '< 1 KB';
  1616. } else {
  1617. return '0 KB';
  1618. }
  1619. }
  1620. if(order < 2){
  1621. relativeSize = parseFloat(relativeSize).toFixed(0);
  1622. }
  1623. else if(relativeSize.substr(relativeSize.length-2,2)==='.0'){
  1624. relativeSize=relativeSize.substr(0,relativeSize.length-2);
  1625. }
  1626. return relativeSize + ' ' + readableFormat;
  1627. }
  1628. /**
  1629. * Format an UNIX timestamp to a human understandable format
  1630. * @param {number} timestamp UNIX timestamp
  1631. * @return {string} Human readable format
  1632. */
  1633. function formatDate(timestamp){
  1634. return OC.Util.formatDate(timestamp);
  1635. }
  1636. //
  1637. /**
  1638. * Get the value of a URL parameter
  1639. * @link http://stackoverflow.com/questions/1403888/get-url-parameter-with-jquery
  1640. * @param {string} name URL parameter
  1641. * @return {string}
  1642. */
  1643. function getURLParameter(name) {
  1644. return decodeURIComponent(
  1645. (new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(
  1646. location.search)||[,''])[1].replace(/\+/g, '%20')
  1647. )||'';
  1648. }
  1649. /**
  1650. * Takes an absolute timestamp and return a string with a human-friendly relative date
  1651. * @param {number} timestamp A Unix timestamp
  1652. */
  1653. function relative_modified_date(timestamp) {
  1654. /*
  1655. Were multiplying by 1000 to bring the timestamp back to its original value
  1656. per https://github.com/owncloud/core/pull/10647#discussion_r16790315
  1657. */
  1658. return OC.Util.relativeModifiedDate(timestamp * 1000);
  1659. }
  1660. /**
  1661. * Utility functions
  1662. * @namespace
  1663. */
  1664. OC.Util = {
  1665. // TODO: remove original functions from global namespace
  1666. humanFileSize: humanFileSize,
  1667. /**
  1668. * Returns a file size in bytes from a humanly readable string
  1669. * Makes 2kB to 2048.
  1670. * Inspired by computerFileSize in helper.php
  1671. * @param {string} string file size in human readable format
  1672. * @return {number} or null if string could not be parsed
  1673. *
  1674. *
  1675. */
  1676. computerFileSize: function (string) {
  1677. if (typeof string !== 'string') {
  1678. return null;
  1679. }
  1680. var s = string.toLowerCase().trim();
  1681. var bytes = null;
  1682. var bytesArray = {
  1683. 'b' : 1,
  1684. 'k' : 1024,
  1685. 'kb': 1024,
  1686. 'mb': 1024 * 1024,
  1687. 'm' : 1024 * 1024,
  1688. 'gb': 1024 * 1024 * 1024,
  1689. 'g' : 1024 * 1024 * 1024,
  1690. 'tb': 1024 * 1024 * 1024 * 1024,
  1691. 't' : 1024 * 1024 * 1024 * 1024,
  1692. 'pb': 1024 * 1024 * 1024 * 1024 * 1024,
  1693. 'p' : 1024 * 1024 * 1024 * 1024 * 1024
  1694. };
  1695. var matches = s.match(/^[\s+]?([0-9]*)(\.([0-9]+))?( +)?([kmgtp]?b?)$/i);
  1696. if (matches !== null) {
  1697. bytes = parseFloat(s);
  1698. if (!isFinite(bytes)) {
  1699. return null;
  1700. }
  1701. } else {
  1702. return null;
  1703. }
  1704. if (matches[5]) {
  1705. bytes = bytes * bytesArray[matches[5]];
  1706. }
  1707. bytes = Math.round(bytes);
  1708. return bytes;
  1709. },
  1710. /**
  1711. * @param timestamp
  1712. * @param format
  1713. * @returns {string} timestamp formatted as requested
  1714. */
  1715. formatDate: function (timestamp, format) {
  1716. format = format || "LLL";
  1717. return moment(timestamp).format(format);
  1718. },
  1719. /**
  1720. * @param timestamp
  1721. * @returns {string} human readable difference from now
  1722. */
  1723. relativeModifiedDate: function (timestamp) {
  1724. var diff = moment().diff(moment(timestamp));
  1725. if (diff >= 0 && diff < 45000 ) {
  1726. return t('core', 'seconds ago');
  1727. }
  1728. return moment(timestamp).fromNow();
  1729. },
  1730. /**
  1731. * Returns whether the browser supports SVG
  1732. * @deprecated SVG is always supported (since 9.0)
  1733. * @return {boolean} true if the browser supports SVG, false otherwise
  1734. */
  1735. hasSVGSupport: function(){
  1736. return true;
  1737. },
  1738. /**
  1739. * If SVG is not supported, replaces the given icon's extension
  1740. * from ".svg" to ".png".
  1741. * If SVG is supported, return the image path as is.
  1742. * @param {string} file image path with svg extension
  1743. * @deprecated SVG is always supported (since 9.0)
  1744. * @return {string} fixed image path with png extension if SVG is not supported
  1745. */
  1746. replaceSVGIcon: function(file) {
  1747. return file;
  1748. },
  1749. /**
  1750. * Replace SVG images in all elements that have the "svg" class set
  1751. * with PNG images.
  1752. *
  1753. * @param $el root element from which to search, defaults to $('body')
  1754. * @deprecated SVG is always supported (since 9.0)
  1755. */
  1756. replaceSVG: function($el) {},
  1757. /**
  1758. * Fix image scaling for IE8, since background-size is not supported.
  1759. *
  1760. * This scales the image to the element's actual size, the URL is
  1761. * taken from the "background-image" CSS attribute.
  1762. *
  1763. * @deprecated IE8 isn't supported since 9.0
  1764. * @param {Object} $el image element
  1765. */
  1766. scaleFixForIE8: function($el) {},
  1767. /**
  1768. * Returns whether this is IE
  1769. *
  1770. * @return {bool} true if this is IE, false otherwise
  1771. */
  1772. isIE: function() {
  1773. return $('html').hasClass('ie');
  1774. },
  1775. /**
  1776. * Returns whether this is IE8
  1777. *
  1778. * @deprecated IE8 isn't supported since 9.0
  1779. * @return {bool} false (IE8 isn't supported anymore)
  1780. */
  1781. isIE8: function() {
  1782. return false;
  1783. },
  1784. /**
  1785. * Returns the width of a generic browser scrollbar
  1786. *
  1787. * @return {int} width of scrollbar
  1788. */
  1789. getScrollBarWidth: function() {
  1790. if (this._scrollBarWidth) {
  1791. return this._scrollBarWidth;
  1792. }
  1793. var inner = document.createElement('p');
  1794. inner.style.width = "100%";
  1795. inner.style.height = "200px";
  1796. var outer = document.createElement('div');
  1797. outer.style.position = "absolute";
  1798. outer.style.top = "0px";
  1799. outer.style.left = "0px";
  1800. outer.style.visibility = "hidden";
  1801. outer.style.width = "200px";
  1802. outer.style.height = "150px";
  1803. outer.style.overflow = "hidden";
  1804. outer.appendChild (inner);
  1805. document.body.appendChild (outer);
  1806. var w1 = inner.offsetWidth;
  1807. outer.style.overflow = 'scroll';
  1808. var w2 = inner.offsetWidth;
  1809. if(w1 === w2) {
  1810. w2 = outer.clientWidth;
  1811. }
  1812. document.body.removeChild (outer);
  1813. this._scrollBarWidth = (w1 - w2);
  1814. return this._scrollBarWidth;
  1815. },
  1816. /**
  1817. * Remove the time component from a given date
  1818. *
  1819. * @param {Date} date date
  1820. * @return {Date} date with stripped time
  1821. */
  1822. stripTime: function(date) {
  1823. // FIXME: likely to break when crossing DST
  1824. // would be better to use a library like momentJS
  1825. return new Date(date.getFullYear(), date.getMonth(), date.getDate());
  1826. },
  1827. _chunkify: function(t) {
  1828. // Adapted from http://my.opera.com/GreyWyvern/blog/show.dml/1671288
  1829. var tz = [], x = 0, y = -1, n = 0, code, c;
  1830. while (x < t.length) {
  1831. c = t.charAt(x);
  1832. // only include the dot in strings
  1833. var m = ((!n && c === '.') || (c >= '0' && c <= '9'));
  1834. if (m !== n) {
  1835. // next chunk
  1836. y++;
  1837. tz[y] = '';
  1838. n = m;
  1839. }
  1840. tz[y] += c;
  1841. x++;
  1842. }
  1843. return tz;
  1844. },
  1845. /**
  1846. * Compare two strings to provide a natural sort
  1847. * @param a first string to compare
  1848. * @param b second string to compare
  1849. * @return -1 if b comes before a, 1 if a comes before b
  1850. * or 0 if the strings are identical
  1851. */
  1852. naturalSortCompare: function(a, b) {
  1853. var x;
  1854. var aa = OC.Util._chunkify(a);
  1855. var bb = OC.Util._chunkify(b);
  1856. for (x = 0; aa[x] && bb[x]; x++) {
  1857. if (aa[x] !== bb[x]) {
  1858. var aNum = Number(aa[x]), bNum = Number(bb[x]);
  1859. // note: == is correct here
  1860. if (aNum == aa[x] && bNum == bb[x]) {
  1861. return aNum - bNum;
  1862. } else {
  1863. // Forcing 'en' locale to match the server-side locale which is
  1864. // always 'en'.
  1865. //
  1866. // Note: This setting isn't supported by all browsers but for the ones
  1867. // that do there will be more consistency between client-server sorting
  1868. return aa[x].localeCompare(bb[x], 'en');
  1869. }
  1870. }
  1871. }
  1872. return aa.length - bb.length;
  1873. },
  1874. /**
  1875. * Calls the callback in a given interval until it returns true
  1876. * @param {function} callback
  1877. * @param {integer} interval in milliseconds
  1878. */
  1879. waitFor: function(callback, interval) {
  1880. var internalCallback = function() {
  1881. if(callback() !== true) {
  1882. setTimeout(internalCallback, interval);
  1883. }
  1884. };
  1885. internalCallback();
  1886. },
  1887. /**
  1888. * Checks if a cookie with the given name is present and is set to the provided value.
  1889. * @param {string} name name of the cookie
  1890. * @param {string} value value of the cookie
  1891. * @return {boolean} true if the cookie with the given name has the given value
  1892. */
  1893. isCookieSetToValue: function(name, value) {
  1894. var cookies = document.cookie.split(';');
  1895. for (var i=0; i < cookies.length; i++) {
  1896. var cookie = cookies[i].split('=');
  1897. if (cookie[0].trim() === name && cookie[1].trim() === value) {
  1898. return true;
  1899. }
  1900. }
  1901. return false;
  1902. }
  1903. };
  1904. /**
  1905. * Utility class for the history API,
  1906. * includes fallback to using the URL hash when
  1907. * the browser doesn't support the history API.
  1908. *
  1909. * @namespace
  1910. */
  1911. OC.Util.History = {
  1912. _handlers: [],
  1913. /**
  1914. * Push the current URL parameters to the history stack
  1915. * and change the visible URL.
  1916. * Note: this includes a workaround for IE8/IE9 that uses
  1917. * the hash part instead of the search part.
  1918. *
  1919. * @param {Object|string} params to append to the URL, can be either a string
  1920. * or a map
  1921. * @param {string} [url] URL to be used, otherwise the current URL will be used,
  1922. * using the params as query string
  1923. * @param {boolean} [replace=false] whether to replace instead of pushing
  1924. */
  1925. _pushState: function(params, url, replace) {
  1926. var strParams;
  1927. if (typeof(params) === 'string') {
  1928. strParams = params;
  1929. }
  1930. else {
  1931. strParams = OC.buildQueryString(params);
  1932. }
  1933. if (window.history.pushState) {
  1934. url = url || location.pathname + '?' + strParams;
  1935. // Workaround for bug with SVG and window.history.pushState on Firefox < 51
  1936. // https://bugzilla.mozilla.org/show_bug.cgi?id=652991
  1937. var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  1938. if (isFirefox && parseInt(navigator.userAgent.split('/').pop()) < 51) {
  1939. var patterns = document.querySelectorAll('[fill^="url(#"], [stroke^="url(#"], [filter^="url(#invert"]');
  1940. for (var i = 0, ii = patterns.length, pattern; i < ii; i++) {
  1941. pattern = patterns[i];
  1942. pattern.style.fill = pattern.style.fill;
  1943. pattern.style.stroke = pattern.style.stroke;
  1944. pattern.removeAttribute("filter");
  1945. pattern.setAttribute("filter", "url(#invert)");
  1946. }
  1947. }
  1948. if (replace) {
  1949. window.history.replaceState(params, '', url);
  1950. } else {
  1951. window.history.pushState(params, '', url);
  1952. }
  1953. }
  1954. // use URL hash for IE8
  1955. else {
  1956. window.location.hash = '?' + strParams;
  1957. // inhibit next onhashchange that just added itself
  1958. // to the event queue
  1959. this._cancelPop = true;
  1960. }
  1961. },
  1962. /**
  1963. * Push the current URL parameters to the history stack
  1964. * and change the visible URL.
  1965. * Note: this includes a workaround for IE8/IE9 that uses
  1966. * the hash part instead of the search part.
  1967. *
  1968. * @param {Object|string} params to append to the URL, can be either a string
  1969. * or a map
  1970. * @param {string} [url] URL to be used, otherwise the current URL will be used,
  1971. * using the params as query string
  1972. */
  1973. pushState: function(params, url) {
  1974. return this._pushState(params, url, false);
  1975. },
  1976. /**
  1977. * Push the current URL parameters to the history stack
  1978. * and change the visible URL.
  1979. * Note: this includes a workaround for IE8/IE9 that uses
  1980. * the hash part instead of the search part.
  1981. *
  1982. * @param {Object|string} params to append to the URL, can be either a string
  1983. * or a map
  1984. * @param {string} [url] URL to be used, otherwise the current URL will be used,
  1985. * using the params as query string
  1986. */
  1987. replaceState: function(params, url) {
  1988. return this._pushState(params, url, true);
  1989. },
  1990. /**
  1991. * Add a popstate handler
  1992. *
  1993. * @param handler function
  1994. */
  1995. addOnPopStateHandler: function(handler) {
  1996. this._handlers.push(handler);
  1997. },
  1998. /**
  1999. * Parse a query string from the hash part of the URL.
  2000. * (workaround for IE8 / IE9)
  2001. */
  2002. _parseHashQuery: function() {
  2003. var hash = window.location.hash,
  2004. pos = hash.indexOf('?');
  2005. if (pos >= 0) {
  2006. return hash.substr(pos + 1);
  2007. }
  2008. if (hash.length) {
  2009. // remove hash sign
  2010. return hash.substr(1);
  2011. }
  2012. return '';
  2013. },
  2014. _decodeQuery: function(query) {
  2015. return query.replace(/\+/g, ' ');
  2016. },
  2017. /**
  2018. * Parse the query/search part of the URL.
  2019. * Also try and parse it from the URL hash (for IE8)
  2020. *
  2021. * @return map of parameters
  2022. */
  2023. parseUrlQuery: function() {
  2024. var query = this._parseHashQuery(),
  2025. params;
  2026. // try and parse from URL hash first
  2027. if (query) {
  2028. params = OC.parseQueryString(this._decodeQuery(query));
  2029. }
  2030. // else read from query attributes
  2031. params = _.extend(params || {}, OC.parseQueryString(this._decodeQuery(location.search)));
  2032. return params || {};
  2033. },
  2034. _onPopState: function(e) {
  2035. if (this._cancelPop) {
  2036. this._cancelPop = false;
  2037. return;
  2038. }
  2039. var params;
  2040. if (!this._handlers.length) {
  2041. return;
  2042. }
  2043. params = (e && e.state);
  2044. if (_.isString(params)) {
  2045. params = OC.parseQueryString(params);
  2046. } else if (!params) {
  2047. params = this.parseUrlQuery() || {};
  2048. }
  2049. for (var i = 0; i < this._handlers.length; i++) {
  2050. this._handlers[i](params);
  2051. }
  2052. }
  2053. };
  2054. // fallback to hashchange when no history support
  2055. if (window.history.pushState) {
  2056. window.onpopstate = _.bind(OC.Util.History._onPopState, OC.Util.History);
  2057. }
  2058. else {
  2059. $(window).on('hashchange', _.bind(OC.Util.History._onPopState, OC.Util.History));
  2060. }
  2061. /**
  2062. * Get a variable by name
  2063. * @param {string} name
  2064. * @return {*}
  2065. */
  2066. OC.get=function(name) {
  2067. var namespaces = name.split(".");
  2068. var tail = namespaces.pop();
  2069. var context=window;
  2070. for(var i = 0; i < namespaces.length; i++) {
  2071. context = context[namespaces[i]];
  2072. if(!context){
  2073. return false;
  2074. }
  2075. }
  2076. return context[tail];
  2077. };
  2078. /**
  2079. * Set a variable by name
  2080. * @param {string} name
  2081. * @param {*} value
  2082. */
  2083. OC.set=function(name, value) {
  2084. var namespaces = name.split(".");
  2085. var tail = namespaces.pop();
  2086. var context=window;
  2087. for(var i = 0; i < namespaces.length; i++) {
  2088. if(!context[namespaces[i]]){
  2089. context[namespaces[i]]={};
  2090. }
  2091. context = context[namespaces[i]];
  2092. }
  2093. context[tail]=value;
  2094. };
  2095. // fix device width on windows phone
  2096. (function() {
  2097. if ("-ms-user-select" in document.documentElement.style && navigator.userAgent.match(/IEMobile\/10\.0/)) {
  2098. var msViewportStyle = document.createElement("style");
  2099. msViewportStyle.appendChild(
  2100. document.createTextNode("@-ms-viewport{width:auto!important}")
  2101. );
  2102. document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
  2103. }
  2104. })();
  2105. /**
  2106. * Namespace for apps
  2107. * @namespace OCA
  2108. */
  2109. window.OCA = {};
  2110. /**
  2111. * select a range in an input field
  2112. * @link http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area
  2113. * @param {type} start
  2114. * @param {type} end
  2115. */
  2116. jQuery.fn.selectRange = function(start, end) {
  2117. return this.each(function() {
  2118. if (this.setSelectionRange) {
  2119. this.focus();
  2120. this.setSelectionRange(start, end);
  2121. } else if (this.createTextRange) {
  2122. var range = this.createTextRange();
  2123. range.collapse(true);
  2124. range.moveEnd('character', end);
  2125. range.moveStart('character', start);
  2126. range.select();
  2127. }
  2128. });
  2129. };
  2130. /**
  2131. * check if an element exists.
  2132. * allows you to write if ($('#myid').exists()) to increase readability
  2133. * @link http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery
  2134. */
  2135. jQuery.fn.exists = function(){
  2136. return this.length > 0;
  2137. };
  2138. /**
  2139. * @deprecated use OC.Util.getScrollBarWidth() instead
  2140. */
  2141. function getScrollBarWidth() {
  2142. return OC.Util.getScrollBarWidth();
  2143. }
  2144. /**
  2145. * jQuery tipsy shim for the bootstrap tooltip
  2146. */
  2147. jQuery.fn.tipsy = function(argument) {
  2148. console.warn('Deprecation warning: tipsy is deprecated. Use tooltip instead.');
  2149. if(typeof argument === 'object' && argument !== null) {
  2150. // tipsy defaults
  2151. var options = {
  2152. placement: 'bottom',
  2153. delay: { 'show': 0, 'hide': 0},
  2154. trigger: 'hover',
  2155. html: false,
  2156. container: 'body'
  2157. };
  2158. if(argument.gravity) {
  2159. switch(argument.gravity) {
  2160. case 'n':
  2161. case 'nw':
  2162. case 'ne':
  2163. options.placement='bottom';
  2164. break;
  2165. case 's':
  2166. case 'sw':
  2167. case 'se':
  2168. options.placement='top';
  2169. break;
  2170. case 'w':
  2171. options.placement='right';
  2172. break;
  2173. case 'e':
  2174. options.placement='left';
  2175. break;
  2176. }
  2177. }
  2178. if(argument.trigger) {
  2179. options.trigger = argument.trigger;
  2180. }
  2181. if(argument.delayIn) {
  2182. options.delay.show = argument.delayIn;
  2183. }
  2184. if(argument.delayOut) {
  2185. options.delay.hide = argument.delayOut;
  2186. }
  2187. if(argument.html) {
  2188. options.html = true;
  2189. }
  2190. if(argument.fallback) {
  2191. options.title = argument.fallback;
  2192. }
  2193. // destroy old tooltip in case the title has changed
  2194. jQuery.fn.tooltip.call(this, 'destroy');
  2195. jQuery.fn.tooltip.call(this, options);
  2196. } else {
  2197. this.tooltip(argument);
  2198. jQuery.fn.tooltip.call(this, argument);
  2199. }
  2200. return this;
  2201. };