1
0

js.js 60 KB

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