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