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

js.js 59KB

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