js.js 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193
  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 ownCloud root.
  65. * For example: "/owncloud"
  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 ownCloud 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 ownCloud 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 ownCloud 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 ownCloud 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 ownCloud instance
  265. * is accessible, with a leading slash.
  266. * For example "/owncloud".
  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)) {
  729. // sometimes "beforeunload" happens later, so need to defer the reload a bit
  730. setTimeout(function() {
  731. if (!self._userIsNavigatingAway && !self._reloadCalled) {
  732. OC.Notification.show(t('core', 'Problem loading page, reloading in 5 seconds'));
  733. setTimeout(OC.reload, 5000);
  734. // only call reload once
  735. self._reloadCalled = true;
  736. }
  737. }, 100);
  738. } else if(xhr.status === 0) {
  739. // Connection lost (e.g. WiFi disconnected or server is down)
  740. setTimeout(function() {
  741. if (!self._userIsNavigatingAway && !self._reloadCalled) {
  742. self._ajaxConnectionLostHandler();
  743. }
  744. }, 100);
  745. }
  746. },
  747. /**
  748. * Registers XmlHttpRequest object for global error processing.
  749. *
  750. * This means that if this XHR object returns 401 or session timeout errors,
  751. * the current page will automatically be reloaded.
  752. *
  753. * @param {XMLHttpRequest} xhr
  754. */
  755. registerXHRForErrorProcessing: function(xhr) {
  756. var loadCallback = function() {
  757. if (xhr.readyState !== 4) {
  758. return;
  759. }
  760. if (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) {
  761. return;
  762. }
  763. // fire jquery global ajax error handler
  764. $(document).trigger(new $.Event('ajaxError'), xhr);
  765. };
  766. var errorCallback = function() {
  767. // fire jquery global ajax error handler
  768. $(document).trigger(new $.Event('ajaxError'), xhr);
  769. };
  770. if (xhr.addEventListener) {
  771. xhr.addEventListener('load', loadCallback);
  772. xhr.addEventListener('error', errorCallback);
  773. }
  774. }
  775. };
  776. /**
  777. * Current user attributes
  778. *
  779. * @typedef {Object} OC.CurrentUser
  780. *
  781. * @property {String} uid user id
  782. * @property {String} displayName display name
  783. */
  784. /**
  785. * @namespace OC.Plugins
  786. */
  787. OC.Plugins = {
  788. /**
  789. * @type Array.<OC.Plugin>
  790. */
  791. _plugins: {},
  792. /**
  793. * Register plugin
  794. *
  795. * @param {String} targetName app name / class name to hook into
  796. * @param {OC.Plugin} plugin
  797. */
  798. register: function(targetName, plugin) {
  799. var plugins = this._plugins[targetName];
  800. if (!plugins) {
  801. plugins = this._plugins[targetName] = [];
  802. }
  803. plugins.push(plugin);
  804. },
  805. /**
  806. * Returns all plugin registered to the given target
  807. * name / app name / class name.
  808. *
  809. * @param {String} targetName app name / class name to hook into
  810. * @return {Array.<OC.Plugin>} array of plugins
  811. */
  812. getPlugins: function(targetName) {
  813. return this._plugins[targetName] || [];
  814. },
  815. /**
  816. * Call attach() on all plugins registered to the given target name.
  817. *
  818. * @param {String} targetName app name / class name
  819. * @param {Object} object to be extended
  820. * @param {Object} [options] options
  821. */
  822. attach: function(targetName, targetObject, options) {
  823. var plugins = this.getPlugins(targetName);
  824. for (var i = 0; i < plugins.length; i++) {
  825. if (plugins[i].attach) {
  826. plugins[i].attach(targetObject, options);
  827. }
  828. }
  829. },
  830. /**
  831. * Call detach() on all plugins registered to the given target name.
  832. *
  833. * @param {String} targetName app name / class name
  834. * @param {Object} object to be extended
  835. * @param {Object} [options] options
  836. */
  837. detach: function(targetName, targetObject, options) {
  838. var plugins = this.getPlugins(targetName);
  839. for (var i = 0; i < plugins.length; i++) {
  840. if (plugins[i].detach) {
  841. plugins[i].detach(targetObject, options);
  842. }
  843. }
  844. },
  845. /**
  846. * Plugin
  847. *
  848. * @todo make this a real class in the future
  849. * @typedef {Object} OC.Plugin
  850. *
  851. * @property {String} name plugin name
  852. * @property {Function} attach function that will be called when the
  853. * plugin is attached
  854. * @property {Function} [detach] function that will be called when the
  855. * plugin is detached
  856. */
  857. };
  858. /**
  859. * @namespace OC.search
  860. */
  861. OC.search.customResults = {};
  862. /**
  863. * @deprecated use get/setFormatter() instead
  864. */
  865. OC.search.resultTypes = {};
  866. OC.addStyle.loaded=[];
  867. OC.addScript.loaded=[];
  868. /**
  869. * A little class to manage a status field for a "saving" process.
  870. * It can be used to display a starting message (e.g. "Saving...") and then
  871. * replace it with a green success message or a red error message.
  872. *
  873. * @namespace OC.msg
  874. */
  875. OC.msg = {
  876. /**
  877. * Displayes a "Saving..." message in the given message placeholder
  878. *
  879. * @param {Object} selector Placeholder to display the message in
  880. */
  881. startSaving: function(selector) {
  882. this.startAction(selector, t('core', 'Saving...'));
  883. },
  884. /**
  885. * Displayes a custom message in the given message placeholder
  886. *
  887. * @param {Object} selector Placeholder to display the message in
  888. * @param {string} message Plain text message to display (no HTML allowed)
  889. */
  890. startAction: function(selector, message) {
  891. $(selector).text(message)
  892. .removeClass('success')
  893. .removeClass('error')
  894. .stop(true, true)
  895. .show();
  896. },
  897. /**
  898. * Displayes an success/error message in the given selector
  899. *
  900. * @param {Object} selector Placeholder to display the message in
  901. * @param {Object} response Response of the server
  902. * @param {Object} response.data Data of the servers response
  903. * @param {string} response.data.message Plain text message to display (no HTML allowed)
  904. * @param {string} response.status is being used to decide whether the message
  905. * is displayed as an error/success
  906. */
  907. finishedSaving: function(selector, response) {
  908. this.finishedAction(selector, response);
  909. },
  910. /**
  911. * Displayes an success/error message in the given selector
  912. *
  913. * @param {Object} selector Placeholder to display the message in
  914. * @param {Object} response Response of the server
  915. * @param {Object} response.data Data of the servers response
  916. * @param {string} response.data.message Plain text message to display (no HTML allowed)
  917. * @param {string} response.status is being used to decide whether the message
  918. * is displayed as an error/success
  919. */
  920. finishedAction: function(selector, response) {
  921. if (response.status === "success") {
  922. this.finishedSuccess(selector, response.data.message);
  923. } else {
  924. this.finishedError(selector, response.data.message);
  925. }
  926. },
  927. /**
  928. * Displayes an success message in the given selector
  929. *
  930. * @param {Object} selector Placeholder to display the message in
  931. * @param {string} message Plain text success message to display (no HTML allowed)
  932. */
  933. finishedSuccess: function(selector, message) {
  934. $(selector).text(message)
  935. .addClass('success')
  936. .removeClass('error')
  937. .stop(true, true)
  938. .delay(3000)
  939. .fadeOut(900)
  940. .show();
  941. },
  942. /**
  943. * Displayes an error message in the given selector
  944. *
  945. * @param {Object} selector Placeholder to display the message in
  946. * @param {string} message Plain text error message to display (no HTML allowed)
  947. */
  948. finishedError: function(selector, message) {
  949. $(selector).text(message)
  950. .addClass('error')
  951. .removeClass('success')
  952. .show();
  953. }
  954. };
  955. /**
  956. * @todo Write documentation
  957. * @namespace
  958. */
  959. OC.Notification={
  960. queuedNotifications: [],
  961. getDefaultNotificationFunction: null,
  962. /**
  963. * @type Array.<int> array of notification timers
  964. */
  965. notificationTimers: [],
  966. /**
  967. * @param callback
  968. * @todo Write documentation
  969. */
  970. setDefault: function(callback) {
  971. OC.Notification.getDefaultNotificationFunction = callback;
  972. },
  973. /**
  974. * Hides a notification.
  975. *
  976. * If a row is given, only hide that one.
  977. * If no row is given, hide all notifications.
  978. *
  979. * @param {jQuery} [$row] notification row
  980. * @param {Function} [callback] callback
  981. */
  982. hide: function($row, callback) {
  983. var self = this;
  984. var $notification = $('#notification');
  985. if (_.isFunction($row)) {
  986. // first arg is the callback
  987. callback = $row;
  988. $row = undefined;
  989. }
  990. if (!$row) {
  991. console.warn('Missing argument $row in OC.Notification.hide() call, caller needs to be adjusted to only dismiss its own notification');
  992. // assume that the row to be hidden is the first one
  993. $row = $notification.find('.row:first');
  994. }
  995. if ($row && $notification.find('.row').length > 1) {
  996. // remove the row directly
  997. $row.remove();
  998. if (callback) {
  999. callback.call();
  1000. }
  1001. return;
  1002. }
  1003. _.defer(function() {
  1004. // fade out is supposed to only fade when there is a single row
  1005. // however, some code might call hide() and show() directly after,
  1006. // which results in more than one element
  1007. // in this case, simply delete that one element that was supposed to
  1008. // fade out
  1009. //
  1010. // FIXME: remove once all callers are adjusted to only hide their own notifications
  1011. if ($notification.find('.row').length > 1) {
  1012. $row.remove();
  1013. return;
  1014. }
  1015. // else, fade out whatever was present
  1016. $notification.fadeOut('400', function(){
  1017. if (self.isHidden()) {
  1018. if (self.getDefaultNotificationFunction) {
  1019. self.getDefaultNotificationFunction.call();
  1020. }
  1021. }
  1022. if (callback) {
  1023. callback.call();
  1024. }
  1025. $notification.empty();
  1026. });
  1027. });
  1028. },
  1029. /**
  1030. * Shows a notification as HTML without being sanitized before.
  1031. * If you pass unsanitized user input this may lead to a XSS vulnerability.
  1032. * Consider using show() instead of showHTML()
  1033. *
  1034. * @param {string} html Message to display
  1035. * @param {Object} [options] options
  1036. * @param {string] [options.type] notification type
  1037. * @param {int} [options.timeout=0] timeout value, defaults to 0 (permanent)
  1038. * @return {jQuery} jQuery element for notification row
  1039. */
  1040. showHtml: function(html, options) {
  1041. options = options || {};
  1042. _.defaults(options, {
  1043. timeout: 0
  1044. });
  1045. var self = this;
  1046. var $notification = $('#notification');
  1047. if (this.isHidden()) {
  1048. $notification.fadeIn().css('display','inline-block');
  1049. }
  1050. var $row = $('<div class="row"></div>');
  1051. if (options.type) {
  1052. $row.addClass('type-' + options.type);
  1053. }
  1054. if (options.type === 'error') {
  1055. // add a close button
  1056. var $closeButton = $('<a class="action close icon-close" href="#"></a>');
  1057. $closeButton.attr('alt', t('core', 'Dismiss'));
  1058. $row.append($closeButton);
  1059. $closeButton.one('click', function() {
  1060. self.hide($row);
  1061. return false;
  1062. });
  1063. $row.addClass('closeable');
  1064. }
  1065. $row.prepend(html);
  1066. $notification.append($row);
  1067. if(options.timeout > 0) {
  1068. // register timeout to vanish notification
  1069. this.notificationTimers.push(setTimeout(function() {
  1070. self.hide($row);
  1071. }, (options.timeout * 1000)));
  1072. }
  1073. return $row;
  1074. },
  1075. /**
  1076. * Shows a sanitized notification
  1077. *
  1078. * @param {string} text Message to display
  1079. * @param {Object} [options] options
  1080. * @param {string} [options.type] notification type
  1081. * @param {int} [options.timeout=0] timeout value, defaults to 0 (permanent)
  1082. * @return {jQuery} jQuery element for notification row
  1083. */
  1084. show: function(text, options) {
  1085. return this.showHtml($('<div/>').text(text).html(), options);
  1086. },
  1087. /**
  1088. * Shows a notification that disappears after x seconds, default is
  1089. * 7 seconds
  1090. *
  1091. * @param {string} text Message to show
  1092. * @param {array} [options] options array
  1093. * @param {int} [options.timeout=7] timeout in seconds, if this is 0 it will show the message permanently
  1094. * @param {boolean} [options.isHTML=false] an indicator for HTML notifications (true) or text (false)
  1095. * @param {string} [options.type] notification type
  1096. */
  1097. showTemporary: function(text, options) {
  1098. var self = this;
  1099. var defaults = {
  1100. isHTML: false,
  1101. timeout: 7
  1102. };
  1103. options = options || {};
  1104. // merge defaults with passed in options
  1105. _.defaults(options, defaults);
  1106. var $row;
  1107. if(options.isHTML) {
  1108. $row = this.showHtml(text, options);
  1109. } else {
  1110. $row = this.show(text, options);
  1111. }
  1112. return $row;
  1113. },
  1114. /**
  1115. * Returns whether a notification is hidden.
  1116. * @return {boolean}
  1117. */
  1118. isHidden: function() {
  1119. return !$("#notification").find('.row').length;
  1120. }
  1121. };
  1122. /**
  1123. * Initializes core
  1124. */
  1125. function initCore() {
  1126. /**
  1127. * Disable automatic evaluation of responses for $.ajax() functions (and its
  1128. * higher-level alternatives like $.get() and $.post()).
  1129. *
  1130. * If a response to a $.ajax() request returns a content type of "application/javascript"
  1131. * JQuery would previously execute the response body. This is a pretty unexpected
  1132. * behaviour and can result in a bypass of our Content-Security-Policy as well as
  1133. * multiple unexpected XSS vectors.
  1134. */
  1135. $.ajaxSetup({
  1136. contents: {
  1137. script: false
  1138. }
  1139. });
  1140. /**
  1141. * Set users locale to moment.js as soon as possible
  1142. */
  1143. moment.locale(OC.getLocale());
  1144. var userAgent = window.navigator.userAgent;
  1145. var msie = userAgent.indexOf('MSIE ');
  1146. var trident = userAgent.indexOf('Trident/');
  1147. var edge = userAgent.indexOf('Edge/');
  1148. if (msie > 0 || trident > 0) {
  1149. // (IE 10 or older) || IE 11
  1150. $('html').addClass('ie');
  1151. } else if (edge > 0) {
  1152. // for edge
  1153. $('html').addClass('edge');
  1154. }
  1155. $(window).on('unload.main', function() {
  1156. OC._unloadCalled = true;
  1157. });
  1158. $(window).on('beforeunload.main', function() {
  1159. // super-trick thanks to http://stackoverflow.com/a/4651049
  1160. // in case another handler displays a confirmation dialog (ex: navigating away
  1161. // during an upload), there are two possible outcomes: user clicked "ok" or
  1162. // "cancel"
  1163. // first timeout handler is called after unload dialog is closed
  1164. setTimeout(function() {
  1165. OC._userIsNavigatingAway = true;
  1166. // second timeout event is only called if user cancelled (Chrome),
  1167. // but in other browsers it might still be triggered, so need to
  1168. // set a higher delay...
  1169. setTimeout(function() {
  1170. if (!OC._unloadCalled) {
  1171. OC._userIsNavigatingAway = false;
  1172. }
  1173. }, 10000);
  1174. },1);
  1175. });
  1176. $(document).on('ajaxError.main', function( event, request, settings ) {
  1177. if (settings && settings.allowAuthErrors) {
  1178. return;
  1179. }
  1180. OC._processAjaxError(request);
  1181. });
  1182. /**
  1183. * Calls the server periodically to ensure that session doesn't
  1184. * time out
  1185. */
  1186. function initSessionHeartBeat(){
  1187. // max interval in seconds set to 24 hours
  1188. var maxInterval = 24 * 3600;
  1189. // interval in seconds
  1190. var interval = 900;
  1191. if (oc_config.session_lifetime) {
  1192. interval = Math.floor(oc_config.session_lifetime / 2);
  1193. }
  1194. // minimum one minute
  1195. if (interval < 60) {
  1196. interval = 60;
  1197. }
  1198. if (interval > maxInterval) {
  1199. interval = maxInterval;
  1200. }
  1201. var url = OC.generateUrl('/heartbeat');
  1202. var heartBeatTimeout = null;
  1203. var heartBeat = function() {
  1204. clearTimeout(heartBeatTimeout);
  1205. heartBeatTimeout = setInterval(function() {
  1206. $.post(url);
  1207. }, interval * 1000);
  1208. };
  1209. $(document).ajaxComplete(heartBeat);
  1210. heartBeat();
  1211. }
  1212. // session heartbeat (defaults to enabled)
  1213. if (typeof(oc_config.session_keepalive) === 'undefined' ||
  1214. !!oc_config.session_keepalive) {
  1215. initSessionHeartBeat();
  1216. }
  1217. OC.registerMenu($('#expand'), $('#expanddiv'));
  1218. // toggle for menus
  1219. $(document).on('mouseup.closemenus', function(event) {
  1220. var $el = $(event.target);
  1221. if ($el.closest('.menu').length || $el.closest('.menutoggle').length) {
  1222. // don't close when clicking on the menu directly or a menu toggle
  1223. return false;
  1224. }
  1225. OC.hideMenus();
  1226. });
  1227. /**
  1228. * Set up the main menu toggle to react to media query changes.
  1229. * If the screen is small enough, the main menu becomes a toggle.
  1230. * If the screen is bigger, the main menu is not a toggle any more.
  1231. */
  1232. function setupMainMenu() {
  1233. // toggle the navigation
  1234. var $toggle = $('#header .header-appname-container');
  1235. var $navigation = $('#navigation');
  1236. // init the menu
  1237. OC.registerMenu($toggle, $navigation);
  1238. $toggle.data('oldhref', $toggle.attr('href'));
  1239. $toggle.attr('href', '#');
  1240. $navigation.hide();
  1241. // show loading feedback
  1242. $navigation.delegate('a', 'click', function(event) {
  1243. var $app = $(event.target);
  1244. if(!$app.is('a')) {
  1245. $app = $app.closest('a');
  1246. }
  1247. if(event.which === 1 && !event.ctrlKey && !event.metaKey) {
  1248. $app.addClass('app-loading');
  1249. } else {
  1250. // Close navigation when opening app in
  1251. // a new tab
  1252. OC.hideMenus(function(){return false});
  1253. }
  1254. });
  1255. $navigation.delegate('a', 'mouseup', function(event) {
  1256. if(event.which === 2) {
  1257. // Close navigation when opening app in
  1258. // a new tab via middle click
  1259. OC.hideMenus(function(){return false});
  1260. }
  1261. });
  1262. }
  1263. function setupUserMenu() {
  1264. var $menu = $('#header #settings');
  1265. // show loading feedback
  1266. $menu.delegate('a', 'click', function(event) {
  1267. var $page = $(event.target);
  1268. if (!$page.is('a')) {
  1269. $page = $page.closest('a');
  1270. }
  1271. if(event.which === 1 && !event.ctrlKey && !event.metaKey) {
  1272. $page.find('img').remove();
  1273. $page.find('div').remove(); // prevent odd double-clicks
  1274. $page.prepend($('<div/>').addClass('icon-loading-small-dark'));
  1275. } else {
  1276. // Close navigation when opening menu entry in
  1277. // a new tab
  1278. OC.hideMenus(function(){return false});
  1279. }
  1280. });
  1281. $menu.delegate('a', 'mouseup', function(event) {
  1282. if(event.which === 2) {
  1283. // Close navigation when opening app in
  1284. // a new tab via middle click
  1285. OC.hideMenus(function(){return false});
  1286. }
  1287. });
  1288. }
  1289. setupMainMenu();
  1290. setupUserMenu();
  1291. // move triangle of apps dropdown to align with app name triangle
  1292. // 2 is the additional offset between the triangles
  1293. if($('#navigation').length) {
  1294. $('#header #owncloud + .menutoggle').one('click', function(){
  1295. var caretPosition = $('.header-appname + .icon-caret').offset().left - 2;
  1296. if(caretPosition > 255) {
  1297. // if the app name is longer than the menu, just put the triangle in the middle
  1298. return;
  1299. } else {
  1300. $('head').append('<style>#navigation:after { left: '+ caretPosition +'px; }</style>');
  1301. }
  1302. });
  1303. }
  1304. // just add snapper for logged in users
  1305. if($('#app-navigation').length && !$('html').hasClass('lte9')) {
  1306. // App sidebar on mobile
  1307. var snapper = new Snap({
  1308. element: document.getElementById('app-content'),
  1309. disable: 'right',
  1310. maxPosition: 250,
  1311. minDragDistance: 100
  1312. });
  1313. $('#app-content').prepend('<div id="app-navigation-toggle" class="icon-menu" style="display:none;"></div>');
  1314. $('#app-navigation-toggle').click(function(){
  1315. if(snapper.state().state == 'left'){
  1316. snapper.close();
  1317. } else {
  1318. snapper.open('left');
  1319. }
  1320. });
  1321. // close sidebar when switching navigation entry
  1322. var $appNavigation = $('#app-navigation');
  1323. $appNavigation.delegate('a, :button', 'click', function(event) {
  1324. var $target = $(event.target);
  1325. // don't hide navigation when changing settings or adding things
  1326. if($target.is('.app-navigation-noclose') ||
  1327. $target.closest('.app-navigation-noclose').length) {
  1328. return;
  1329. }
  1330. if($target.is('.app-navigation-entry-utils-menu-button') ||
  1331. $target.closest('.app-navigation-entry-utils-menu-button').length) {
  1332. return;
  1333. }
  1334. if($target.is('.add-new') ||
  1335. $target.closest('.add-new').length) {
  1336. return;
  1337. }
  1338. if($target.is('#app-settings') ||
  1339. $target.closest('#app-settings').length) {
  1340. return;
  1341. }
  1342. snapper.close();
  1343. });
  1344. var toggleSnapperOnSize = function() {
  1345. if($(window).width() > 768) {
  1346. snapper.close();
  1347. snapper.disable();
  1348. } else {
  1349. snapper.enable();
  1350. }
  1351. };
  1352. $(window).resize(_.debounce(toggleSnapperOnSize, 250));
  1353. // initial call
  1354. toggleSnapperOnSize();
  1355. // adjust controls bar width
  1356. var adjustControlsWidth = function() {
  1357. if($('#controls').length) {
  1358. var controlsWidth;
  1359. // if there is a scrollbar …
  1360. if($('#app-content').get(0).scrollHeight > $('#app-content').height()) {
  1361. if($(window).width() > 768) {
  1362. controlsWidth = $('#content').width() - $('#app-navigation').width() - getScrollBarWidth();
  1363. if (!$('#app-sidebar').hasClass('hidden') && !$('#app-sidebar').hasClass('disappear')) {
  1364. controlsWidth -= $('#app-sidebar').width();
  1365. }
  1366. } else {
  1367. controlsWidth = $('#content').width() - getScrollBarWidth();
  1368. }
  1369. } else { // if there is none
  1370. if($(window).width() > 768) {
  1371. controlsWidth = $('#content').width() - $('#app-navigation').width();
  1372. if (!$('#app-sidebar').hasClass('hidden') && !$('#app-sidebar').hasClass('disappear')) {
  1373. controlsWidth -= $('#app-sidebar').width();
  1374. }
  1375. } else {
  1376. controlsWidth = $('#content').width();
  1377. }
  1378. }
  1379. $('#controls').css('width', controlsWidth);
  1380. $('#controls').css('min-width', controlsWidth);
  1381. }
  1382. };
  1383. $(window).resize(_.debounce(adjustControlsWidth, 250));
  1384. $('body').delegate('#app-content', 'apprendered appresized', adjustControlsWidth);
  1385. }
  1386. // Update live timestamps every 30 seconds
  1387. setInterval(function() {
  1388. $('.live-relative-timestamp').each(function() {
  1389. $(this).text(OC.Util.relativeModifiedDate(parseInt($(this).attr('data-timestamp'), 10)));
  1390. });
  1391. }, 30 * 1000);
  1392. OC.PasswordConfirmation.init();
  1393. }
  1394. OC.PasswordConfirmation = {
  1395. callback: null,
  1396. init: function() {
  1397. $('.password-confirm-required').on('click', _.bind(this.requirePasswordConfirmation, this));
  1398. },
  1399. requiresPasswordConfirmation: function() {
  1400. var timeSinceLogin = moment.now() - (nc_lastLogin * 1000);
  1401. return timeSinceLogin > 30 * 60 * 1000; // 30 minutes
  1402. },
  1403. /**
  1404. * @param {function} callback
  1405. */
  1406. requirePasswordConfirmation: function(callback) {
  1407. var self = this;
  1408. if (this.requiresPasswordConfirmation()) {
  1409. OC.dialogs.prompt(
  1410. t(
  1411. 'core',
  1412. 'This action requires you to confirm your password'
  1413. ),
  1414. t('core','Authentication required'),
  1415. function (result, password) {
  1416. if (result && password !== '') {
  1417. self._confirmPassword(password);
  1418. }
  1419. },
  1420. true,
  1421. t('core','Password'),
  1422. true
  1423. ).then(function() {
  1424. var $dialog = $('.oc-dialog:visible');
  1425. $dialog.find('.ui-icon').remove();
  1426. var $buttons = $dialog.find('button');
  1427. $buttons.eq(0).text(t('core', 'Cancel'));
  1428. $buttons.eq(1).text(t('core', 'Confirm'));
  1429. });
  1430. }
  1431. this.callback = callback;
  1432. },
  1433. _confirmPassword: function(password) {
  1434. var self = this;
  1435. $.ajax({
  1436. url: OC.generateUrl('/login/confirm'),
  1437. data: {
  1438. password: password
  1439. },
  1440. type: 'POST',
  1441. success: function(response) {
  1442. nc_lastLogin = response.lastLogin;
  1443. if (_.isFunction(self.callback)) {
  1444. self.callback();
  1445. }
  1446. },
  1447. error: function() {
  1448. OC.Notification.showTemporary(t('core', 'Failed to authenticate, try again'));
  1449. }
  1450. });
  1451. }
  1452. };
  1453. $(document).ready(initCore);
  1454. /**
  1455. * Filter Jquery selector by attribute value
  1456. */
  1457. $.fn.filterAttr = function(attr_name, attr_value) {
  1458. return this.filter(function() { return $(this).attr(attr_name) === attr_value; });
  1459. };
  1460. /**
  1461. * Returns a human readable file size
  1462. * @param {number} size Size in bytes
  1463. * @param {boolean} skipSmallSizes return '< 1 kB' for small files
  1464. * @return {string}
  1465. */
  1466. function humanFileSize(size, skipSmallSizes) {
  1467. var humanList = ['B', 'KB', 'MB', 'GB', 'TB'];
  1468. // Calculate Log with base 1024: size = 1024 ** order
  1469. var order = size > 0 ? Math.floor(Math.log(size) / Math.log(1024)) : 0;
  1470. // Stay in range of the byte sizes that are defined
  1471. order = Math.min(humanList.length - 1, order);
  1472. var readableFormat = humanList[order];
  1473. var relativeSize = (size / Math.pow(1024, order)).toFixed(1);
  1474. if(skipSmallSizes === true && order === 0) {
  1475. if(relativeSize !== "0.0"){
  1476. return '< 1 KB';
  1477. } else {
  1478. return '0 KB';
  1479. }
  1480. }
  1481. if(order < 2){
  1482. relativeSize = parseFloat(relativeSize).toFixed(0);
  1483. }
  1484. else if(relativeSize.substr(relativeSize.length-2,2)==='.0'){
  1485. relativeSize=relativeSize.substr(0,relativeSize.length-2);
  1486. }
  1487. return relativeSize + ' ' + readableFormat;
  1488. }
  1489. /**
  1490. * Format an UNIX timestamp to a human understandable format
  1491. * @param {number} timestamp UNIX timestamp
  1492. * @return {string} Human readable format
  1493. */
  1494. function formatDate(timestamp){
  1495. return OC.Util.formatDate(timestamp);
  1496. }
  1497. //
  1498. /**
  1499. * Get the value of a URL parameter
  1500. * @link http://stackoverflow.com/questions/1403888/get-url-parameter-with-jquery
  1501. * @param {string} name URL parameter
  1502. * @return {string}
  1503. */
  1504. function getURLParameter(name) {
  1505. return decodeURIComponent(
  1506. (new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(
  1507. location.search)||[,''])[1].replace(/\+/g, '%20')
  1508. )||'';
  1509. }
  1510. /**
  1511. * Takes an absolute timestamp and return a string with a human-friendly relative date
  1512. * @param {number} timestamp A Unix timestamp
  1513. */
  1514. function relative_modified_date(timestamp) {
  1515. /*
  1516. Were multiplying by 1000 to bring the timestamp back to its original value
  1517. per https://github.com/owncloud/core/pull/10647#discussion_r16790315
  1518. */
  1519. return OC.Util.relativeModifiedDate(timestamp * 1000);
  1520. }
  1521. /**
  1522. * Utility functions
  1523. * @namespace
  1524. */
  1525. OC.Util = {
  1526. // TODO: remove original functions from global namespace
  1527. humanFileSize: humanFileSize,
  1528. /**
  1529. * @param timestamp
  1530. * @param format
  1531. * @returns {string} timestamp formatted as requested
  1532. */
  1533. formatDate: function (timestamp, format) {
  1534. format = format || "LLL";
  1535. return moment(timestamp).format(format);
  1536. },
  1537. /**
  1538. * @param timestamp
  1539. * @returns {string} human readable difference from now
  1540. */
  1541. relativeModifiedDate: function (timestamp) {
  1542. var diff = moment().diff(moment(timestamp));
  1543. if (diff >= 0 && diff < 45000 ) {
  1544. return t('core', 'seconds ago');
  1545. }
  1546. return moment(timestamp).fromNow();
  1547. },
  1548. /**
  1549. * Returns whether the browser supports SVG
  1550. * @deprecated SVG is always supported (since 9.0)
  1551. * @return {boolean} true if the browser supports SVG, false otherwise
  1552. */
  1553. hasSVGSupport: function(){
  1554. return true
  1555. },
  1556. /**
  1557. * If SVG is not supported, replaces the given icon's extension
  1558. * from ".svg" to ".png".
  1559. * If SVG is supported, return the image path as is.
  1560. * @param {string} file image path with svg extension
  1561. * @deprecated SVG is always supported (since 9.0)
  1562. * @return {string} fixed image path with png extension if SVG is not supported
  1563. */
  1564. replaceSVGIcon: function(file) {
  1565. return file;
  1566. },
  1567. /**
  1568. * Replace SVG images in all elements that have the "svg" class set
  1569. * with PNG images.
  1570. *
  1571. * @param $el root element from which to search, defaults to $('body')
  1572. * @deprecated SVG is always supported (since 9.0)
  1573. */
  1574. replaceSVG: function($el) {},
  1575. /**
  1576. * Fix image scaling for IE8, since background-size is not supported.
  1577. *
  1578. * This scales the image to the element's actual size, the URL is
  1579. * taken from the "background-image" CSS attribute.
  1580. *
  1581. * @deprecated IE8 isn't supported since 9.0
  1582. * @param {Object} $el image element
  1583. */
  1584. scaleFixForIE8: function($el) {},
  1585. /**
  1586. * Returns whether this is IE
  1587. *
  1588. * @return {bool} true if this is IE, false otherwise
  1589. */
  1590. isIE: function() {
  1591. return $('html').hasClass('ie');
  1592. },
  1593. /**
  1594. * Returns whether this is IE8
  1595. *
  1596. * @deprecated IE8 isn't supported since 9.0
  1597. * @return {bool} false (IE8 isn't supported anymore)
  1598. */
  1599. isIE8: function() {
  1600. return false;
  1601. },
  1602. /**
  1603. * Returns the width of a generic browser scrollbar
  1604. *
  1605. * @return {int} width of scrollbar
  1606. */
  1607. getScrollBarWidth: function() {
  1608. if (this._scrollBarWidth) {
  1609. return this._scrollBarWidth;
  1610. }
  1611. var inner = document.createElement('p');
  1612. inner.style.width = "100%";
  1613. inner.style.height = "200px";
  1614. var outer = document.createElement('div');
  1615. outer.style.position = "absolute";
  1616. outer.style.top = "0px";
  1617. outer.style.left = "0px";
  1618. outer.style.visibility = "hidden";
  1619. outer.style.width = "200px";
  1620. outer.style.height = "150px";
  1621. outer.style.overflow = "hidden";
  1622. outer.appendChild (inner);
  1623. document.body.appendChild (outer);
  1624. var w1 = inner.offsetWidth;
  1625. outer.style.overflow = 'scroll';
  1626. var w2 = inner.offsetWidth;
  1627. if(w1 === w2) {
  1628. w2 = outer.clientWidth;
  1629. }
  1630. document.body.removeChild (outer);
  1631. this._scrollBarWidth = (w1 - w2);
  1632. return this._scrollBarWidth;
  1633. },
  1634. /**
  1635. * Remove the time component from a given date
  1636. *
  1637. * @param {Date} date date
  1638. * @return {Date} date with stripped time
  1639. */
  1640. stripTime: function(date) {
  1641. // FIXME: likely to break when crossing DST
  1642. // would be better to use a library like momentJS
  1643. return new Date(date.getFullYear(), date.getMonth(), date.getDate());
  1644. },
  1645. _chunkify: function(t) {
  1646. // Adapted from http://my.opera.com/GreyWyvern/blog/show.dml/1671288
  1647. var tz = [], x = 0, y = -1, n = 0, code, c;
  1648. while (x < t.length) {
  1649. c = t.charAt(x);
  1650. // only include the dot in strings
  1651. var m = ((!n && c === '.') || (c >= '0' && c <= '9'));
  1652. if (m !== n) {
  1653. // next chunk
  1654. y++;
  1655. tz[y] = '';
  1656. n = m;
  1657. }
  1658. tz[y] += c;
  1659. x++;
  1660. }
  1661. return tz;
  1662. },
  1663. /**
  1664. * Compare two strings to provide a natural sort
  1665. * @param a first string to compare
  1666. * @param b second string to compare
  1667. * @return -1 if b comes before a, 1 if a comes before b
  1668. * or 0 if the strings are identical
  1669. */
  1670. naturalSortCompare: function(a, b) {
  1671. var x;
  1672. var aa = OC.Util._chunkify(a);
  1673. var bb = OC.Util._chunkify(b);
  1674. for (x = 0; aa[x] && bb[x]; x++) {
  1675. if (aa[x] !== bb[x]) {
  1676. var aNum = Number(aa[x]), bNum = Number(bb[x]);
  1677. // note: == is correct here
  1678. if (aNum == aa[x] && bNum == bb[x]) {
  1679. return aNum - bNum;
  1680. } else {
  1681. // Forcing 'en' locale to match the server-side locale which is
  1682. // always 'en'.
  1683. //
  1684. // Note: This setting isn't supported by all browsers but for the ones
  1685. // that do there will be more consistency between client-server sorting
  1686. return aa[x].localeCompare(bb[x], 'en');
  1687. }
  1688. }
  1689. }
  1690. return aa.length - bb.length;
  1691. },
  1692. /**
  1693. * Calls the callback in a given interval until it returns true
  1694. * @param {function} callback
  1695. * @param {integer} interval in milliseconds
  1696. */
  1697. waitFor: function(callback, interval) {
  1698. var internalCallback = function() {
  1699. if(callback() !== true) {
  1700. setTimeout(internalCallback, interval);
  1701. }
  1702. };
  1703. internalCallback();
  1704. },
  1705. /**
  1706. * Checks if a cookie with the given name is present and is set to the provided value.
  1707. * @param {string} name name of the cookie
  1708. * @param {string} value value of the cookie
  1709. * @return {boolean} true if the cookie with the given name has the given value
  1710. */
  1711. isCookieSetToValue: function(name, value) {
  1712. var cookies = document.cookie.split(';');
  1713. for (var i=0; i < cookies.length; i++) {
  1714. var cookie = cookies[i].split('=');
  1715. if (cookie[0].trim() === name && cookie[1].trim() === value) {
  1716. return true;
  1717. }
  1718. }
  1719. return false;
  1720. }
  1721. };
  1722. /**
  1723. * Utility class for the history API,
  1724. * includes fallback to using the URL hash when
  1725. * the browser doesn't support the history API.
  1726. *
  1727. * @namespace
  1728. */
  1729. OC.Util.History = {
  1730. _handlers: [],
  1731. /**
  1732. * Push the current URL parameters to the history stack
  1733. * and change the visible URL.
  1734. * Note: this includes a workaround for IE8/IE9 that uses
  1735. * the hash part instead of the search part.
  1736. *
  1737. * @param params to append to the URL, can be either a string
  1738. * or a map
  1739. * @param {boolean} [replace=false] whether to replace instead of pushing
  1740. */
  1741. _pushState: function(params, replace) {
  1742. var strParams;
  1743. if (typeof(params) === 'string') {
  1744. strParams = params;
  1745. }
  1746. else {
  1747. strParams = OC.buildQueryString(params);
  1748. }
  1749. if (window.history.pushState) {
  1750. var url = location.pathname + '?' + strParams;
  1751. // Workaround for bug with SVG and window.history.pushState on Firefox < 51
  1752. // https://bugzilla.mozilla.org/show_bug.cgi?id=652991
  1753. var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  1754. if (isFirefox && parseInt(navigator.userAgent.split('/').pop()) < 51) {
  1755. var patterns = document.querySelectorAll('[fill^="url(#"], [stroke^="url(#"], [filter^="url(#invert"]');
  1756. for (var i = 0, ii = patterns.length, pattern; i < ii; i++) {
  1757. pattern = patterns[i];
  1758. pattern.style.fill = pattern.style.fill;
  1759. pattern.style.stroke = pattern.style.stroke;
  1760. pattern.removeAttribute("filter");
  1761. pattern.setAttribute("filter", "url(#invert)");
  1762. }
  1763. }
  1764. if (replace) {
  1765. window.history.replaceState(params, '', url);
  1766. } else {
  1767. window.history.pushState(params, '', url);
  1768. }
  1769. }
  1770. // use URL hash for IE8
  1771. else {
  1772. window.location.hash = '?' + strParams;
  1773. // inhibit next onhashchange that just added itself
  1774. // to the event queue
  1775. this._cancelPop = true;
  1776. }
  1777. },
  1778. /**
  1779. * Push the current URL parameters to the history stack
  1780. * and change the visible URL.
  1781. * Note: this includes a workaround for IE8/IE9 that uses
  1782. * the hash part instead of the search part.
  1783. *
  1784. * @param params to append to the URL, can be either a string
  1785. * or a map
  1786. */
  1787. pushState: function(params) {
  1788. return this._pushState(params, false);
  1789. },
  1790. /**
  1791. * Push the current URL parameters to the history stack
  1792. * and change the visible URL.
  1793. * Note: this includes a workaround for IE8/IE9 that uses
  1794. * the hash part instead of the search part.
  1795. *
  1796. * @param params to append to the URL, can be either a string
  1797. * or a map
  1798. */
  1799. replaceState: function(params) {
  1800. return this._pushState(params, true);
  1801. },
  1802. /**
  1803. * Add a popstate handler
  1804. *
  1805. * @param handler function
  1806. */
  1807. addOnPopStateHandler: function(handler) {
  1808. this._handlers.push(handler);
  1809. },
  1810. /**
  1811. * Parse a query string from the hash part of the URL.
  1812. * (workaround for IE8 / IE9)
  1813. */
  1814. _parseHashQuery: function() {
  1815. var hash = window.location.hash,
  1816. pos = hash.indexOf('?');
  1817. if (pos >= 0) {
  1818. return hash.substr(pos + 1);
  1819. }
  1820. if (hash.length) {
  1821. // remove hash sign
  1822. return hash.substr(1);
  1823. }
  1824. return '';
  1825. },
  1826. _decodeQuery: function(query) {
  1827. return query.replace(/\+/g, ' ');
  1828. },
  1829. /**
  1830. * Parse the query/search part of the URL.
  1831. * Also try and parse it from the URL hash (for IE8)
  1832. *
  1833. * @return map of parameters
  1834. */
  1835. parseUrlQuery: function() {
  1836. var query = this._parseHashQuery(),
  1837. params;
  1838. // try and parse from URL hash first
  1839. if (query) {
  1840. params = OC.parseQueryString(this._decodeQuery(query));
  1841. }
  1842. // else read from query attributes
  1843. params = _.extend(params || {}, OC.parseQueryString(this._decodeQuery(location.search)));
  1844. return params || {};
  1845. },
  1846. _onPopState: function(e) {
  1847. if (this._cancelPop) {
  1848. this._cancelPop = false;
  1849. return;
  1850. }
  1851. var params;
  1852. if (!this._handlers.length) {
  1853. return;
  1854. }
  1855. params = (e && e.state);
  1856. if (_.isString(params)) {
  1857. params = OC.parseQueryString(params);
  1858. } else if (!params) {
  1859. params = this.parseUrlQuery() || {};
  1860. }
  1861. for (var i = 0; i < this._handlers.length; i++) {
  1862. this._handlers[i](params);
  1863. }
  1864. }
  1865. };
  1866. // fallback to hashchange when no history support
  1867. if (window.history.pushState) {
  1868. window.onpopstate = _.bind(OC.Util.History._onPopState, OC.Util.History);
  1869. }
  1870. else {
  1871. $(window).on('hashchange', _.bind(OC.Util.History._onPopState, OC.Util.History));
  1872. }
  1873. /**
  1874. * Get a variable by name
  1875. * @param {string} name
  1876. * @return {*}
  1877. */
  1878. OC.get=function(name) {
  1879. var namespaces = name.split(".");
  1880. var tail = namespaces.pop();
  1881. var context=window;
  1882. for(var i = 0; i < namespaces.length; i++) {
  1883. context = context[namespaces[i]];
  1884. if(!context){
  1885. return false;
  1886. }
  1887. }
  1888. return context[tail];
  1889. };
  1890. /**
  1891. * Set a variable by name
  1892. * @param {string} name
  1893. * @param {*} value
  1894. */
  1895. OC.set=function(name, value) {
  1896. var namespaces = name.split(".");
  1897. var tail = namespaces.pop();
  1898. var context=window;
  1899. for(var i = 0; i < namespaces.length; i++) {
  1900. if(!context[namespaces[i]]){
  1901. context[namespaces[i]]={};
  1902. }
  1903. context = context[namespaces[i]];
  1904. }
  1905. context[tail]=value;
  1906. };
  1907. // fix device width on windows phone
  1908. (function() {
  1909. if ("-ms-user-select" in document.documentElement.style && navigator.userAgent.match(/IEMobile\/10\.0/)) {
  1910. var msViewportStyle = document.createElement("style");
  1911. msViewportStyle.appendChild(
  1912. document.createTextNode("@-ms-viewport{width:auto!important}")
  1913. );
  1914. document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
  1915. }
  1916. })();
  1917. /**
  1918. * Namespace for apps
  1919. * @namespace OCA
  1920. */
  1921. window.OCA = {};
  1922. /**
  1923. * select a range in an input field
  1924. * @link http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area
  1925. * @param {type} start
  1926. * @param {type} end
  1927. */
  1928. jQuery.fn.selectRange = function(start, end) {
  1929. return this.each(function() {
  1930. if (this.setSelectionRange) {
  1931. this.focus();
  1932. this.setSelectionRange(start, end);
  1933. } else if (this.createTextRange) {
  1934. var range = this.createTextRange();
  1935. range.collapse(true);
  1936. range.moveEnd('character', end);
  1937. range.moveStart('character', start);
  1938. range.select();
  1939. }
  1940. });
  1941. };
  1942. /**
  1943. * check if an element exists.
  1944. * allows you to write if ($('#myid').exists()) to increase readability
  1945. * @link http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery
  1946. */
  1947. jQuery.fn.exists = function(){
  1948. return this.length > 0;
  1949. };
  1950. /**
  1951. * @deprecated use OC.Util.getScrollBarWidth() instead
  1952. */
  1953. function getScrollBarWidth() {
  1954. return OC.Util.getScrollBarWidth();
  1955. }
  1956. /**
  1957. * jQuery tipsy shim for the bootstrap tooltip
  1958. */
  1959. jQuery.fn.tipsy = function(argument) {
  1960. console.warn('Deprecation warning: tipsy is deprecated. Use tooltip instead.');
  1961. if(typeof argument === 'object' && argument !== null) {
  1962. // tipsy defaults
  1963. var options = {
  1964. placement: 'bottom',
  1965. delay: { 'show': 0, 'hide': 0},
  1966. trigger: 'hover',
  1967. html: false,
  1968. container: 'body'
  1969. };
  1970. if(argument.gravity) {
  1971. switch(argument.gravity) {
  1972. case 'n':
  1973. case 'nw':
  1974. case 'ne':
  1975. options.placement='bottom';
  1976. break;
  1977. case 's':
  1978. case 'sw':
  1979. case 'se':
  1980. options.placement='top';
  1981. break;
  1982. case 'w':
  1983. options.placement='right';
  1984. break;
  1985. case 'e':
  1986. options.placement='left';
  1987. break;
  1988. }
  1989. }
  1990. if(argument.trigger) {
  1991. options.trigger = argument.trigger;
  1992. }
  1993. if(argument.delayIn) {
  1994. options.delay["show"] = argument.delayIn;
  1995. }
  1996. if(argument.delayOut) {
  1997. options.delay["hide"] = argument.delayOut;
  1998. }
  1999. if(argument.html) {
  2000. options.html = true;
  2001. }
  2002. if(argument.fallback) {
  2003. options.title = argument.fallback;
  2004. }
  2005. // destroy old tooltip in case the title has changed
  2006. jQuery.fn.tooltip.call(this, 'destroy');
  2007. jQuery.fn.tooltip.call(this, options);
  2008. } else {
  2009. this.tooltip(argument);
  2010. jQuery.fn.tooltip.call(this, argument);
  2011. }
  2012. return this;
  2013. }