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

1001 lines
36 KiB

10 years ago
12 years ago
13 years ago
13 years ago
13 years ago
  1. /* global escapeHTML */
  2. /**
  3. * @namespace
  4. */
  5. OC.Share = _.extend(OC.Share, {
  6. SHARE_TYPE_USER:0,
  7. SHARE_TYPE_GROUP:1,
  8. SHARE_TYPE_LINK:3,
  9. SHARE_TYPE_EMAIL:4,
  10. SHARE_TYPE_REMOTE:6,
  11. /**
  12. * Regular expression for splitting parts of remote share owners:
  13. * "user@example.com/path/to/owncloud"
  14. * "user@anotherexample.com@example.com/path/to/owncloud
  15. */
  16. _REMOTE_OWNER_REGEXP: new RegExp("^([^@]*)@(([^@]*)@)?([^/]*)([/](.*)?)?$"),
  17. /**
  18. * @deprecated use OC.Share.currentShares instead
  19. */
  20. itemShares:[],
  21. /**
  22. * Full list of all share statuses
  23. */
  24. statuses:{},
  25. /**
  26. * Shares for the currently selected file.
  27. * (for which the dropdown is open)
  28. *
  29. * Key is item type and value is an array or
  30. * shares of the given item type.
  31. */
  32. currentShares: {},
  33. /**
  34. * Whether the share dropdown is opened.
  35. */
  36. droppedDown:false,
  37. /**
  38. * Loads ALL share statuses from server, stores them in
  39. * OC.Share.statuses then calls OC.Share.updateIcons() to update the
  40. * files "Share" icon to "Shared" according to their share status and
  41. * share type.
  42. *
  43. * If a callback is specified, the update step is skipped.
  44. *
  45. * @param itemType item type
  46. * @param fileList file list instance, defaults to OCA.Files.App.fileList
  47. * @param callback function to call after the shares were loaded
  48. */
  49. loadIcons:function(itemType, fileList, callback) {
  50. // Load all share icons
  51. $.get(
  52. OC.filePath('core', 'ajax', 'share.php'),
  53. {
  54. fetch: 'getItemsSharedStatuses',
  55. itemType: itemType
  56. }, function(result) {
  57. if (result && result.status === 'success') {
  58. OC.Share.statuses = {};
  59. $.each(result.data, function(item, data) {
  60. OC.Share.statuses[item] = data;
  61. });
  62. if (_.isFunction(callback)) {
  63. callback(OC.Share.statuses);
  64. } else {
  65. OC.Share.updateIcons(itemType, fileList);
  66. }
  67. }
  68. }
  69. );
  70. },
  71. /**
  72. * Updates the files' "Share" icons according to the known
  73. * sharing states stored in OC.Share.statuses.
  74. * (not reloaded from server)
  75. *
  76. * @param itemType item type
  77. * @param fileList file list instance
  78. * defaults to OCA.Files.App.fileList
  79. */
  80. updateIcons:function(itemType, fileList){
  81. var item;
  82. var $fileList;
  83. var currentDir;
  84. if (!fileList && OCA.Files) {
  85. fileList = OCA.Files.App.fileList;
  86. }
  87. // fileList is usually only defined in the files app
  88. if (fileList) {
  89. $fileList = fileList.$fileList;
  90. currentDir = fileList.getCurrentDirectory();
  91. }
  92. // TODO: iterating over the files might be more efficient
  93. for (item in OC.Share.statuses){
  94. var image = OC.imagePath('core', 'actions/share');
  95. var data = OC.Share.statuses[item];
  96. var hasLink = data.link;
  97. // Links override shared in terms of icon display
  98. if (hasLink) {
  99. image = OC.imagePath('core', 'actions/public');
  100. }
  101. if (itemType !== 'file' && itemType !== 'folder') {
  102. $('a.share[data-item="'+item+'"]').css('background', 'url('+image+') no-repeat center');
  103. } else {
  104. // TODO: ultimately this part should be moved to files_sharing app
  105. var file = $fileList.find('tr[data-id="'+item+'"]');
  106. var shareFolder = OC.imagePath('core', 'filetypes/folder-shared');
  107. var img;
  108. if (file.length > 0) {
  109. this.markFileAsShared(file, true, hasLink);
  110. } else {
  111. var dir = currentDir;
  112. if (dir.length > 1) {
  113. var last = '';
  114. var path = dir;
  115. // Search for possible parent folders that are shared
  116. while (path != last) {
  117. if (path === data.path && !data.link) {
  118. var actions = $fileList.find('.fileactions .action[data-action="Share"]');
  119. var files = $fileList.find('.filename');
  120. var i;
  121. for (i = 0; i < actions.length; i++) {
  122. // TODO: use this.markFileAsShared()
  123. img = $(actions[i]).find('img');
  124. if (img.attr('src') !== OC.imagePath('core', 'actions/public')) {
  125. img.attr('src', image);
  126. $(actions[i]).addClass('permanent');
  127. $(actions[i]).html('<span> '+t('core', 'Shared')+'</span>').prepend(img);
  128. }
  129. }
  130. for(i = 0; i < files.length; i++) {
  131. if ($(files[i]).closest('tr').data('type') === 'dir') {
  132. $(files[i]).find('.thumbnail').css('background-image', 'url('+shareFolder+')');
  133. }
  134. }
  135. }
  136. last = path;
  137. path = OC.Share.dirname(path);
  138. }
  139. }
  140. }
  141. }
  142. }
  143. },
  144. updateIcon:function(itemType, itemSource) {
  145. var shares = false;
  146. var link = false;
  147. var image = OC.imagePath('core', 'actions/share');
  148. $.each(OC.Share.itemShares, function(index) {
  149. if (OC.Share.itemShares[index]) {
  150. if (index == OC.Share.SHARE_TYPE_LINK) {
  151. if (OC.Share.itemShares[index] == true) {
  152. shares = true;
  153. image = OC.imagePath('core', 'actions/public');
  154. link = true;
  155. return;
  156. }
  157. } else if (OC.Share.itemShares[index].length > 0) {
  158. shares = true;
  159. image = OC.imagePath('core', 'actions/share');
  160. }
  161. }
  162. });
  163. if (itemType != 'file' && itemType != 'folder') {
  164. $('a.share[data-item="'+itemSource+'"]').css('background', 'url('+image+') no-repeat center');
  165. } else {
  166. var $tr = $('tr').filterAttr('data-id', String(itemSource));
  167. if ($tr.length > 0) {
  168. // it might happen that multiple lists exist in the DOM
  169. // with the same id
  170. $tr.each(function() {
  171. OC.Share.markFileAsShared($(this), shares, link);
  172. });
  173. }
  174. }
  175. if (shares) {
  176. OC.Share.statuses[itemSource] = OC.Share.statuses[itemSource] || {};
  177. OC.Share.statuses[itemSource]['link'] = link;
  178. } else {
  179. delete OC.Share.statuses[itemSource];
  180. }
  181. },
  182. /**
  183. * Format a remote address
  184. *
  185. * @param {String} remoteAddress full remote share
  186. * @return {String} HTML code to display
  187. */
  188. _formatRemoteShare: function(remoteAddress) {
  189. var parts = this._REMOTE_OWNER_REGEXP.exec(remoteAddress);
  190. if (!parts) {
  191. // display as is, most likely to be a simple owner name
  192. return escapeHTML(remoteAddress);
  193. }
  194. var userName = parts[1];
  195. var userDomain = parts[3];
  196. var server = parts[4];
  197. var dir = parts[6];
  198. var tooltip = userName;
  199. if (userDomain) {
  200. tooltip += '@' + userDomain;
  201. }
  202. if (server) {
  203. if (!userDomain) {
  204. userDomain = '…';
  205. }
  206. tooltip += '@' + server;
  207. }
  208. var html = '<span class="remoteAddress" title="' + escapeHTML(tooltip) + '">';
  209. html += '<span class="username">' + escapeHTML(userName) + '</span>';
  210. if (userDomain) {
  211. html += '<span class="userDomain">@' + escapeHTML(userDomain) + '</span>';
  212. }
  213. html += '</span>';
  214. return html;
  215. },
  216. /**
  217. * Loop over all recipients in the list and format them using
  218. * all kind of fancy magic.
  219. *
  220. * @param {String[]} recipients array of all the recipients
  221. * @return {String[]} modified list of recipients
  222. */
  223. _formatShareList: function(recipients) {
  224. var _parent = this;
  225. return $.map(recipients, function(recipient) {
  226. recipient = _parent._formatRemoteShare(recipient);
  227. return recipient;
  228. });
  229. },
  230. /**
  231. * Marks/unmarks a given file as shared by changing its action icon
  232. * and folder icon.
  233. *
  234. * @param $tr file element to mark as shared
  235. * @param hasShares whether shares are available
  236. * @param hasLink whether link share is available
  237. */
  238. markFileAsShared: function($tr, hasShares, hasLink) {
  239. var action = $tr.find('.fileactions .action[data-action="Share"]');
  240. var type = $tr.data('type');
  241. var img = action.find('img');
  242. var message;
  243. var recipients;
  244. var owner = $tr.attr('data-share-owner');
  245. var shareFolderIcon;
  246. var image = OC.imagePath('core', 'actions/share');
  247. action.removeClass('shared-style');
  248. // update folder icon
  249. if (type === 'dir' && (hasShares || hasLink || owner)) {
  250. if (hasLink) {
  251. shareFolderIcon = OC.imagePath('core', 'filetypes/folder-public');
  252. }
  253. else {
  254. shareFolderIcon = OC.imagePath('core', 'filetypes/folder-shared');
  255. }
  256. $tr.find('.filename .thumbnail').css('background-image', 'url(' + shareFolderIcon + ')');
  257. } else if (type === 'dir') {
  258. shareFolderIcon = OC.imagePath('core', 'filetypes/folder');
  259. $tr.find('.filename .thumbnail').css('background-image', 'url(' + shareFolderIcon + ')');
  260. }
  261. // update share action text / icon
  262. if (hasShares || owner) {
  263. recipients = $tr.attr('data-share-recipients');
  264. action.addClass('shared-style');
  265. message = t('core', 'Shared');
  266. // even if reshared, only show "Shared by"
  267. if (owner) {
  268. message = this._formatRemoteShare(owner);
  269. }
  270. else if (recipients) {
  271. message = t('core', 'Shared with {recipients}', {recipients: this._formatShareList(recipients.split(", ")).join(", ")}, 0, {escape: false});
  272. }
  273. action.html('<span> ' + message + '</span>').prepend(img);
  274. if (owner || recipients) {
  275. action.find('.remoteAddress').tipsy({gravity: 's'});
  276. }
  277. }
  278. else {
  279. action.html('<span></span>').prepend(img);
  280. }
  281. if (hasLink) {
  282. image = OC.imagePath('core', 'actions/public');
  283. }
  284. img.attr('src', image);
  285. },
  286. /**
  287. *
  288. * @param itemType
  289. * @param itemSource
  290. * @param callback - optional. If a callback is given this method works
  291. * asynchronous and the callback will be provided with data when the request
  292. * is done.
  293. * @returns {OC.Share.Types.ShareInfo}
  294. */
  295. loadItem:function(itemType, itemSource, callback) {
  296. var data = '';
  297. var checkReshare = true;
  298. var async = !_.isUndefined(callback);
  299. if (typeof OC.Share.statuses[itemSource] === 'undefined') {
  300. // NOTE: Check does not always work and misses some shares, fix later
  301. var checkShares = true;
  302. } else {
  303. var checkShares = true;
  304. }
  305. $.ajax({type: 'GET', url: OC.filePath('core', 'ajax', 'share.php'), data: { fetch: 'getItem', itemType: itemType, itemSource: itemSource, checkReshare: checkReshare, checkShares: checkShares }, async: async, success: function(result) {
  306. if (result && result.status === 'success') {
  307. data = result.data;
  308. } else {
  309. data = false;
  310. }
  311. if(async) {
  312. callback(data);
  313. }
  314. }});
  315. return data;
  316. },
  317. share:function(itemType, itemSource, shareType, shareWith, permissions, itemSourceName, expirationDate, callback, errorCallback) {
  318. // Add a fallback for old share() calls without expirationDate.
  319. // We should remove this in a later version,
  320. // after the Apps have been updated.
  321. if (typeof callback === 'undefined' &&
  322. typeof expirationDate === 'function') {
  323. callback = expirationDate;
  324. expirationDate = '';
  325. console.warn(
  326. "Call to 'OC.Share.share()' with too few arguments. " +
  327. "'expirationDate' was assumed to be 'callback'. " +
  328. "Please revisit the call and fix the list of arguments."
  329. );
  330. }
  331. return $.post(OC.filePath('core', 'ajax', 'share.php'),
  332. {
  333. action: 'share',
  334. itemType: itemType,
  335. itemSource: itemSource,
  336. shareType: shareType,
  337. shareWith: shareWith,
  338. permissions: permissions,
  339. itemSourceName: itemSourceName,
  340. expirationDate: expirationDate
  341. }, function (result) {
  342. if (result && result.status === 'success') {
  343. if (callback) {
  344. callback(result.data);
  345. }
  346. } else {
  347. if (_.isUndefined(errorCallback)) {
  348. var msg = t('core', 'Error');
  349. if (result.data && result.data.message) {
  350. msg = result.data.message;
  351. }
  352. OC.dialogs.alert(msg, t('core', 'Error while sharing'));
  353. } else {
  354. errorCallback(result);
  355. }
  356. }
  357. }
  358. );
  359. },
  360. unshare:function(itemType, itemSource, shareType, shareWith, callback) {
  361. $.post(OC.filePath('core', 'ajax', 'share.php'), { action: 'unshare', itemType: itemType, itemSource: itemSource, shareType: shareType, shareWith: shareWith }, function(result) {
  362. if (result && result.status === 'success') {
  363. if (callback) {
  364. callback();
  365. }
  366. } else {
  367. OC.dialogs.alert(t('core', 'Error while unsharing'), t('core', 'Error'));
  368. }
  369. });
  370. },
  371. setPermissions:function(itemType, itemSource, shareType, shareWith, permissions) {
  372. $.post(OC.filePath('core', 'ajax', 'share.php'), { action: 'setPermissions', itemType: itemType, itemSource: itemSource, shareType: shareType, shareWith: shareWith, permissions: permissions }, function(result) {
  373. if (!result || result.status !== 'success') {
  374. OC.dialogs.alert(t('core', 'Error while changing permissions'), t('core', 'Error'));
  375. }
  376. });
  377. },
  378. showDropDown:function(itemType, itemSource, appendTo, link, possiblePermissions, filename) {
  379. var configModel = new OC.Share.ShareConfigModel();
  380. var attributes = {itemType: itemType, itemSource: itemSource, possiblePermissions: possiblePermissions};
  381. var itemModel = new OC.Share.ShareItemModel(attributes, {configModel: configModel});
  382. var dialogView = new OC.Share.ShareDialogView({
  383. id: 'dropdown',
  384. model: itemModel,
  385. configModel: configModel,
  386. className: 'drop shareDropDown',
  387. attributes: {
  388. 'data-item-source-name': filename,
  389. 'data-item-type': itemType,
  390. 'data-item-soruce': itemSource
  391. }
  392. });
  393. dialogView.setShowLink(link);
  394. var $dialog = dialogView.render().$el;
  395. $dialog.appendTo(appendTo);
  396. $dialog.slideDown(OC.menuSpeed, function() {
  397. OC.Share.droppedDown = true;
  398. });
  399. itemModel.fetch();
  400. return;
  401. var data = OC.Share.loadItem(itemType, itemSource);
  402. var dropDownEl;
  403. var html = '<div id="dropdown" class="drop shareDropDown" data-item-type="'+itemType+'" data-item-source="'+itemSource+'">';
  404. if (data !== false && data.reshare !== false && data.reshare.uid_owner !== undefined && data.reshare.uid_owner !== OC.currentUser) {
  405. html += '<span class="reshare">';
  406. if (oc_config.enable_avatars === true) {
  407. html += '<div class="avatar"></div> ';
  408. }
  409. if (data.reshare.share_type == OC.Share.SHARE_TYPE_GROUP) {
  410. html += t('core', 'Shared with you and the group {group} by {owner}', {group: data.reshare.share_with, owner: data.reshare.displayname_owner});
  411. } else {
  412. html += t('core', 'Shared with you by {owner}', {owner: data.reshare.displayname_owner});
  413. }
  414. html += '</span><br />';
  415. // reduce possible permissions to what the original share allowed
  416. possiblePermissions = possiblePermissions & data.reshare.permissions;
  417. }
  418. if (possiblePermissions & OC.PERMISSION_SHARE) {
  419. // Determine the Allow Public Upload status.
  420. // Used later on to determine if the
  421. // respective checkbox should be checked or
  422. // not.
  423. var publicUploadEnabled = $('#filestable').data('allow-public-upload');
  424. if (typeof publicUploadEnabled == 'undefined') {
  425. publicUploadEnabled = 'no';
  426. }
  427. var allowPublicUploadStatus = false;
  428. $.each(data.shares, function(key, value) {
  429. if (value.share_type === OC.Share.SHARE_TYPE_LINK) {
  430. allowPublicUploadStatus = (value.permissions & OC.PERMISSION_CREATE) ? true : false;
  431. return true;
  432. }
  433. });
  434. var sharePlaceholder = t('core', 'Share with users or groups …');
  435. if(oc_appconfig.core.remoteShareAllowed) {
  436. sharePlaceholder = t('core', 'Share with users, groups or remote users …');
  437. }
  438. html += '<label for="shareWith" class="hidden-visually">'+t('core', 'Share')+'</label>';
  439. html += '<input id="shareWith" type="text" placeholder="' + sharePlaceholder + '" />';
  440. if(oc_appconfig.core.remoteShareAllowed) {
  441. var federatedCloudSharingDoc = '<a target="_blank" class="icon-info svg shareWithRemoteInfo" href="{docLink}" '
  442. + 'title="' + t('core', 'Share with people on other ownClouds using the syntax username@example.com/owncloud') + '"></a>';
  443. html += federatedCloudSharingDoc.replace('{docLink}', oc_appconfig.core.federatedCloudShareDoc);
  444. }
  445. html += '<span class="shareWithLoading icon-loading-small hidden"></span>';
  446. html += '<ul id="shareWithList">';
  447. html += '</ul>';
  448. var linksAllowed = $('#allowShareWithLink').val() === 'yes';
  449. if (link && linksAllowed) {
  450. html += '<div id="link" class="linkShare">';
  451. html += '<span class="icon-loading-small hidden"></span>';
  452. html += '<input type="checkbox" name="linkCheckbox" id="linkCheckbox" value="1" /><label for="linkCheckbox">'+t('core', 'Share link')+'</label>';
  453. html += '<br />';
  454. var defaultExpireMessage = '';
  455. if ((itemType === 'folder' || itemType === 'file') && oc_appconfig.core.defaultExpireDateEnforced) {
  456. defaultExpireMessage = t('core', 'The public link will expire no later than {days} days after it is created', {'days': oc_appconfig.core.defaultExpireDate}) + '<br/>';
  457. }
  458. html += '<label for="linkText" class="hidden-visually">'+t('core', 'Link')+'</label>';
  459. html += '<input id="linkText" type="text" readonly="readonly" />';
  460. html += '<input type="checkbox" name="showPassword" id="showPassword" value="1" style="display:none;" /><label for="showPassword" style="display:none;">'+t('core', 'Password protect')+'</label>';
  461. html += '<div id="linkPass">';
  462. html += '<label for="linkPassText" class="hidden-visually">'+t('core', 'Password')+'</label>';
  463. html += '<input id="linkPassText" type="password" placeholder="'+t('core', 'Choose a password for the public link')+'" />';
  464. html += '<span class="icon-loading-small hidden"></span>';
  465. html += '</div>';
  466. if (itemType === 'folder' && (possiblePermissions & OC.PERMISSION_CREATE) && publicUploadEnabled === 'yes') {
  467. html += '<div id="allowPublicUploadWrapper" style="display:none;">';
  468. html += '<span class="icon-loading-small hidden"></span>';
  469. html += '<input type="checkbox" value="1" name="allowPublicUpload" id="sharingDialogAllowPublicUpload"' + ((allowPublicUploadStatus) ? 'checked="checked"' : '') + ' />';
  470. html += '<label for="sharingDialogAllowPublicUpload">' + t('core', 'Allow editing') + '</label>';
  471. html += '</div>';
  472. }
  473. html += '</div>';
  474. var mailPublicNotificationEnabled = $('input:hidden[name=mailPublicNotificationEnabled]').val();
  475. if (mailPublicNotificationEnabled === 'yes') {
  476. html += '<form id="emailPrivateLink">';
  477. html += '<input id="email" style="display:none; width:62%;" value="" placeholder="'+t('core', 'Email link to person')+'" type="text" />';
  478. html += '<input id="emailButton" style="display:none;" type="submit" value="'+t('core', 'Send')+'" />';
  479. html += '</form>';
  480. }
  481. }
  482. html += '<div id="expiration">';
  483. html += '<input type="checkbox" name="expirationCheckbox" id="expirationCheckbox" value="1" /><label for="expirationCheckbox">'+t('core', 'Set expiration date')+'</label>';
  484. html += '<label for="expirationDate" class="hidden-visually">'+t('core', 'Expiration')+'</label>';
  485. html += '<input id="expirationDate" type="text" placeholder="'+t('core', 'Expiration date')+'" style="display:none; width:90%;" />';
  486. html += '<em id="defaultExpireMessage">'+defaultExpireMessage+'</em>';
  487. html += '</div>';
  488. dropDownEl = $(html);
  489. dropDownEl = dropDownEl.appendTo(appendTo);
  490. // trigger remote share info tooltip
  491. if(oc_appconfig.core.remoteShareAllowed) {
  492. $('.shareWithRemoteInfo').tipsy({gravity: 'e'});
  493. }
  494. //Get owner avatars
  495. if (oc_config.enable_avatars === true && data !== false && data.reshare !== false && data.reshare.uid_owner !== undefined) {
  496. dropDownEl.find(".avatar").avatar(data.reshare.uid_owner, 32);
  497. }
  498. // Reset item shares
  499. OC.Share.itemShares = [];
  500. OC.Share.currentShares = {};
  501. if (data.shares) {
  502. $.each(data.shares, function(index, share) {
  503. if (share.share_type == OC.Share.SHARE_TYPE_LINK) {
  504. if (itemSource === share.file_source || itemSource === share.item_source) {
  505. OC.Share.showLink(share.token, share.share_with, itemSource);
  506. }
  507. } else {
  508. if (share.collection) {
  509. OC.Share.addShareWith(share.share_type, share.share_with, share.share_with_displayname, share.permissions, possiblePermissions, share.mail_send, share.collection);
  510. } else {
  511. if (share.share_type === OC.Share.SHARE_TYPE_REMOTE) {
  512. OC.Share.addShareWith(share.share_type, share.share_with, share.share_with_displayname, share.permissions, OC.PERMISSION_READ | OC.PERMISSION_UPDATE | OC.PERMISSION_CREATE, share.mail_send, false);
  513. } else {
  514. OC.Share.addShareWith(share.share_type, share.share_with, share.share_with_displayname, share.permissions, possiblePermissions, share.mail_send, false);
  515. }
  516. }
  517. }
  518. if (share.expiration != null) {
  519. OC.Share.showExpirationDate(share.expiration, share.stime);
  520. }
  521. });
  522. }
  523. $('#shareWith').autocomplete({minLength: 2, delay: 750, source: function(search, response) {
  524. var $loading = $('#dropdown .shareWithLoading');
  525. $loading.removeClass('hidden');
  526. $.get(OC.filePath('core', 'ajax', 'share.php'), { fetch: 'getShareWith', search: search.term.trim(), limit: 200, itemShares: OC.Share.itemShares, itemType: itemType }, function(result) {
  527. $loading.addClass('hidden');
  528. if (result.status == 'success' && result.data.length > 0) {
  529. $( "#shareWith" ).autocomplete( "option", "autoFocus", true );
  530. response(result.data);
  531. } else {
  532. response();
  533. }
  534. }).fail(function(){
  535. $('#dropdown').find('.shareWithLoading').addClass('hidden');
  536. OC.Notification.show(t('core', 'An error occured. Please try again'));
  537. window.setTimeout(OC.Notification.hide, 5000);
  538. });
  539. },
  540. focus: function(event, focused) {
  541. event.preventDefault();
  542. },
  543. select: function(event, selected) {
  544. event.stopPropagation();
  545. var $dropDown = $('#dropdown');
  546. var itemType = $dropDown.data('item-type');
  547. var itemSource = $dropDown.data('item-source');
  548. var itemSourceName = $dropDown.data('item-source-name');
  549. var expirationDate = '';
  550. if ( $('#expirationCheckbox').is(':checked') === true ) {
  551. expirationDate = $( "#expirationDate" ).val();
  552. }
  553. var shareType = selected.item.value.shareType;
  554. var shareWith = selected.item.value.shareWith;
  555. $(this).val(shareWith);
  556. // Default permissions are Edit (CRUD) and Share
  557. // Check if these permissions are possible
  558. var permissions = OC.PERMISSION_READ;
  559. if (shareType === OC.Share.SHARE_TYPE_REMOTE) {
  560. permissions = OC.PERMISSION_CREATE | OC.PERMISSION_UPDATE | OC.PERMISSION_READ;
  561. } else {
  562. if (possiblePermissions & OC.PERMISSION_UPDATE) {
  563. permissions = permissions | OC.PERMISSION_UPDATE;
  564. }
  565. if (possiblePermissions & OC.PERMISSION_CREATE) {
  566. permissions = permissions | OC.PERMISSION_CREATE;
  567. }
  568. if (possiblePermissions & OC.PERMISSION_DELETE) {
  569. permissions = permissions | OC.PERMISSION_DELETE;
  570. }
  571. if (oc_appconfig.core.resharingAllowed && (possiblePermissions & OC.PERMISSION_SHARE)) {
  572. permissions = permissions | OC.PERMISSION_SHARE;
  573. }
  574. }
  575. var $input = $(this);
  576. var $loading = $dropDown.find('.shareWithLoading');
  577. $loading.removeClass('hidden');
  578. $input.val(t('core', 'Adding user...'));
  579. $input.prop('disabled', true);
  580. OC.Share.share(itemType, itemSource, shareType, shareWith, permissions, itemSourceName, expirationDate, function() {
  581. $input.prop('disabled', false);
  582. $loading.addClass('hidden');
  583. var posPermissions = possiblePermissions;
  584. if (shareType === OC.Share.SHARE_TYPE_REMOTE) {
  585. posPermissions = permissions;
  586. }
  587. OC.Share.addShareWith(shareType, shareWith, selected.item.label, permissions, posPermissions);
  588. $('#shareWith').val('');
  589. $('#dropdown').trigger(new $.Event('sharesChanged', {shares: OC.Share.currentShares}));
  590. OC.Share.updateIcon(itemType, itemSource);
  591. });
  592. return false;
  593. }
  594. })
  595. // customize internal _renderItem function to display groups and users differently
  596. .data("ui-autocomplete")._renderItem = function( ul, item ) {
  597. var insert = $( "<a>" );
  598. var text = item.label;
  599. if (item.value.shareType === OC.Share.SHARE_TYPE_GROUP) {
  600. text = text + ' ('+t('core', 'group')+')';
  601. } else if (item.value.shareType === OC.Share.SHARE_TYPE_REMOTE) {
  602. text = text + ' ('+t('core', 'remote')+')';
  603. }
  604. insert.text( text );
  605. if(item.value.shareType === OC.Share.SHARE_TYPE_GROUP) {
  606. insert = insert.wrapInner('<strong></strong>');
  607. }
  608. return $( "<li>" )
  609. .addClass((item.value.shareType === OC.Share.SHARE_TYPE_GROUP)?'group':'user')
  610. .append( insert )
  611. .appendTo( ul );
  612. };
  613. if (link && linksAllowed && $('#email').length != 0) {
  614. $('#email').autocomplete({
  615. minLength: 1,
  616. source: function (search, response) {
  617. $.get(OC.filePath('core', 'ajax', 'share.php'), { fetch: 'getShareWithEmail', search: search.term }, function(result) {
  618. if (result.status == 'success' && result.data.length > 0) {
  619. response(result.data);
  620. }
  621. });
  622. },
  623. select: function( event, item ) {
  624. $('#email').val(item.item.email);
  625. return false;
  626. }
  627. })
  628. .data("ui-autocomplete")._renderItem = function( ul, item ) {
  629. return $('<li>')
  630. .append('<a>' + escapeHTML(item.displayname) + "<br>" + escapeHTML(item.email) + '</a>' )
  631. .appendTo( ul );
  632. };
  633. }
  634. } else {
  635. html += '<input id="shareWith" type="text" placeholder="'+t('core', 'Resharing is not allowed')+'" style="width:90%;" disabled="disabled"/>';
  636. html += '</div>';
  637. dropDownEl = $(html);
  638. dropDownEl.appendTo(appendTo);
  639. }
  640. dropDownEl.attr('data-item-source-name', filename);
  641. $('#dropdown').slideDown(OC.menuSpeed, function() {
  642. OC.Share.droppedDown = true;
  643. });
  644. if ($('html').hasClass('lte9')){
  645. $('#dropdown input[placeholder]').placeholder();
  646. }
  647. $('#shareWith').focus();
  648. },
  649. hideDropDown:function(callback) {
  650. OC.Share.currentShares = null;
  651. $('#dropdown').slideUp(OC.menuSpeed, function() {
  652. OC.Share.droppedDown = false;
  653. $('#dropdown').remove();
  654. if (typeof FileActions !== 'undefined') {
  655. $('tr').removeClass('mouseOver');
  656. }
  657. if (callback) {
  658. callback.call();
  659. }
  660. });
  661. },
  662. showLink:function(token, password, itemSource) {
  663. OC.Share.itemShares[OC.Share.SHARE_TYPE_LINK] = true;
  664. $('#linkCheckbox').attr('checked', true);
  665. //check itemType
  666. var linkSharetype=$('#dropdown').data('item-type');
  667. if (! token) {
  668. //fallback to pre token link
  669. var filename = $('tr').filterAttr('data-id', String(itemSource)).data('file');
  670. var type = $('tr').filterAttr('data-id', String(itemSource)).data('type');
  671. if ($('#dir').val() == '/') {
  672. var file = $('#dir').val() + filename;
  673. } else {
  674. var file = $('#dir').val() + '/' + filename;
  675. }
  676. file = '/'+OC.currentUser+'/files'+file;
  677. // TODO: use oc webroot ?
  678. var link = parent.location.protocol+'//'+location.host+OC.linkTo('', 'public.php')+'?service=files&'+type+'='+encodeURIComponent(file);
  679. } else {
  680. //TODO add path param when showing a link to file in a subfolder of a public link share
  681. var service='';
  682. if(linkSharetype === 'folder' || linkSharetype === 'file'){
  683. service='files';
  684. }else{
  685. service=linkSharetype;
  686. }
  687. // TODO: use oc webroot ?
  688. if (service !== 'files') {
  689. var link = parent.location.protocol+'//'+location.host+OC.linkTo('', 'public.php')+'?service='+service+'&t='+token;
  690. } else {
  691. var link = parent.location.protocol+'//'+location.host+OC.generateUrl('/s/')+token;
  692. }
  693. }
  694. $('#linkText').val(link);
  695. $('#linkText').slideDown(OC.menuSpeed);
  696. $('#linkText').css('display','block');
  697. if (oc_appconfig.core.enforcePasswordForPublicLink === false || password === null) {
  698. $('#showPassword').show();
  699. $('#showPassword+label').show();
  700. }
  701. if (password != null) {
  702. $('#linkPass').slideDown(OC.menuSpeed);
  703. $('#showPassword').attr('checked', true);
  704. $('#linkPassText').attr('placeholder', '**********');
  705. }
  706. $('#expiration').show();
  707. $('#emailPrivateLink #email').show();
  708. $('#emailPrivateLink #emailButton').show();
  709. $('#allowPublicUploadWrapper').show();
  710. },
  711. hideLink:function() {
  712. $('#linkText').slideUp(OC.menuSpeed);
  713. $('#defaultExpireMessage').hide();
  714. $('#showPassword').hide();
  715. $('#showPassword+label').hide();
  716. $('#linkPass').slideUp(OC.menuSpeed);
  717. $('#emailPrivateLink #email').hide();
  718. $('#emailPrivateLink #emailButton').hide();
  719. $('#allowPublicUploadWrapper').hide();
  720. },
  721. dirname:function(path) {
  722. return path.replace(/\\/g,'/').replace(/\/[^\/]*$/, '');
  723. },
  724. /**
  725. * Parses a string to an valid integer (unix timestamp)
  726. * @param time
  727. * @returns {*}
  728. * @internal Only used to work around a bug in the backend
  729. */
  730. _parseTime: function(time) {
  731. if (_.isString(time)) {
  732. // skip empty strings and hex values
  733. if (time === '' || (time.length > 1 && time[0] === '0' && time[1] === 'x')) {
  734. return null;
  735. }
  736. time = parseInt(time, 10);
  737. if(isNaN(time)) {
  738. time = null;
  739. }
  740. }
  741. return time;
  742. },
  743. /**
  744. * Displays the expiration date field
  745. *
  746. * @param {Date} date current expiration date
  747. * @param {int} [shareTime] share timestamp in seconds, defaults to now
  748. */
  749. showExpirationDate:function(date, shareTime) {
  750. var now = new Date();
  751. // min date should always be the next day
  752. var minDate = new Date();
  753. minDate.setDate(minDate.getDate()+1);
  754. var datePickerOptions = {
  755. minDate: minDate,
  756. maxDate: null
  757. };
  758. // TODO: hack: backend returns string instead of integer
  759. shareTime = OC.Share._parseTime(shareTime);
  760. if (_.isNumber(shareTime)) {
  761. shareTime = new Date(shareTime * 1000);
  762. }
  763. if (!shareTime) {
  764. shareTime = now;
  765. }
  766. $('#expirationCheckbox').attr('checked', true);
  767. $('#expirationDate').val(date);
  768. $('#expirationDate').slideDown(OC.menuSpeed);
  769. $('#expirationDate').css('display','block');
  770. $('#expirationDate').datepicker({
  771. dateFormat : 'dd-mm-yy'
  772. });
  773. if (oc_appconfig.core.defaultExpireDateEnforced) {
  774. $('#expirationCheckbox').attr('disabled', true);
  775. shareTime = OC.Util.stripTime(shareTime).getTime();
  776. // max date is share date + X days
  777. datePickerOptions.maxDate = new Date(shareTime + oc_appconfig.core.defaultExpireDate * 24 * 3600 * 1000);
  778. }
  779. if(oc_appconfig.core.defaultExpireDateEnabled) {
  780. $('#defaultExpireMessage').slideDown(OC.menuSpeed);
  781. }
  782. $.datepicker.setDefaults(datePickerOptions);
  783. },
  784. /**
  785. * Get the default Expire date
  786. *
  787. * @return {String} The expire date
  788. */
  789. getDefaultExpirationDate:function() {
  790. var expireDateString = '';
  791. if (oc_appconfig.core.defaultExpireDateEnabled) {
  792. var date = new Date().getTime();
  793. var expireAfterMs = oc_appconfig.core.defaultExpireDate * 24 * 60 * 60 * 1000;
  794. var expireDate = new Date(date + expireAfterMs);
  795. var month = expireDate.getMonth() + 1;
  796. var year = expireDate.getFullYear();
  797. var day = expireDate.getDate();
  798. expireDateString = year + "-" + month + '-' + day + ' 00:00:00';
  799. }
  800. return expireDateString;
  801. }
  802. });
  803. $(document).ready(function() {
  804. if(typeof monthNames != 'undefined'){
  805. // min date should always be the next day
  806. var minDate = new Date();
  807. minDate.setDate(minDate.getDate()+1);
  808. $.datepicker.setDefaults({
  809. monthNames: monthNames,
  810. monthNamesShort: monthNamesShort,
  811. dayNames: dayNames,
  812. dayNamesMin: dayNamesMin,
  813. dayNamesShort: dayNamesShort,
  814. firstDay: firstDay,
  815. minDate : minDate
  816. });
  817. }
  818. $(this).click(function(event) {
  819. var target = $(event.target);
  820. var isMatched = !target.is('.drop, .ui-datepicker-next, .ui-datepicker-prev, .ui-icon')
  821. && !target.closest('#ui-datepicker-div').length && !target.closest('.ui-autocomplete').length;
  822. if (OC.Share.droppedDown && isMatched && $('#dropdown').has(event.target).length === 0) {
  823. OC.Share.hideDropDown();
  824. }
  825. });
  826. $(document).on('click', '#dropdown .showCruds', function() {
  827. $(this).closest('li').find('.cruds').toggle();
  828. return false;
  829. });
  830. $(document).on('change', '#dropdown .permissions', function() {
  831. var li = $(this).closest('li');
  832. if ($(this).attr('name') == 'edit') {
  833. var checkboxes = $('.permissions', li);
  834. var checked = $(this).is(':checked');
  835. // Check/uncheck Create, Update, and Delete checkboxes if Edit is checked/unck
  836. $(checkboxes).filter('input[name="create"]').attr('checked', checked);
  837. $(checkboxes).filter('input[name="update"]').attr('checked', checked);
  838. $(checkboxes).filter('input[name="delete"]').attr('checked', checked);
  839. } else {
  840. var checkboxes = $('.permissions', li);
  841. // Uncheck Edit if Create, Update, and Delete are not checked
  842. if (!$(this).is(':checked')
  843. && !$(checkboxes).filter('input[name="create"]').is(':checked')
  844. && !$(checkboxes).filter('input[name="update"]').is(':checked')
  845. && !$(checkboxes).filter('input[name="delete"]').is(':checked'))
  846. {
  847. $(checkboxes).filter('input[name="edit"]').attr('checked', false);
  848. // Check Edit if Create, Update, or Delete is checked
  849. } else if (($(this).attr('name') == 'create'
  850. || $(this).attr('name') == 'update'
  851. || $(this).attr('name') == 'delete'))
  852. {
  853. $(checkboxes).filter('input[name="edit"]').attr('checked', true);
  854. }
  855. }
  856. var permissions = OC.PERMISSION_READ;
  857. $(checkboxes).filter(':not(input[name="edit"])').filter(':checked').each(function(index, checkbox) {
  858. permissions |= $(checkbox).data('permissions');
  859. });
  860. OC.Share.setPermissions($('#dropdown').data('item-type'),
  861. $('#dropdown').data('item-source'),
  862. li.data('share-type'),
  863. li.attr('data-share-with'),
  864. permissions);
  865. });
  866. $(document).on('click', '#dropdown #expirationCheckbox', function() {
  867. if (this.checked) {
  868. OC.Share.showExpirationDate('');
  869. } else {
  870. var itemType = $('#dropdown').data('item-type');
  871. var itemSource = $('#dropdown').data('item-source');
  872. $.post(OC.filePath('core', 'ajax', 'share.php'), { action: 'setExpirationDate', itemType: itemType, itemSource: itemSource, date: '' }, function(result) {
  873. if (!result || result.status !== 'success') {
  874. OC.dialogs.alert(t('core', 'Error unsetting expiration date'), t('core', 'Error'));
  875. }
  876. $('#expirationDate').slideUp(OC.menuSpeed);
  877. if (oc_appconfig.core.defaultExpireDateEnforced === false) {
  878. $('#defaultExpireMessage').slideDown(OC.menuSpeed);
  879. }
  880. });
  881. }
  882. });
  883. $(document).on('change', '#dropdown #expirationDate', function() {
  884. var itemType = $('#dropdown').data('item-type');
  885. var itemSource = $('#dropdown').data('item-source');
  886. $(this).tipsy('hide');
  887. $(this).removeClass('error');
  888. $.post(OC.filePath('core', 'ajax', 'share.php'), { action: 'setExpirationDate', itemType: itemType, itemSource: itemSource, date: $(this).val() }, function(result) {
  889. if (!result || result.status !== 'success') {
  890. var expirationDateField = $('#dropdown #expirationDate');
  891. if (!result.data.message) {
  892. expirationDateField.attr('original-title', t('core', 'Error setting expiration date'));
  893. } else {
  894. expirationDateField.attr('original-title', result.data.message);
  895. }
  896. expirationDateField.tipsy({gravity: 'n'});
  897. expirationDateField.tipsy('show');
  898. expirationDateField.addClass('error');
  899. } else {
  900. if (oc_appconfig.core.defaultExpireDateEnforced === 'no') {
  901. $('#defaultExpireMessage').slideUp(OC.menuSpeed);
  902. }
  903. }
  904. });
  905. });
  906. $(document).on('submit', '#dropdown #emailPrivateLink', function(event) {
  907. event.preventDefault();
  908. var link = $('#linkText').val();
  909. var itemType = $('#dropdown').data('item-type');
  910. var itemSource = $('#dropdown').data('item-source');
  911. var file = $('tr').filterAttr('data-id', String(itemSource)).data('file');
  912. var email = $('#email').val();
  913. var expirationDate = '';
  914. if ( $('#expirationCheckbox').is(':checked') === true ) {
  915. expirationDate = $( "#expirationDate" ).val();
  916. }
  917. if (email != '') {
  918. $('#email').prop('disabled', true);
  919. $('#email').val(t('core', 'Sending ...'));
  920. $('#emailButton').prop('disabled', true);
  921. $.post(OC.filePath('core', 'ajax', 'share.php'), { action: 'email', toaddress: email, link: link, itemType: itemType, itemSource: itemSource, file: file, expiration: expirationDate},
  922. function(result) {
  923. $('#email').prop('disabled', false);
  924. $('#emailButton').prop('disabled', false);
  925. if (result && result.status == 'success') {
  926. $('#email').css('font-weight', 'bold').val(t('core','Email sent'));
  927. setTimeout(function() {
  928. $('#email').css('font-weight', 'normal').val('');
  929. }, 2000);
  930. } else {
  931. OC.dialogs.alert(result.data.message, t('core', 'Error while sharing'));
  932. }
  933. });
  934. }
  935. });
  936. $(document).on('click', '#dropdown input[name=mailNotification]', function() {
  937. var $li = $(this).closest('li');
  938. var itemType = $('#dropdown').data('item-type');
  939. var itemSource = $('#dropdown').data('item-source');
  940. var action = '';
  941. if (this.checked) {
  942. action = 'informRecipients';
  943. } else {
  944. action = 'informRecipientsDisabled';
  945. }
  946. var shareType = $li.data('share-type');
  947. var shareWith = $li.attr('data-share-with');
  948. $.post(OC.filePath('core', 'ajax', 'share.php'), {action: action, recipient: shareWith, shareType: shareType, itemSource: itemSource, itemType: itemType}, function(result) {
  949. if (result.status !== 'success') {
  950. OC.dialogs.alert(t('core', result.data.message), t('core', 'Warning'));
  951. }
  952. });
  953. });
  954. });