Failed Conditions
Pull Request — master (#56)
by Sander
02:03
created

js/share.js (2 issues)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
/* global Ownnote, escapeHTML */
2
window.Ownnote = {};
3
window.Ownnote.Share = {};
4
5
(function ($, Ownnote) {
6
  "use strict";
7
8
  /**
9
   * @typedef {Object} Ownnote.Share.Types.ShareInfo
10
   * @property {Number} share_type
11
   * @property {Number} permissions
12
   * @property {Number} file_source optional
13
   * @property {Number} item_source
14
   * @property {String} token
15
   * @property {String} share_with
16
   * @property {String} share_with_displayname
17
   * @property {String} mail_send
18
   * @property {String} displayname_file_owner
19
   * @property {String} displayname_owner
20
   * @property {String} uid_owner
21
   * @property {String} uid_file_owner
22
   * @property {String} expiration optional
23
   * @property {Number} stime
24
   */
25
26
      // copied and stripped out from the old core
27
  var Share = {
28
        SHARE_TYPE_USER: 0,
29
        SHARE_TYPE_GROUP: 1,
30
        SHARE_TYPE_LINK: 3,
31
        SHARE_TYPE_EMAIL: 4,
32
        SHARE_TYPE_REMOTE: 6,
33
34
        itemShares: [],
35
36
        /**
37
         * Shares for the currently selected file.
38
         * (for which the dropdown is open)
39
         *
40
         * Key is item type and value is an array or
41
         * shares of the given item type.
42
         */
43
        currentShares: {},
44
45
        /**
46
         * Whether the share dropdown is opened.
47
         */
48
        droppedDown: false,
49
50
        /**
51
         *
52
         * @param path {String} path to the file/folder which should be shared
53
         * @param shareType {Number} 0 = user; 1 = group; 3 = public link; 6 = federated cloud
54
         *     share
55
         * @param shareWith {String} user / group id with which the file should be shared
56
         * @param publicUpload {Boolean} allow public upload to a public shared folder
57
         * @param password {String} password to protect public link Share with
58
         * @param permissions {Number} 1 = read; 2 = update; 4 = create; 8 = delete; 16 = share; 31
59
         *     = all (default: 31, for public shares: 1)
60
         * @param callback {Function} method to call back after a successful share creation
61
         * @param errorCallback {Function} method to call back after a failed share creation
62
         *
63
         * @returns {*}
64
         */
65
        share: function (noteid, shareType, shareWith, publicUpload, password, permissions, callback, errorCallback) {
66
67
          return $.ajax({
68
            url: OC.generateUrl('/apps/nextnote/') + 'api/v2.0/sharing/shares',
69
            type: 'POST',
70
            data: {
71
              noteid: noteid,
72
              shareType: shareType,
73
              shareWith: shareWith,
74
              publicUpload: publicUpload,
75
              password: password,
76
              permissions: permissions
77
            },
78
            dataType: 'json'
79
          }).done(function (result) {
80
            if (result) {
81
              var data = {
82
                id: noteid
83
              };
84
              if (callback) {
85
                callback(data);
86
              }
87
            }
88
          }).fail(function (xhr) {
89
            var result = xhr.responseJSON;
90
            if (_.isFunction(errorCallback)) {
91
              errorCallback(result);
92
            } else {
93
              var msg = t('core', 'Error');
94
              if (result.ocs && result.ocs.meta.message) {
95
                msg = result.ocs.meta.message;
96
              }
97
              OC.dialogs.alert(msg, t('core', 'Error while sharing'));
98
            }
99
          });
100
        },
101
        /**
102
         *
103
         * @param {Number} shareId
104
         * @param {Function} callback
105
         */
106
        unshare: function (shareId, shareType, shareWith, callback) {
107
          var url = OC.generateUrl('/apps/nextnote/') + 'api/v2.0/sharing/shares/' + shareId;
108
          url += '?' + $.param({
109
                'shareType': shareType,
110
                'shareWith': shareWith
111
              });
112
          $.ajax({
113
            url: url,
114
            type: 'DELETE'
115
          }).done(function () {
116
            if (callback) {
117
              callback();
118
            }
119
          }).fail(function () {
120
            OC.dialogs.alert(t('core', 'Error while unsharing'), t('core', 'Error'));
121
122
          });
123
        },
124
        /**
125
         *
126
         * @param {Number} shareId
127
         * @param {Number} permissions
128
         */
129
        setPermissions: function (shareId, shareType, shareWith, permissions) {
130
          var url = OC.generateUrl('/apps/nextnote/') + 'api/v2.0/sharing/shares/' + shareId + '/permissions';
131
          $.ajax({
132
            url: url,
133
            type: 'PUT',
134
            data: {
135
              shareType: shareType,
136
              shareWith: shareWith,
137
              permissions: permissions
138
            }
139
          }).fail(function () {
140
            OC.dialogs.alert(t('core', 'Error while changing permissions'),
141
                t('core', 'Error'));
142
          });
143
        },
144
        /**
145
         *
146
         * @param {String} itemType
147
         * @param {String} path
148
         * @param {String} appendTo
149
         * @param {String} link
150
         * @param {Number} possiblePermissions
151
         * @param {String} filename
152
         */
153
        showDropDown: function (itemType, path, appendTo, link, possiblePermissions, filename) {
154
          // This is a sync AJAX request on the main thread...
155
          var data = this._loadShares(path);
156
          var dropDownEl;
157
          var self = this;
158
          var html = '<div id="dropdown" class="drop shareDropDown" data-item-type="' + itemType +
159
              '" data-item-source="' + path + '">';
160
          if (data !== false && data[0] && !_.isUndefined(data[0].uid_owner) &&
161
              data[0].uid_owner !== OC.currentUser
162
          ) {
163
            html += '<span class="reshare">';
164
            if (oc_config.enable_avatars === true) {
165
              html += '<div class="avatar"></div>';
166
            }
167
168
            if (data[0].share_type == this.SHARE_TYPE_GROUP) {
169
              html += t('core', 'Shared with you and the group {group} by {owner}', {
170
                group: data[0].share_with,
171
                owner: data[0].displayname_owner
172
              });
173
            } else {
174
              html += t('core', 'Shared with you by {owner}',
175
                  {owner: data[0].displayname_owner});
176
            }
177
            html += '</span><br />';
178
            // reduce possible permissions to what the original share allowed
179
            possiblePermissions = possiblePermissions & data[0].permissions;
180
          }
181
182
          if (possiblePermissions & OC.PERMISSION_SHARE) {
183
            // Determine the Allow Public Upload status.
184
            // Used later on to determine if the
185
            // respective checkbox should be checked or
186
            // not.
187
            var publicUploadEnabled = $('#Ownnote').data('allow-public-upload');
188
            if (typeof publicUploadEnabled == 'undefined') {
189
              publicUploadEnabled = 'no';
190
            }
191
            var allowPublicUploadStatus = false;
192
193
            $.each(data, function (key, value) {
194
              if (value.share_type === self.SHARE_TYPE_LINK) {
195
                allowPublicUploadStatus =
196
                    (value.permissions & OC.PERMISSION_CREATE) ? true : false;
197
                return true;
198
              }
199
            });
200
201
            var sharePlaceholder = t('core', 'Share with users or groups …');
202
            if (oc_appconfig.core.remoteShareAllowed) {
203
              sharePlaceholder = t('core', 'Share with users, groups or remote users …');
204
            }
205
206
            html += '<label for="shareWith" class="hidden-visually">' + t('core', 'Share') +
207
                '</label>';
208
            html +=
209
                '<input id="shareWith" type="text" placeholder="' + sharePlaceholder + '" />';
210
            if (oc_appconfig.core.remoteShareAllowed) {
211
              var federatedCloudSharingDoc =
212
                  '<a target="_blank" class="icon-info svg shareWithRemoteInfo" ' +
213
                  'href="{docLink}" title="' + t('core',
214
                      'Share with people on other ownCloud/Nextcloud using the syntax [email protected]') +
215
                  '"></a>';
216
              html += federatedCloudSharingDoc.replace('{docLink}',
217
                  oc_appconfig.core.federatedCloudShareDoc);
218
            }
219
            html += '<span class="shareWithLoading icon-loading-small hidden"></span>';
220
            html += '<ul id="shareWithList">';
221
            html += '</ul>';
222
            var linksAllowed = $('#allowShareWithLink').val() === 'yes';
223
224
            if (link && linksAllowed) {
225
              html += '<div id="link" class="linkShare">';
226
              html += '<span class="icon-loading-small hidden"></span>';
227
              html +=
228
                  '<input type="checkbox" class="checkbox checkbox--right" ' +
229
                  'name="linkCheckbox" id="linkCheckbox" value="1" />' +
230
                  '<label for="linkCheckbox">' + t('core', 'Share link') + '</label>';
231
              html += '<br />';
232
233
              var defaultExpireMessage = '';
234
              if ((itemType === 'folder' || itemType === 'file') &&
235
                  oc_appconfig.core.defaultExpireDateEnforced) {
236
                defaultExpireMessage =
237
                    t('core',
238
                        'The public link will expire no later than {days} days after it is created',
239
                        {'days': oc_appconfig.core.defaultExpireDate}) + '<br/>';
240
              }
241
242
              html += '<label for="linkText" class="hidden-visually">' + t('core', 'Link') +
243
                  '</label>';
244
              html += '<input id="linkText" type="text" readonly="readonly" />';
245
              html +=
246
                  '<input type="checkbox" class="checkbox checkbox--right" ' +
247
                  'name="showPassword" id="showPassword" value="1" />' +
248
                  '<label for="showPassword" style="display:none;">' +
249
                  t('core', 'Password protect') + '</label>';
250
              html += '<div id="linkPass">';
251
              html += '<label for="linkPassText" class="hidden-visually">' +
252
                  t('core', 'Password') + '</label>';
253
              html += '<input id="linkPassText" type="password" placeholder="' +
254
                  t('core', 'Choose a password for the public link') + '" />';
255
              html += '<span class="icon-loading-small hidden"></span>';
256
              html += '</div>';
257
258
              if (itemType === 'folder' && (possiblePermissions & OC.PERMISSION_CREATE) &&
259
                  publicUploadEnabled === 'yes') {
260
                html += '<div id="allowPublicUploadWrapper" style="display:none;">';
261
                html += '<span class="icon-loading-small hidden"></span>';
262
                html +=
263
                    '<input type="checkbox" class="checkbox checkbox--right" value="1" name="allowPublicUpload" id="sharingDialogAllowPublicUpload"' +
264
                    ((allowPublicUploadStatus) ? 'checked="checked"' : '') + ' />';
265
                html += '<label for="sharingDialogAllowPublicUpload">' +
266
                    t('core', 'Allow editing') + '</label>';
267
                html += '</div>';
268
              }
269
270
              var mailPublicNotificationEnabled = $('input:hidden[name=mailPublicNotificationEnabled]').val();
271
              if (mailPublicNotificationEnabled === 'yes') {
272
                html += '<form id="emailPrivateLink">';
273
                html +=
274
                    '<input id="email" style="display:none; width:62%;" value="" placeholder="' +
275
                    t('core', 'Email link to person') + '" type="text" />';
276
                html +=
277
                    '<input id="emailButton" style="display:none;" type="submit" value="' +
278
                    t('core', 'Send') + '" />';
279
                html += '</form>';
280
              }
281
            }
282
283
            html += '<div id="expiration" >';
284
            html +=
285
                '<input type="checkbox" class="checkbox checkbox--right" ' +
286
                'name="expirationCheckbox" id="expirationCheckbox" value="1" />' +
287
                '<label for="expirationCheckbox">' +
288
                t('core', 'Set expiration date') + '</label>';
289
            html += '<label for="expirationDate" class="hidden-visually">' +
290
                t('core', 'Expiration') + '</label>';
291
            html += '<input id="expirationDate" type="text" placeholder="' +
292
                t('core', 'Expiration date') + '" style="display:none; width:90%;" />';
293
            if(defaultExpireMessage) {
0 ignored issues
show
The variable defaultExpireMessage seems to be used out of scope.

This error can usually be fixed by declaring the variable in the scope where it is used:

function someFunction() {
    (function() {
        var i = 0;
    })();

    // i is not defined.
    alert(i);
}

// This can be fixed by moving the var statement to the outer scope.

function someFunction() {
    var i;
    (function() {
        i = 1;
    })();

    alert(i);
};
Loading history...
294
              html += '<em id="defaultExpireMessage">' + defaultExpireMessage + '</em>';
0 ignored issues
show
The variable defaultExpireMessage seems to be used out of scope.

This error can usually be fixed by declaring the variable in the scope where it is used:

function someFunction() {
    (function() {
        var i = 0;
    })();

    // i is not defined.
    alert(i);
}

// This can be fixed by moving the var statement to the outer scope.

function someFunction() {
    var i;
    (function() {
        i = 1;
    })();

    alert(i);
};
Loading history...
295
            }
296
297
            html += '</div>';
298
            dropDownEl = $(html);
299
            dropDownEl = dropDownEl.appendTo(appendTo);
300
301
302
            // trigger remote share info tooltip
303
            if (oc_appconfig.core.remoteShareAllowed) {
304
              $('.shareWithRemoteInfo').tooltip({placement: 'top'});
305
            }
306
307
            //Get owner avatars
308
            if (oc_config.enable_avatars === true && data !== false && data[0] !== false &&
309
                !_.isUndefined(data[0]) && !_.isUndefined(data[0].uid_owner)) {
310
              dropDownEl.find(".avatar").avatar(data[0].uid, 32);
311
            }
312
313
            // Reset item shares
314
            this.itemShares = [];
315
            this.currentShares = {};
316
            if (data) {
317
              $.each(data, function (index, share) {
318
                if (share.share_type === self.SHARE_TYPE_LINK) {
319
                  self.showLink(share.id, share.token, share.share_with);
320
                } else {
321
                  if (share.share_with !== OC.currentUser || share.share_type !== self.SHARE_TYPE_USER) {
322
                    if (share.share_type === self.SHARE_TYPE_REMOTE) {
323
                      self._addShareWith(share.id,
324
                          share.share_type,
325
                          share.share_with,
326
                          share.share_with_displayname,
327
                          share.permissions,
328
                          OC.PERMISSION_READ | OC.PERMISSION_UPDATE |
329
                          OC.PERMISSION_CREATE,
330
                          share.mail_send,
331
                          share.item_source,
332
                          false);
333
                    } else {
334
                      self._addShareWith(share.id,
335
                          share.share_type,
336
                          share.share_with,
337
                          share.share_with_displayname,
338
                          share.permissions,
339
                          possiblePermissions,
340
                          share.mail_send,
341
                          share.item_source,
342
                          false);
343
                    }
344
                  }
345
                }
346
                if (share.expiration != null) {
347
                  var expireDate = moment(share.expiration, 'YYYY-MM-DD').format(
348
                      'DD-MM-YYYY');
349
                  self.showExpirationDate(expireDate, share.stime);
350
                }
351
              });
352
            }
353
            $('#shareWith').autocomplete({
354
              minLength: 1,
355
              delay: 750,
356
              source: function (search, response) {
357
                var $loading = $('#dropdown .shareWithLoading');
358
                $loading.removeClass('hidden');
359
                // Can be replaced with Sharee API
360
                // https://github.com/owncloud/core/pull/18234
361
                $.get('/ocs/v1.php/apps/files_sharing/api/v1/sharees?format=json&search=' + search.term.trim() + '&perPage=200&itemType=' + itemType, {
362
                  fetch: 'getShareWith',
363
                  search: search.term.trim(),
364
                  perPage: 200,
365
                  itemShares: this.itemShares,
366
                  itemType: itemType
367
                }, function (result) {
368
                  var sharees = result.ocs.data;
369
370
                  var results = [];
371
372
                  for (var key in sharees) {
373
                    if (sharees.hasOwnProperty(key)) {
374
                      if (sharees[key]) {
375
                        if (!sharees[key].hasOwnProperty('circles')) {
376
                          results = results.concat(sharees[key])
377
                        }
378
                      }
379
                    }
380
                  }
381
382
                  $loading.addClass('hidden');
383
                  if (result.ocs.meta.status === 'ok') {
384
                    $("#shareWith").autocomplete("option", "autoFocus", true);
385
                    response(results);
386
                  } else {
387
                    response();
388
                  }
389
                }).fail(function () {
390
                  $('#dropdown').find('.shareWithLoading').addClass('hidden');
391
                  OC.Notification.show(t('core', 'An error occured. Please try again'));
392
                  window.setTimeout(OC.Notification.hide, 5000);
393
                });
394
              },
395
              focus: function (event) {
396
                event.preventDefault();
397
              },
398
              select: function (event, selected) {
399
                event.stopPropagation();
400
                var $dropDown = $('#dropdown');
401
                var itemSource = $dropDown.data('item-source');
402
                var expirationDate = '';
403
                if ($('#expirationCheckbox').is(':checked') === true) {
404
                  expirationDate = $("#expirationDate").val();
405
                }
406
                var shareType = selected.item.value.shareType;
407
                var shareWith = selected.item.value.shareWith;
408
                $(this).val(shareWith);
409
                // Default permissions are Edit (CRUD) and Share
410
                // Check if these permissions are possible
411
                var permissions = OC.PERMISSION_READ;
412
                if (shareType === Ownnote.Share.SHARE_TYPE_REMOTE) {
413
                  permissions =
414
                      OC.PERMISSION_CREATE | OC.PERMISSION_UPDATE | OC.PERMISSION_READ;
415
                } else {
416
                  if (possiblePermissions & OC.PERMISSION_UPDATE) {
417
                    permissions = permissions | OC.PERMISSION_UPDATE;
418
                  }
419
                  if (possiblePermissions & OC.PERMISSION_CREATE) {
420
                    permissions = permissions | OC.PERMISSION_CREATE;
421
                  }
422
                  if (possiblePermissions & OC.PERMISSION_DELETE) {
423
                    permissions = permissions | OC.PERMISSION_DELETE;
424
                  }
425
                  if (oc_appconfig.core.resharingAllowed &&
426
                      (possiblePermissions & OC.PERMISSION_SHARE)) {
427
                    permissions = permissions | OC.PERMISSION_SHARE;
428
                  }
429
                }
430
431
                var $input = $(this);
432
                var $loading = $dropDown.find('.shareWithLoading');
433
                $loading.removeClass('hidden');
434
                $input.val(t('core', 'Adding user...'));
435
                $input.prop('disabled', true);
436
                Ownnote.Share.share(
437
                    itemSource,
438
                    shareType,
439
                    shareWith,
440
                    0,
441
                    null,
442
                    permissions,
443
                    function (data) {
444
                      var posPermissions = possiblePermissions;
445
                      if (shareType === Ownnote.Share.SHARE_TYPE_REMOTE) {
446
                        posPermissions = permissions;
447
                      }
448
                      Ownnote.Share._addShareWith(data.id, shareType, shareWith,
449
                          selected.item.label,
450
                          permissions, posPermissions, false, itemSource, false);
451
                    });
452
                $input.prop('disabled', false);
453
                $loading.addClass('hidden');
454
                $('#shareWith').val('');
455
                return false;
456
              }
457
            }).data("ui-autocomplete")._renderItem = function (ul, item) {
458
              // customize internal _renderItem function to display groups and users
459
              // differently
460
              var insert = $("<a>");
461
              var text = item.label;
462
              if (item.value.shareType === Ownnote.Share.SHARE_TYPE_GROUP) {
463
                text = text + ' (' + t('core', 'group') + ')';
464
              } else if (item.value.shareType === Ownnote.Share.SHARE_TYPE_REMOTE) {
465
                text = text + ' (' + t('core', 'remote') + ')';
466
              }
467
              insert.text(text);
468
              if (item.value.shareType === Ownnote.Share.SHARE_TYPE_GROUP) {
469
                insert = insert.wrapInner('<strong></strong>');
470
              }
471
              return $("<li>")
472
              .addClass(
473
                  (item.value.shareType ===
474
                  Ownnote.Share.SHARE_TYPE_GROUP) ? 'group' : 'user')
475
              .append(insert)
476
              .appendTo(ul);
477
            };
478
479
            if (link && linksAllowed && $('#email').length != 0) {
480
              $('#email').autocomplete({
481
                minLength: 1,
482
                source: function (search, response) {
483
                  $.get(OC.filePath('core', 'ajax', 'share.php'), {
484
                    fetch: 'getShareWithEmail',
485
                    search: search.term
486
                  }, function (result) {
487
                    if (result.status == 'success' && result.data.length > 0) {
488
                      response(result.data);
489
                    }
490
                  });
491
                },
492
                select: function (event, item) {
493
                  $('#email').val(item.item.email);
494
                  return false;
495
                }
496
              })
497
              .data("ui-autocomplete")._renderItem = function (ul, item) {
498
                return $('<li>')
499
                .append('<a>' + escapeHTML(item.displayname) + "<br>" +
500
                    escapeHTML(item.email) + '</a>')
501
                .appendTo(ul);
502
              };
503
            }
504
505
          } else {
506
            html += '<input id="shareWith" type="text" placeholder="' +
507
                t('core', 'Resharing is not allowed') +
508
                '" style="width:90%;" disabled="disabled"/>';
509
            html += '</div>';
510
            dropDownEl = $(html);
511
            dropDownEl.appendTo(appendTo);
512
          }
513
          dropDownEl.attr('data-item-source-name', filename);
514
          $('#dropdown').slideDown(OC.menuSpeed, function () {
515
            Ownnote.Share.droppedDown = true;
516
          });
517
          if ($('html').hasClass('lte9')) {
518
            $('#dropdown input[placeholder]').placeholder();
519
          }
520
          $('#shareWith').focus();
521
          if(!link){
522
            $('#expiration').hide();
523
          }
524
        },
525
        /**
526
         *
527
         * @param callback
528
         */
529
        hideDropDown: function (callback) {
530
          this.currentShares = null;
531
          $('#dropdown').slideUp(OC.menuSpeed, function () {
532
            Ownnote.Share.droppedDown = false;
533
            $('#dropdown').remove();
534
            if (typeof FileActions !== 'undefined') {
535
              $('tr').removeClass('mouseOver');
536
            }
537
            if (callback) {
538
              callback.call();
539
            }
540
          });
541
        },
542
        /**
543
         *
544
         * @param id
545
         * @param token
546
         * @param password
547
         */
548
        showLink: function (id, token, password) {
549
          var $linkCheckbox = $('#linkCheckbox');
550
          this.itemShares[this.SHARE_TYPE_LINK] = true;
551
          $linkCheckbox.attr('checked', true);
552
          $linkCheckbox.attr('data-id', id);
553
          var $linkText = $('#linkText');
554
555
          var link = parent.location.protocol + '//' + location.host +
556
              OC.generateUrl('/apps/' + Ownnote.appName + '/s/') + token;
557
558
          $linkText.val(link);
559
          $linkText.slideDown(OC.menuSpeed);
560
          $linkText.css('display', 'block');
561
          if (oc_appconfig.core.enforcePasswordForPublicLink === false || password === null) {
562
            $('#showPassword+label').show();
563
          }
564
          if (password != null) {
565
            $('#linkPass').slideDown(OC.menuSpeed);
566
            $('#showPassword').attr('checked', true);
567
            $('#linkPassText').attr('placeholder', '**********');
568
          }
569
          $('#expiration').show();
570
          $('#emailPrivateLink #email').show();
571
          $('#emailPrivateLink #emailButton').show();
572
          $('#allowPublicUploadWrapper').show();
573
        },
574
        /**
575
         *
576
         */
577
        hideLink: function () {
578
          $('#linkText').slideUp(OC.menuSpeed);
579
          $('#defaultExpireMessage').hide();
580
          $('#showPassword+label').hide();
581
          $('#linkPass').slideUp(OC.menuSpeed);
582
          $('#emailPrivateLink #email').hide();
583
          $('#emailPrivateLink #emailButton').hide();
584
          $('#allowPublicUploadWrapper').hide();
585
        },
586
        /**
587
         * Displays the expiration date field
588
         *
589
         * @param {String} date current expiration date
590
         * @param {Date|Number|String} [shareTime] share timestamp in seconds, defaults to now
591
         */
592
        showExpirationDate: function (date, shareTime) {
593
          var $expirationDate = $('#expirationDate');
594
          var $expirationCheckbox = $('#expirationCheckbox');
595
          var now = new Date();
596
          // min date should always be the next day
597
          var minDate = new Date();
598
          minDate.setDate(minDate.getDate() + 1);
599
          var datePickerOptions = {
600
            minDate: minDate,
601
            maxDate: null
602
          };
603
          // TODO: hack: backend returns string instead of integer
604
          shareTime = this._parseTime(shareTime);
605
          if (_.isNumber(shareTime)) {
606
            shareTime = new Date(shareTime * 1000);
607
          }
608
          if (!shareTime) {
609
            shareTime = now;
610
          }
611
          $expirationCheckbox.attr('checked', true);
612
          $expirationDate.val(date);
613
          $expirationDate.slideDown(OC.menuSpeed);
614
          $expirationDate.css('display', 'block');
615
          $expirationDate.datepicker({
616
            dateFormat: 'dd-mm-yy'
617
          });
618
          if (oc_appconfig.core.defaultExpireDateEnforced) {
619
            $expirationCheckbox.attr('disabled', true);
620
            shareTime = OC.Util.stripTime(shareTime).getTime();
621
            // max date is share date + X days
622
            datePickerOptions.maxDate =
623
                new Date(shareTime + oc_appconfig.core.defaultExpireDate * 24 * 3600 * 1000);
624
          }
625
          if (oc_appconfig.core.defaultExpireDateEnabled) {
626
            $('#defaultExpireMessage').slideDown(OC.menuSpeed);
627
          }
628
          $.datepicker.setDefaults(datePickerOptions);
629
        },
630
        /**
631
         * Get the default Expire date
632
         *
633
         * @return {String} The expire date
634
         */
635
        getDefaultExpirationDate: function () {
636
          var expireDateString = '';
637
          if (oc_appconfig.core.defaultExpireDateEnabled) {
638
            var date = new Date().getTime();
639
            var expireAfterMs = oc_appconfig.core.defaultExpireDate * 24 * 60 * 60 * 1000;
640
            var expireDate = new Date(date + expireAfterMs);
641
            var month = expireDate.getMonth() + 1;
642
            var year = expireDate.getFullYear();
643
            var day = expireDate.getDate();
644
            expireDateString = year + "-" + month + '-' + day + ' 00:00:00';
645
          }
646
          return expireDateString;
647
        },
648
        /**
649
         * Loads all shares associated with a path
650
         *
651
         * @param path
652
         *
653
         * @returns {Ownnote.Share.Types.ShareInfo|Boolean}
654
         * @private
655
         */
656
        _loadShares: function (noteid) {
657
          var data = false;
658
          var url = OC.generateUrl('/apps/nextnote/') + 'api/v2.0/sharing/shares';
659
          $.ajax({
660
            url: url,
661
            type: 'GET',
662
            data: {
663
              noteid: noteid,
664
              shared_with_me: true
665
            },
666
            async: false
667
          }).done(function (result) {
668
            data = result;
669
            $.ajax({
670
              url: url,
671
              type: 'GET',
672
              data: {
673
                noteid: noteid,
674
                reshares: true
675
              },
676
              async: false
677
            }).done(function (result) {
678
              data = _.union(data, result);
679
            })
680
681
          });
682
683
          if (data === false) {
684
            OC.dialogs.alert(t('Ownnote', 'Error while retrieving shares'),
685
                t('core', 'Error'));
686
          }
687
688
          return data;
689
        },
690
        /**
691
         *
692
         * @param shareId
693
         * @param shareType
694
         * @param shareWith
695
         * @param shareWithDisplayName
696
         * @param permissions
697
         * @param possiblePermissions
698
         * @param mailSend
699
         *
700
         * @private
701
         */
702
        _addShareWith: function (shareId, shareType, shareWith, shareWithDisplayName, permissions, possiblePermissions, mailSend, itemSource) {
703
          var shareItem = {
704
            share_id: shareId,
705
            share_type: shareType,
706
            share_with: shareWith,
707
            share_with_displayname: shareWithDisplayName,
708
            permissions: permissions,
709
            itemSource: itemSource,
710
          };
711
          if (shareType === this.SHARE_TYPE_GROUP) {
712
            shareWithDisplayName = shareWithDisplayName + " (" + t('core', 'group') + ')';
713
          }
714
          if (shareType === this.SHARE_TYPE_REMOTE) {
715
            shareWithDisplayName = shareWithDisplayName + " (" + t('core', 'remote') + ')';
716
          }
717
          if (!this.itemShares[shareType]) {
718
            this.itemShares[shareType] = [];
719
          }
720
          this.itemShares[shareType].push(shareWith);
721
722
          var editChecked = '',
723
              createChecked = '',
724
              updateChecked = '',
725
              deleteChecked = '',
726
              shareChecked = '';
727
          if (permissions & OC.PERMISSION_CREATE) {
728
            createChecked = 'checked="checked"';
729
            editChecked = 'checked="checked"';
730
          }
731
          if (permissions & OC.PERMISSION_UPDATE) {
732
            updateChecked = 'checked="checked"';
733
            editChecked = 'checked="checked"';
734
          }
735
          if (permissions & OC.PERMISSION_DELETE) {
736
            deleteChecked = 'checked="checked"';
737
            editChecked = 'checked="checked"';
738
          }
739
          if (permissions & OC.PERMISSION_SHARE) {
740
            shareChecked = 'checked="checked"';
741
          }
742
          var html = '<li style="clear: both;" ' +
743
              'data-id="' + escapeHTML(shareId) + '"' +
744
              'data-share-type="' + escapeHTML(shareType) + '"' +
745
              'data-share-with="' + escapeHTML(shareWith) + '"' +
746
              'data-item-source="' + escapeHTML(itemSource) + '"' +
747
              'title="' + escapeHTML(shareWith) + '">';
748
          var showCrudsButton;
749
          html +=
750
              '<a href="#" class="unshare"><img class="svg" alt="' + t('core', 'Unshare') +
751
              '" title="' + t('core', 'Unshare') + '" src="' +
752
              OC.imagePath('core', 'actions/delete') + '"/></a>';
753
          if (oc_config.enable_avatars === true) {
754
            html += '<div class="avatar"></div>';
755
          }
756
          html += '<span class="username">' + escapeHTML(shareWithDisplayName) + '</span>';
757
          var mailNotificationEnabled = $('input:hidden[name=mailNotificationEnabled]').val();
758
          if (mailNotificationEnabled === 'yes' &&
759
              shareType !== this.SHARE_TYPE_REMOTE) {
760
            var checked = '';
761
            if (mailSend === 1) {
762
              checked = 'checked';
763
            }
764
            html +=
765
                '<input id="mail-' + escapeHTML(shareWith) + '" type="checkbox" class="mailNotification checkbox checkbox--right" ' +
766
                'name="mailNotification" ' +
767
                checked + ' />';
768
            html +=
769
                '<label for="mail-' + escapeHTML(shareWith) + '">' + t('core', 'notify by email') + '</label>';
770
          }
771
          html += '<span class="sharingOptionsGroup">';
772
          if (oc_appconfig.core.resharingAllowed &&
773
              (possiblePermissions & OC.PERMISSION_SHARE)) {
774
            html += '<input id="canShare-' + escapeHTML(shareWith) +
775
                '" type="checkbox" class="permissions checkbox checkbox--right" name="share" ' +
776
                shareChecked + ' data-permissions="' + OC.PERMISSION_SHARE + '" />';
777
            html += '<label for="canShare-' + escapeHTML(shareWith) + '">' +
778
                t('core', 'can share') + '</label>';
779
          }
780
          /*if (possiblePermissions & OC.PERMISSION_CREATE ||
781
              possiblePermissions & OC.PERMISSION_UPDATE ||
782
              possiblePermissions & OC.PERMISSION_DELETE) {
783
            html += '<input id="canEdit-' + escapeHTML(shareWith) +
784
                '" type="checkbox" class="permissions checkbox checkbox--right" name="edit" ' +
785
                editChecked + ' />';
786
            html += '<label for="canEdit-' + escapeHTML(shareWith) + '">' +
787
                t('core', 'can edit') + '</label>';
788
          }*/
789
          if (shareType !== this.SHARE_TYPE_REMOTE) {
790
            showCrudsButton = '<a class="showCruds"><img class="svg" alt="' +
791
                t('core', 'access control') + '" src="' +
792
                OC.imagePath('core', 'actions/triangle-s') + '"/></a>';
793
          }
794
          //html += '<div class="cruds" style="display:none;">';
795
          if (possiblePermissions & OC.PERMISSION_UPDATE) {
796
            html += '<input id="canUpdate-' + escapeHTML(shareWith) +
797
                '" type="checkbox" class="permissions checkbox checkbox--right" name="update" ' +
798
                updateChecked + ' data-permissions="' + OC.PERMISSION_UPDATE + '"/>';
799
            html += '<label for="canUpdate-' + escapeHTML(shareWith) + '">' +
800
                t('core', 'can edit') + '</label>';
801
          }
802
          if (possiblePermissions & OC.PERMISSION_DELETE) {
803
            html += '<input id="canDelete-' + escapeHTML(shareWith) +
804
                '" type="checkbox" class="permissions checkbox checkbox--right" name="delete" ' +
805
                deleteChecked + ' data-permissions="' + OC.PERMISSION_DELETE + '"/>';
806
            html += '<label for="canDelete-' + escapeHTML(shareWith) + '">' +
807
                t('core', 'delete') + '</label>';
808
          }
809
          html += '</span>';
810
          //html += '</div>';
811
          html += '</li>';
812
          html = $(html).appendTo('#shareWithList');
813
          if (oc_config.enable_avatars === true) {
814
            if (shareType === this.SHARE_TYPE_USER) {
815
              html.find('.avatar').avatar(escapeHTML(shareWith), 32);
816
            } else {
817
              //Add sharetype to generate different seed if there is a group and use with
818
              // the same name
819
              html.find('.avatar').imageplaceholder(
820
                  escapeHTML(shareWith) + ' ' + shareType);
821
            }
822
          }
823
          // insert cruds button into last label element
824
          var lastLabel = html.find('>label:last');
825
          if (lastLabel.exists()) {
826
            lastLabel.append(showCrudsButton);
827
          }
828
          else {
829
            html.find('.cruds').before(showCrudsButton);
830
          }
831
          if (!this.currentShares[shareType]) {
832
            this.currentShares[shareType] = [];
833
          }
834
          this.currentShares[shareType].push(shareItem);
835
        },
836
        /**
837
         * Parses a string to an valid integer (unix timestamp)
838
         * @param time
839
         * @returns {*}
840
         * @internal Only used to work around a bug in the backend
841
         * @private
842
         */
843
        _parseTime: function (time) {
844
          if (_.isString(time)) {
845
            // skip empty strings and hex values
846
            if (time === '' || (time.length > 1 && time[0] === '0' && time[1] === 'x')) {
847
              return null;
848
            }
849
            time = parseInt(time, 10);
850
            if (isNaN(time)) {
851
              time = null;
852
            }
853
          }
854
          return time;
855
        }
856
      };
857
858
  Ownnote.Share = Share;
859
})(jQuery, Ownnote);
860
861
$(document).ready(function () {
862
863
  if (typeof monthNames != 'undefined') {
864
    // min date should always be the next day
865
    var minDate = new Date();
866
    minDate.setDate(minDate.getDate() + 1);
867
    $.datepicker.setDefaults({
868
      monthNames: monthNames,
869
      monthNamesShort: $.map(monthNames, function (v) {
870
        return v.slice(0, 3) + '.';
871
      }),
872
      dayNames: dayNames,
873
      dayNamesMin: $.map(dayNames, function (v) {
874
        return v.slice(0, 2);
875
      }),
876
      dayNamesShort: $.map(dayNames, function (v) {
877
        return v.slice(0, 3) + '.';
878
      }),
879
      firstDay: firstDay,
880
      minDate: minDate
881
    });
882
  }
883
  $(document).on('click', 'a.share', function (event) {
884
    event.stopPropagation();
885
    if ($(this).data('item-type') !== undefined && $(this).data('path') !== undefined) {
886
      var itemType = $(this).data('item-type');
887
      var path = $(this).data('path');
888
      var appendTo = $(this).parent().parent();
889
      var link = false;
890
      var possiblePermissions = $(this).data('possible-permissions');
891
      if ($(this).data('link') !== undefined && $(this).data('link') == true) {
892
        link = true;
893
      }
894
     // Ownnote.Share.showDropDown(itemType, path, appendTo, link, possiblePermissions);
895
896
      if (Ownnote.Share.droppedDown) {
897
        if (path != $('#dropdown').data('path')) {
898
          Ownnote.Share.hideDropDown(function() {
899
            Ownnote.Share.showDropDown(itemType, path, appendTo, link,
900
                possiblePermissions);
901
          });
902
        } else {
903
          Ownnote.Share.hideDropDown();
904
        }
905
      } else {
906
        Ownnote.Share.showDropDown(itemType, path, appendTo, link, possiblePermissions);
907
      }
908
    }
909
  });
910
911
  $(this).click(function (event) {
912
    var target = $(event.target);
913
    var isMatched = !target.is('.drop, .ui-datepicker-next, .ui-datepicker-prev, .ui-icon')
914
        && !target.closest('#ui-datepicker-div').length &&
915
        !target.closest('.ui-autocomplete').length;
916
    if (Ownnote.Share.droppedDown && isMatched &&
917
        $('#dropdown').has(event.target).length === 0) {
918
        Ownnote.Share.hideDropDown();
919
    }
920
  });
921
922
  $(document).on('click', '#dropdown .showCruds', function (e) {
923
924
    $(this).parent().find('.cruds').toggle();
925
    return false;
926
  });
927
928
  $(document).on('click', '#dropdown .unshare', function () {
929
    var $li = $(this).closest('li');
930
    var shareType = $li.data('share-type');
931
    var shareWith = $li.attr('data-share-with');
932
    var shareId = $li.attr('data-id');
933
    var itemSource = $li.data('item-source');
934
    var $button = $(this);
935
936
    if (!$button.is('a')) {
937
      $button = $button.closest('a');
938
    }
939
940
    if ($button.hasClass('icon-loading-small')) {
941
      // deletion in progress
942
      return false;
943
    }
944
    $button.empty().addClass('icon-loading-small');
945
    Ownnote.Share.unshare(itemSource, shareType, shareWith, function () {
946
      $li.remove();
947
      var index = Ownnote.Share.itemShares[shareType].indexOf(shareWith);
948
      Ownnote.Share.itemShares[shareType].splice(index, 1);
949
      // updated list of shares
950
      Ownnote.Share.currentShares[shareType].splice(index, 1);
951
      // todo: update listing
952
    });
953
954
    return false;
955
  });
956
957
  $(document).on('change', '#dropdown .permissions', function () {
958
    var $li = $(this).closest('li');
959
    var checkboxes = $('.permissions', $li);
960
    if ($(this).attr('name') == 'edit') {
961
      var checked = $(this).is(':checked');
962
      // Check/uncheck Create, Update, and Delete checkboxes if Edit is checked/unck
963
      $(checkboxes).filter('input[name="create"]').attr('checked', checked);
964
      $(checkboxes).filter('input[name="update"]').attr('checked', checked);
965
      $(checkboxes).filter('input[name="delete"]').attr('checked', checked);
966
    } else {
967
      // Uncheck Edit if Create, Update, and Delete are not checked
968
      if (!$(this).is(':checked')
969
          && !$(checkboxes).filter('input[name="create"]').is(':checked')
970
          && !$(checkboxes).filter('input[name="update"]').is(':checked')
971
          && !$(checkboxes).filter('input[name="delete"]').is(':checked')) {
972
        $(checkboxes).filter('input[name="edit"]').attr('checked', false);
973
        // Check Edit if Create, Update, or Delete is checked
974
      } else if (($(this).attr('name') == 'create'
975
          || $(this).attr('name') == 'update'
976
          || $(this).attr('name') == 'delete')) {
977
        $(checkboxes).filter('input[name="edit"]').attr('checked', true);
978
      }
979
    }
980
    var permissions = OC.PERMISSION_READ;
981
    $(checkboxes).filter(':not(input[name="edit"])').filter(':checked').each(
982
        function (index, checkbox) {
983
          permissions += $(checkbox).data('permissions');
984
        });
985
    Ownnote.Share.setPermissions(
986
        $li.attr('data-item-source'),
987
        $li.attr('data-share-type'),
988
        $li.attr('data-share-with'),
989
        permissions
990
    );
991
  });
992
993
  $(document).on('change', '#dropdown #linkCheckbox', function () {
994
    var $dropDown = $('#dropdown');
995
    var path = $dropDown.data('item-source');
996
    var shareId = $('#linkCheckbox').data('id');
997
    var shareWith = '';
998
    var publicUpload = 0;
999
    var $loading = $dropDown.find('#link .icon-loading-small');
1000
    var $button = $(this);
1001
1002
    if (!$loading.hasClass('hidden')) {
1003
      // already in progress
1004
      return false;
1005
    }
1006
1007
    if (this.checked) {
1008
      // Reset password placeholder
1009
      $('#linkPassText').attr('placeholder',
1010
          t('core', 'Choose a password for the public link'));
1011
      // Reset link
1012
      $('#linkText').val('');
1013
      $('#showPassword').prop('checked', false);
1014
      $('#linkPass').hide();
1015
      $('#sharingDialogAllowPublicUpload').prop('checked', false);
1016
      $('#expirationCheckbox').prop('checked', false);
1017
      $('#expirationDate').hide();
1018
      var expireDateString = '';
1019
      // Create a link
1020
      if (oc_appconfig.core.enforcePasswordForPublicLink === false) {
1021
        expireDateString = Ownnote.Share.getDefaultExpirationDate();
1022
        $loading.removeClass('hidden');
1023
        $button.addClass('hidden');
1024
        $button.prop('disabled', true);
1025
        Ownnote.Share.share(
1026
            path,
1027
            Ownnote.Share.SHARE_TYPE_LINK,
1028
            shareWith,
1029
            publicUpload,
1030
            null,
1031
            OC.PERMISSION_READ,
1032
            function (data) {
1033
              $loading.addClass('hidden');
1034
              $button.removeClass('hidden');
1035
              $button.prop('disabled', false);
1036
              Ownnote.Share.showLink(data.id, data.token, null);
1037
            });
1038
      } else {
1039
        $('#linkPass').slideToggle(OC.menuSpeed);
1040
        $('#linkPassText').focus();
1041
      }
1042
      if (expireDateString !== '') {
1043
        Ownnote.Share.showExpirationDate(expireDateString);
1044
      }
1045
    } else {
1046
      // Delete private link
1047
      Ownnote.Share.hideLink();
1048
      $('#expiration').slideUp(OC.menuSpeed);
1049
      if ($('#linkText').val() !== '') {
1050
        $loading.removeClass('hidden');
1051
        $button.addClass('hidden');
1052
        $button.prop('disabled', true);
1053
        Ownnote.Share.unshare(shareId, function () {
1054
          $loading.addClass('hidden');
1055
          $button.removeClass('hidden');
1056
          $button.prop('disabled', false);
1057
          Ownnote.Share.itemShares[Ownnote.Share.SHARE_TYPE_LINK] = false;
1058
        });
1059
      }
1060
    }
1061
  });
1062
1063
  $(document).on('click', '#dropdown #linkText', function () {
1064
    $(this).focus();
1065
    $(this).select();
1066
  });
1067
1068
  // Handle the Allow Public Upload Checkbox
1069
  $(document).on('click', '#sharingDialogAllowPublicUpload', function () {
1070
1071
    // Gather data
1072
    var $dropDown = $('#dropdown');
1073
    var shareId = $('#linkCheckbox').data('id');
1074
    var allowPublicUpload = $(this).is(':checked');
1075
    var $button = $(this);
1076
    var $loading = $dropDown.find('#allowPublicUploadWrapper .icon-loading-small');
1077
1078
    if (!$loading.hasClass('hidden')) {
1079
      // already in progress
1080
      return false;
1081
    }
1082
1083
    // Update the share information
1084
    $button.addClass('hidden');
1085
    $button.prop('disabled', true);
1086
    $loading.removeClass('hidden');
1087
    //(path, shareType, shareWith, publicUpload, password, permissions)
1088
    $.ajax({
1089
      url: OC.linkToOCS('apps/files_sharing/api/v1', 2) + 'shares/' + shareId +
1090
      '?format=json',
1091
      type: 'PUT',
1092
      data: {
1093
        publicUpload: allowPublicUpload
1094
      }
1095
    }).done(function () {
1096
      $loading.addClass('hidden');
1097
      $button.removeClass('hidden');
1098
      $button.prop('disabled', false);
1099
    });
1100
  });
1101
1102
  $(document).on('click', '#dropdown #showPassword', function () {
1103
    $('#linkPass').slideToggle(OC.menuSpeed);
1104
    if (!$('#showPassword').is(':checked')) {
1105
      var shareId = $('#linkCheckbox').data('id');
1106
      var $loading = $('#showPassword .icon-loading-small');
1107
1108
      $loading.removeClass('hidden');
1109
      $.ajax({
1110
        url: OC.linkToOCS('apps/files_sharing/api/v1', 2) + 'shares/' + shareId +
1111
        '?format=json',
1112
        type: 'PUT',
1113
        data: {
1114
          password: null
1115
        }
1116
      }).done(function () {
1117
        $loading.addClass('hidden');
1118
        $('#linkPassText').attr('placeholder',
1119
            t('core', 'Choose a password for the public link'));
1120
      });
1121
    } else {
1122
      $('#linkPassText').focus();
1123
    }
1124
  });
1125
1126
  $(document).on('focusout keyup', '#dropdown #linkPassText', function (event) {
1127
    var linkPassText = $('#linkPassText');
1128
    if (linkPassText.val() != '' && (event.type == 'focusout' || event.keyCode == 13)) {
1129
      var dropDown = $('#dropdown');
1130
      var $loading = dropDown.find('#linkPass .icon-loading-small');
1131
      var shareId = $('#linkCheckbox').data('id');
1132
1133
      $loading.removeClass('hidden');
1134
      $.ajax({
1135
        url: OC.linkToOCS('apps/files_sharing/api/v1', 2) + 'shares/' + shareId +
1136
        '?format=json',
1137
        type: 'PUT',
1138
        data: {
1139
          password: $('#linkPassText').val()
1140
        }
1141
      }).done(function (data) {
1142
        $loading.addClass('hidden');
1143
        linkPassText.val('');
1144
        linkPassText.attr('placeholder', t('core', 'Password protected'));
1145
1146
        if (oc_appconfig.core.enforcePasswordForPublicLink) {
1147
          Ownnote.Share.showLink(data.id, data.token, "password set");
1148
        }
1149
      }).fail(function (xhr) {
1150
        var result = xhr.responseJSON;
1151
        $loading.addClass('hidden');
1152
        linkPassText.val('');
1153
        linkPassText.attr('placeholder', result.data.message);
1154
      });
1155
    }
1156
  });
1157
1158
  $(document).on('click', '#dropdown #expirationCheckbox', function () {
1159
    if (this.checked) {
1160
      Ownnote.Share.showExpirationDate('');
1161
    } else {
1162
      var shareId = $('#linkCheckbox').data('id');
1163
      $.ajax({
1164
        url: OC.linkToOCS('apps/files_sharing/api/v1', 2) + 'shares/' + shareId +
1165
        '?format=json',
1166
        type: 'PUT',
1167
        data: {
1168
          expireDate: ''
1169
        }
1170
      }).done(function () {
1171
        $('#expirationDate').slideUp(OC.menuSpeed);
1172
        if (oc_appconfig.core.defaultExpireDateEnforced === false) {
1173
          $('#defaultExpireMessage').slideDown(OC.menuSpeed);
1174
        }
1175
      }).fail(function () {
1176
        OC.dialogs.alert(t('core', 'Error unsetting expiration date'),
1177
            t('core', 'Error'));
1178
      });
1179
    }
1180
  });
1181
1182
  $(document).on('change', '#dropdown #expirationDate', function () {
1183
    var shareId = $('#linkCheckbox').data('id');
1184
    if(!shareId){
1185
      return;
1186
    }
1187
    $(this).tooltip('hide');
1188
    $(this).removeClass('error');
1189
1190
    $.ajax({
1191
      url: OC.linkToOCS('apps/files_sharing/api/v1', 2) + 'shares/' + shareId +
1192
      '?format=json',
1193
      type: 'PUT',
1194
      data: {
1195
        expireDate: $(this).val()
1196
      }
1197
    }).done(function () {
1198
      if (oc_appconfig.core.defaultExpireDateEnforced === 'no') {
1199
        $('#defaultExpireMessage').slideUp(OC.menuSpeed);
1200
      }
1201
    }).fail(function (xhr) {
1202
      var result = xhr.responseJSON;
1203
      var expirationDateField = $('#dropdown #expirationDate');
1204
      if (result && !result.ocs.meta.message) {
1205
        expirationDateField.attr('original-title',
1206
            t('core', 'Error setting expiration date'));
1207
      } else {
1208
        expirationDateField.attr('original-title', result.ocs.meta.message);
1209
      }
1210
      expirationDateField.tooltip({placement: 'top'});
1211
      expirationDateField.tooltip('show');
1212
      expirationDateField.addClass('error');
1213
    });
1214
  });
1215
1216
1217
  $(document).on('submit', '#dropdown #emailPrivateLink', function (event) {
1218
    event.preventDefault();
1219
    var link = $('#linkText').val();
1220
    var itemType = $('#dropdown').data('item-type');
1221
    var itemSource = $('#dropdown').data('item-source');
1222
    var fileName = $('.last').children()[0].innerText;
1223
    var email = $('#email').val();
1224
    var expirationDate = '';
1225
    if ($('#expirationCheckbox').is(':checked') === true) {
1226
      expirationDate = $("#expirationDate").val();
1227
    }
1228
    if (email != '') {
1229
      $('#email').prop('disabled', true);
1230
      $('#email').val(t('core', 'Sending ...'));
1231
      $('#emailButton').prop('disabled', true);
1232
1233
      $.post(OC.filePath('core', 'ajax', 'share.php'), {
1234
            action: 'email',
1235
            toaddress: email,
1236
            link: link,
1237
            file: fileName,
1238
            itemType: itemType,
1239
            itemSource: itemSource,
1240
            expiration: expirationDate
1241
          },
1242
          function (result) {
1243
            $('#email').prop('disabled', false);
1244
            $('#emailButton').prop('disabled', false);
1245
            if (result && result.status == 'success') {
1246
              $('#email').css('font-weight', 'bold').val(t('core', 'Email sent'));
1247
              setTimeout(function () {
1248
                $('#email').css('font-weight', 'normal').val('');
1249
              }, 2000);
1250
            } else {
1251
              OC.dialogs.alert(result.data.message, t('core', 'Error while sharing'));
1252
            }
1253
          });
1254
    }
1255
  });
1256
1257
  $(document).on('click', '#dropdown input[name=mailNotification]', function () {
1258
    var $li = $(this).closest('li');
1259
    var itemType = $('#dropdown').data('item-type');
1260
    var itemSource = $('a.share').data('item-source');
1261
    var action = '';
1262
    if (this.checked) {
1263
      action = 'informRecipients';
1264
    } else {
1265
      action = 'informRecipientsDisabled';
1266
    }
1267
    var shareType = $li.data('share-type');
1268
    var shareWith = $li.attr('data-share-with');
1269
    $.post(OC.filePath('core', 'ajax', 'share.php'), {
1270
      action: action,
1271
      recipient: shareWith,
1272
      shareType: shareType,
1273
      itemSource: itemSource,
1274
      itemType: itemType
1275
    }, function (result) {
1276
      if (result.status !== 'success') {
1277
        OC.dialogs.alert(t('core', result.data.message), t('core', 'Warning'));
1278
      }
1279
    });
1280
1281
  });
1282
});
1283