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