Merge pull request #19708 from J0WI/patch-1
[civicrm-core.git] / js / crm.ajax.js
1 // https://civicrm.org/licensing
2 /**
3 * @see https://docs.civicrm.org/dev/en/latest/api/interfaces/#ajax
4 * @see https://docs.civicrm.org/dev/en/latest/framework/ajax/
5 */
6 (function($, CRM, _, undefined) {
7 /**
8 * @param string path
9 * @param string|object query
10 * @param string mode - optionally specify "front" or "back"
11 */
12 var tplURL;
13 CRM.url = function (path, query, mode) {
14 if (typeof path === 'object') {
15 tplURL = path;
16 return path;
17 }
18 if (!tplURL) {
19 CRM.console('error', 'Error: CRM.url called before initialization');
20 }
21 if (!mode) {
22 mode = CRM.config && CRM.config.isFrontend ? 'front' : 'back';
23 }
24 query = query || '';
25 var frag = path.split('?');
26 var url = tplURL[mode].replace("civicrm-placeholder-url-path", frag[0]);
27
28 if (!query) {
29 url = url.replace(/[?&]civicrm-placeholder-url-query=1/, '');
30 }
31 else {
32 url = url.replace("civicrm-placeholder-url-query=1", typeof query === 'string' ? query : $.param(query));
33 }
34 if (frag[1]) {
35 url += (url.indexOf('?') < 0 ? '?' : '&') + frag[1];
36 }
37 return url;
38 };
39
40 $.fn.crmURL = function () {
41 return this.each(function() {
42 if (this.href) {
43 this.href = CRM.url(this.href);
44 }
45 });
46 };
47
48 // result is an array, but in js, an array is also an object
49 // Assign all the metadata properties to it, mirroring the results arrayObject in php
50 function arrayObject(data) {
51 var result = data.values || [];
52 if (_.isArray(result)) {
53 delete(data.values);
54 _.assign(result, data);
55 }
56 return result;
57 }
58
59 // https://docs.civicrm.org/dev/en/latest/api/interfaces/#ajax
60 CRM.api4 = function(entity, action, params, index) {
61 return new Promise(function(resolve, reject) {
62 if (typeof entity === 'string') {
63 $.post(CRM.url('civicrm/ajax/api4/' + entity + '/' + action), {
64 params: JSON.stringify(params),
65 index: index
66 })
67 .done(function (data) {
68 resolve(arrayObject(data));
69 })
70 .fail(function (data) {
71 reject(data.responseJSON);
72 });
73 } else {
74 $.post(CRM.url('civicrm/ajax/api4'), {
75 calls: JSON.stringify(entity)
76 })
77 .done(function(data) {
78 _.each(data, function(item, key) {
79 data[key] = arrayObject(item);
80 });
81 resolve(data);
82 })
83 .fail(function (data) {
84 reject(data.responseJSON);
85 });
86 }
87 });
88 };
89
90 /**
91 * AJAX api
92 * @link https://docs.civicrm.org/dev/en/latest/api/interfaces/#ajax
93 */
94 CRM.api3 = function(entity, action, params, status) {
95 if (typeof(entity) === 'string') {
96 params = {
97 entity: entity,
98 action: action.toLowerCase(),
99 json: JSON.stringify(params || {})
100 };
101 } else {
102 params = {
103 entity: 'api3',
104 action: 'call',
105 json: JSON.stringify(entity)
106 };
107 status = action;
108 }
109 var ajax = $.ajax({
110 url: CRM.url('civicrm/ajax/rest'),
111 dataType: 'json',
112 data: params,
113 type: params.action.indexOf('get') === 0 ? 'GET' : 'POST'
114 });
115 if (status) {
116 // Default status messages
117 if (status === true) {
118 status = {success: params.action === 'delete' ? ts('Removed') : ts('Saved')};
119 if (params.action.indexOf('get') === 0) {
120 status.start = ts('Loading...');
121 status.success = null;
122 }
123 }
124 var messages = status === true ? {} : status;
125 CRM.status(status, ajax);
126 }
127 return ajax;
128 };
129
130 /**
131 * @deprecated
132 * AJAX api
133 */
134 CRM.api = function(entity, action, params, options) {
135 // Default settings
136 var settings = {
137 context: null,
138 success: function(result, settings) {
139 return true;
140 },
141 error: function(result, settings) {
142 $().crmError(result.error_message, ts('Error'));
143 return false;
144 },
145 callBack: function(result, settings) {
146 if (result.is_error == 1) {
147 return settings.error.call(this, result, settings);
148 }
149 return settings.success.call(this, result, settings);
150 },
151 ajaxURL: 'civicrm/ajax/rest'
152 };
153 action = action.toLowerCase();
154 // Default success handler
155 switch (action) {
156 case "update":
157 case "create":
158 case "setvalue":
159 case "replace":
160 settings.success = function() {
161 CRM.status(ts('Saved'));
162 return true;
163 };
164 break;
165 case "delete":
166 settings.success = function() {
167 CRM.status(ts('Removed'));
168 return true;
169 };
170 }
171 params = {
172 entity: entity,
173 action: action,
174 json: JSON.stringify(params)
175 };
176 // Pass copy of settings into closure to preserve its value during multiple requests
177 (function(stg) {
178 $.ajax({
179 url: stg.ajaxURL.indexOf('http') === 0 ? stg.ajaxURL : CRM.url(stg.ajaxURL),
180 dataType: 'json',
181 data: params,
182 type: action.indexOf('get') < 0 ? 'POST' : 'GET',
183 success: function(result) {
184 stg.callBack.call(stg.context, result, stg);
185 }
186 });
187 })($.extend({}, settings, options));
188 };
189
190 $.widget('civi.crmSnippet', {
191 options: {
192 url: null,
193 block: true,
194 crmForm: null
195 },
196 _originalContent: null,
197 _originalUrl: null,
198 isOriginalUrl: function() {
199 var
200 args = {},
201 same = true,
202 newUrl = this._formatUrl(this.options.url),
203 oldUrl = this._formatUrl(this._originalUrl);
204 // Compare path
205 if (newUrl.split('?')[0] !== oldUrl.split('?')[0]) {
206 return false;
207 }
208 // Compare arguments
209 $.each((newUrl.split('?')[1] || '').split('&'), function(k, v) {
210 var arg = v.split('=');
211 args[arg[0]] = arg[1];
212 });
213 $.each((oldUrl.split('?')[1] || '').split('&'), function(k, v) {
214 var arg = v.split('=');
215 if (args[arg[0]] !== undefined && arg[1] !== args[arg[0]]) {
216 same = false;
217 }
218 });
219 return same;
220 },
221 resetUrl: function() {
222 this.options.url = this._originalUrl;
223 },
224 _create: function() {
225 this.element.addClass('crm-ajax-container');
226 if (!this.element.is('.crm-container *')) {
227 this.element.addClass('crm-container');
228 }
229 this._handleOrderLinks();
230 // Set default if not supplied
231 this.options.url = this.options.url || document.location.href;
232 this._originalUrl = this.options.url;
233 },
234 _onFailure: function(data, status) {
235 var msg, title = ts('Network Error');
236 if (this.options.block) this.element.unblock();
237 this.element.trigger('crmAjaxFail', data);
238 switch (status) {
239 case 'Forbidden':
240 title = ts('Access Denied');
241 msg = ts('Ensure you are still logged in and have permission to access this feature.');
242 break;
243 default:
244 msg = ts('Unable to reach the server. Please refresh this page in your browser and try again.');
245 }
246 CRM.alert(msg, title, 'error');
247 },
248 _onError: function(data) {
249 this.element.attr('data-unsaved-changes', 'false').trigger('crmAjaxError', data);
250 if (this.options.crmForm && this.options.crmForm.autoClose && this.element.data('uiDialog')) {
251 this.element.dialog('close');
252 }
253 },
254 _formatUrl: function(url, snippetType) {
255 // Strip hash
256 url = url.split('#')[0];
257 // Add snippet argument to url
258 if (snippetType) {
259 if (url.search(/[&?]snippet=/) < 0) {
260 url += (url.indexOf('?') < 0 ? '?' : '&') + 'snippet=' + snippetType;
261 } else {
262 url = url.replace(/snippet=[^&]*/, 'snippet=' + snippetType);
263 }
264 }
265 return url;
266 },
267 // Hack to deal with civicrm legacy sort functionality
268 _handleOrderLinks: function() {
269 var that = this;
270 $('a.crm-weight-arrow', that.element).click(function(e) {
271 if (that.options.block) that.element.block();
272 $.getJSON(that._formatUrl(this.href, 'json')).done(function() {
273 that.refresh();
274 });
275 e.stopImmediatePropagation();
276 return false;
277 });
278 },
279 refresh: function() {
280 var that = this;
281 var url = this._formatUrl(this.options.url, 'json');
282 if (this.options.crmForm) $('form', this.element).ajaxFormUnbind();
283 if (this.options.block) this.element.block();
284 $.getJSON(url, function(data) {
285 if (data.status === 'redirect') {
286 that.options.url = data.userContext;
287 return that.refresh();
288 }
289 if (that.options.block) that.element.unblock();
290 if (!$.isPlainObject(data)) {
291 that._onFailure(data);
292 return;
293 }
294 if (data.status === 'error') {
295 that._onError(data);
296 return;
297 }
298 data.url = url;
299 that.element.trigger('crmUnload').trigger('crmBeforeLoad', data);
300 that._beforeRemovingContent();
301 that.element.html(data.content);
302 that._handleOrderLinks();
303 that.element.trigger('crmLoad', data);
304 if (that.options.crmForm) that.element.trigger('crmFormLoad', data);
305 // This is only needed by forms that load via ajax but submit without ajax, e.g. configure contribution page tabs
306 // TODO: remove this when those forms have been converted to use ajax submit
307 if (data.status === 'form_error' && $.isPlainObject(data.errors)) {
308 that.element.trigger('crmFormError', data);
309 $.each(data.errors, function(formElement, msg) {
310 $('[name="'+formElement+'"]', that.element).crmError(msg);
311 });
312 }
313 }).fail(function(data, msg, status) {
314 that._onFailure(data, status);
315 });
316 },
317 // Perform any cleanup needed before removing/replacing content
318 _beforeRemovingContent: function() {
319 var that = this;
320 // Save original content to be restored if widget is destroyed
321 if (this._originalContent === null) {
322 $('.blockUI', this.element).remove();
323 this._originalContent = this.element.contents().detach();
324 }
325 if (this.options.crmForm) $('form', this.element).ajaxFormUnbind();
326 },
327 _destroy: function() {
328 this.element.removeClass('crm-ajax-container').trigger('crmUnload');
329 this._beforeRemovingContent();
330 if (this._originalContent !== null) {
331 this.element.empty().append(this._originalContent);
332 }
333 }
334 });
335
336 var dialogCount = 0,
337 exclude = '[href^=#], [href^=javascript], [onclick], .no-popup, .cancel';
338
339 CRM.loadPage = function(url, options) {
340 var settings = {
341 target: '#crm-ajax-dialog-' + (dialogCount++),
342 dialog: (options && options.target) ? false : {}
343 };
344 if (options) $.extend(true, settings, options);
345 settings.url = url;
346 // Create new dialog
347 if (settings.dialog) {
348 settings.dialog = CRM.utils.adjustDialogDefaults(settings.dialog);
349 $('<div id="' + settings.target.substring(1) + '"></div>')
350 .dialog(settings.dialog)
351 .parent().find('.ui-dialog-titlebar')
352 .append($('<a class="crm-dialog-titlebar-print ui-dialog-titlebar-close" title="'+ts('Print window')+'" target="_blank" style="right:3.8em;"/>')
353 .button({icons: {primary: 'fa-print'}, text: false}));
354 }
355 // Add handlers to new or existing dialog
356 if ($(settings.target).data('uiDialog')) {
357 $(settings.target)
358 .on('dialogclose', function() {
359 if (settings.dialog && $(this).attr('data-unsaved-changes') !== 'true') {
360 $(this).crmSnippet('destroy').dialog('destroy').remove();
361 }
362 })
363 .on('crmLoad', function(e, data) {
364 // Set title
365 if (e.target === $(settings.target)[0] && data && !settings.dialog.title && data.title) {
366 $(this).dialog('option', 'title', data.title);
367 }
368 // Update print url
369 $(this).parent().find('a.crm-dialog-titlebar-print').attr('href', $(this).data('civiCrmSnippet')._formatUrl($(this).crmSnippet('option', 'url'), '2'));
370 });
371 }
372 $(settings.target).crmSnippet(settings).crmSnippet('refresh');
373 return $(settings.target);
374 };
375 CRM.loadForm = function(url, options) {
376 var formErrors = [], settings = {
377 crmForm: {
378 ajaxForm: {},
379 autoClose: true,
380 validate: true,
381 refreshAction: ['next_new', 'submit_savenext', 'upload_new'],
382 cancelButton: '.cancel',
383 openInline: 'a.open-inline, a.button, a.action-item, a.open-inline-noreturn',
384 onCancel: function(event) {}
385 }
386 };
387 // Move options that belong to crmForm. Others will be passed through to crmSnippet
388 if (options) $.each(options, function(key, value) {
389 if (typeof(settings.crmForm[key]) !== 'undefined') {
390 settings.crmForm[key] = value;
391 }
392 else {
393 settings[key] = value;
394 }
395 });
396
397 var widget = CRM.loadPage(url, settings).off('.crmForm');
398
399 // CRM-14353 - Warn of unsaved changes for all forms except those which have opted out
400 function cancelAction() {
401 var dirty = CRM.utils.initialValueChanged($('form:not([data-warn-changes=false])', widget));
402 widget.attr('data-unsaved-changes', dirty ? 'true' : 'false');
403 if (dirty) {
404 var id = widget.attr('id') + '-unsaved-alert',
405 title = widget.dialog('option', 'title'),
406 alert = CRM.alert('<p>' + ts('%1 has not been saved.', {1: title}) + '</p><p><a href="#" id="' + id + '">' + ts('Restore') + '</a></p>', ts('Unsaved Changes'), 'alert unsaved-dialog', {expires: 60000});
407 $('#' + id).button({icons: {primary: 'fa-undo'}}).click(function(e) {
408 widget.attr('data-unsaved-changes', 'false').dialog('open');
409 e.preventDefault();
410 });
411 }
412 }
413
414 if (widget.data('uiDialog')) widget.on('dialogbeforeclose', function(e) {
415 // CRM-14353 - Warn unsaved changes if user clicks close button or presses "esc"
416 if (e.originalEvent) {
417 cancelAction();
418 }
419 });
420
421 widget.on('crmFormLoad.crmForm', function(event, data) {
422 var $el = $(this).attr('data-unsaved-changes', 'false'),
423 settings = $el.crmSnippet('option', 'crmForm');
424 if (settings.cancelButton) $(settings.cancelButton, this).click(function(e) {
425 e.preventDefault();
426 var returnVal = settings.onCancel.call($el, e);
427 if (returnVal !== false) {
428 $el.trigger('crmFormCancel', e);
429 if ($el.data('uiDialog') && settings.autoClose) {
430 cancelAction();
431 $el.dialog('close');
432 }
433 else if (!settings.autoClose) {
434 $el.crmSnippet('resetUrl').crmSnippet('refresh');
435 }
436 }
437 });
438 if (settings.validate) {
439 $("form", this).crmValidate();
440 }
441 $("form:not('[data-no-ajax-submit=true]')", this).ajaxForm($.extend({
442 url: data.url.replace(/reset=1[&]?/, ''),
443 dataType: 'json',
444 success: function(response) {
445 if (response.content === undefined) {
446 $el.trigger('crmFormSuccess', response);
447 // Reset form for e.g. "save and new"
448 if (response.userContext && (response.status === 'redirect' || (settings.refreshAction && $.inArray(response.buttonName, settings.refreshAction) >= 0))) {
449 // Force reset of original url
450 $el.data('civiCrmSnippet')._originalUrl = response.userContext;
451 $el.crmSnippet('resetUrl').crmSnippet('refresh');
452 }
453 // Close if we are on the original url or the action was "delete" (in which case returning to view may be inappropriate)
454 else if ($el.data('uiDialog') && (settings.autoClose || response.action === 8)) {
455 $el.dialog('close');
456 }
457 else if (settings.autoClose === false) {
458 $el.crmSnippet('resetUrl').crmSnippet('refresh');
459 }
460 }
461 else {
462 if ($el.crmSnippet('option', 'block')) $el.unblock();
463 response.url = data.url;
464 $el.html(response.content).trigger('crmLoad', response).trigger('crmFormLoad', response);
465 if (response.status === 'form_error') {
466 formErrors = [];
467 $el.trigger('crmFormError', response);
468 $.each(response.errors || [], function(formElement, msg) {
469 formErrors.push($('[name="'+formElement+'"]', $el).crmError(msg));
470 });
471 }
472 }
473 },
474 beforeSubmit: function(submission) {
475 $.each(formErrors, function() {
476 if (this && this.close) this.close();
477 });
478 if ($el.crmSnippet('option', 'block')) $el.block();
479 $el.trigger('crmFormSubmit', submission);
480 }
481 }, settings.ajaxForm));
482 if (settings.openInline) {
483 settings.autoClose = $el.crmSnippet('isOriginalUrl');
484 $(this).off('.openInline').on('click.openInline', settings.openInline, function(e) {
485 if ($(this).is(exclude + ', .crm-popup')) {
486 return;
487 }
488 if ($(this).hasClass('open-inline-noreturn')) {
489 // Force reset of original url
490 $el.data('civiCrmSnippet')._originalUrl = $(this).attr('href');
491 }
492 $el.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
493 e.preventDefault();
494 });
495 }
496 if ($el.data('uiDialog')) {
497 // Show form buttons as part of the dialog
498 var buttonContainers = '.crm-submit-buttons, .action-link',
499 buttons = [],
500 added = [];
501 $(buttonContainers, $el).find('.crm-form-submit, .crm-form-xbutton, a.button, button').each(function() {
502 var $el = $(this),
503 label = $el.is('input') ? $el.attr('value') : $el.text(),
504 identifier = $el.attr('name') || $el.attr('href');
505 if (!identifier || identifier === '#' || $.inArray(identifier, added) < 0) {
506 var $icon = $el.find('.icon, .crm-i'),
507 button = {'data-identifier': identifier, text: label, click: function() {
508 $el[0].click();
509 }};
510 if ($icon.length) {
511 button.icons = {primary: $icon.attr('class')};
512 } else {
513 var action = $el.attr('crm-icon') || ($el.hasClass('cancel') ? 'fa-times' : 'fa-check');
514 button.icons = {primary: action};
515 }
516 buttons.push(button);
517 added.push(identifier);
518 }
519 // display:none causes the form to not submit when pressing "enter"
520 $el.parents(buttonContainers).css({height: 0, padding: 0, margin: 0, overflow: 'hidden'});
521 });
522 $el.dialog('option', 'buttons', buttons);
523 }
524 // Allow a button to prevent ajax submit
525 $('input[data-no-ajax-submit=true], button[data-no-ajax-submit=true]').click(function() {
526 $(this).closest('form').ajaxFormUnbind();
527 });
528 // For convenience, focus the first field
529 $('input[type=text], textarea, select', this).filter(':visible').first().not('.dateplugin').focus();
530 });
531 return widget;
532 };
533 /**
534 * Handler for jQuery click event e.g. $('a').click(CRM.popup);
535 */
536 CRM.popup = function(e) {
537 var $el = $(this).first(),
538 url = $el.attr('href'),
539 popup = $el.data('popup-type') === 'page' ? CRM.loadPage : CRM.loadForm,
540 settings = $el.data('popup-settings') || {},
541 formData = false;
542 settings.dialog = settings.dialog || {};
543 if (e.isDefaultPrevented() || !CRM.config.ajaxPopupsEnabled || !url || $el.is(exclude + ', .open-inline, .open-inline-noreturn')) {
544 return;
545 }
546 // Sized based on css class
547 if ($el.hasClass('small-popup')) {
548 settings.dialog.width = 400;
549 settings.dialog.height = 300;
550 }
551 else if ($el.hasClass('medium-popup')) {
552 settings.dialog.width = settings.dialog.height = '50%';
553 }
554 var dialog = popup(url, settings);
555 // Trigger events from the dialog on the original link element
556 $el.trigger('crmPopupOpen', [dialog]);
557 // Listen for success events and buffer them so we only trigger once
558 dialog.on('crmFormSuccess.crmPopup crmPopupFormSuccess.crmPopup', function(e, data) {
559 formData = data;
560 });
561 dialog.on('dialogclose.crmPopup', function(e, data) {
562 if (formData) {
563 $el.trigger('crmPopupFormSuccess', [dialog, formData]);
564 }
565 $el.trigger('crmPopupClose', [dialog, data]);
566 });
567 e.preventDefault();
568 };
569 /**
570 * An event callback for CRM.popup or a standalone function to refresh the content around a given element
571 * @param e {event|selector}
572 */
573 CRM.refreshParent = function(e) {
574 // Use e.target if input smells like an event, otherwise assume it's a jQuery selector
575 var $el = (e.stopPropagation && e.target) ? $(e.target) : $(e),
576 $table = $el.closest('.dataTable');
577 // Call native refresh method on ajax datatables
578 if ($table.length && $.fn.DataTable.fnIsDataTable($table[0]) && $table.dataTable().fnSettings().sAjaxSource) {
579 // Refresh ALL datatables - needed for contact relationship tab
580 $.each($.fn.dataTable.fnTables(), function() {
581 if ($(this).dataTable().fnSettings().sAjaxSource) $(this).unblock().dataTable().fnDraw();
582 });
583 }
584 // Otherwise refresh the nearest crmSnippet
585 else {
586 $el.closest('.crm-ajax-container, #crm-main-content-wrapper').crmSnippet().crmSnippet('refresh');
587 }
588 };
589
590 $(function($) {
591 $('body')
592 .on('click', 'a.crm-popup', CRM.popup)
593 // Close unsaved dialog messages
594 .on('dialogopen', function(e) {
595 $('.alert.unsaved-dialog .ui-notify-cross', '#crm-notification-container').click();
596 })
597 // Destroy old unsaved dialog
598 .on('dialogcreate', function(e) {
599 $('.ui-dialog-content.crm-ajax-container:hidden[data-unsaved-changes=true]').crmSnippet('destroy').dialog('destroy').remove();
600 })
601 // Ensure wysiwyg content is updated prior to ajax submit
602 .on('form-pre-serialize', function(e) {
603 $('.crm-wysiwyg-enabled', e.target).each(function() {
604 CRM.wysiwyg.updateElement(this);
605 });
606 })
607 // Auto-resize dialogs when loading content
608 .on('crmLoad dialogopen', 'div.ui-dialog.ui-resizable.crm-container', function(e) {
609 var
610 $wrapper = $(this),
611 $dialog = $wrapper.children('.ui-dialog-content');
612 // small delay to allow contents to render
613 window.setTimeout(function() {
614 var currentHeight = $wrapper.outerHeight(),
615 padding = currentHeight - $dialog.height(),
616 newHeight = $dialog.prop('scrollHeight') + padding,
617 menuHeight = $('#civicrm-menu').outerHeight();
618 if ($('body').hasClass('crm-menubar-below-cms-menu')) {
619 menuHeight += $('#civicrm-menu').offset().top;
620 }
621 var maxHeight = $(window).height() - menuHeight;
622 newHeight = newHeight > maxHeight ? maxHeight : newHeight;
623 if (newHeight > (currentHeight + 15)) {
624 $dialog.dialog('option', {
625 position: {my: 'center', at: 'center center+' + (menuHeight / 2), of: window},
626 height: newHeight
627 });
628 }
629 }, 500);
630 });
631 });
632
633 }(jQuery, CRM, _));