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