js.js 58 KB

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