js.js 59 KB

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