1 (function($, _
, undefined) {
10 fieldTpl
= _
.template($('#api-param-tpl').html()),
11 optionsTpl
= _
.template($('#api-options-tpl').html()),
12 returnTpl
= _
.template($('#api-return-tpl').html()),
13 chainTpl
= _
.template($('#api-chain-tpl').html()),
15 // Operators with special properties
16 BOOL
= ['IS NULL', 'IS NOT NULL'],
17 TEXT
= ['LIKE', 'NOT LIKE'],
18 MULTI
= ['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'];
21 * Call prettyPrint function if it successfully loaded from the cdn
23 function prettyPrint() {
24 if (window
.prettyPrint
) {
33 function addField(name
) {
34 $('#api-params').append($(fieldTpl({name
: name
|| ''})));
35 var $row
= $('tr:last-child', '#api-params');
36 $('input.api-param-name', $row
).crmSelect2({
37 data
: fields
.concat({id
: '-', text
: ts('Other') + '...'})
42 * Add a new "options" row
45 function addOptionField(name
) {
46 if ($('.api-options-row', '#api-params').length
) {
47 $('.api-options-row:last', '#api-params').after($(optionsTpl({})));
49 $('#api-params').append($(optionsTpl({})));
51 var $row
= $('.api-options-row:last', '#api-params');
52 $('.api-option-name', $row
).crmSelect2({data
: [
53 {id
: 'limit', text
: 'limit'},
54 {id
: 'offset', text
: 'offset'},
55 {id
: 'sort', text
: 'sort'},
56 {id
: 'metadata', text
: 'metadata'},
57 {id
: '-', text
: ts('Other') + '...'}
62 * Add an "api chain" row
64 function addChainField() {
65 $('#api-params').append($(chainTpl({})));
66 var $row
= $('tr:last-child', '#api-params');
67 $('.api-chain-entity', $row
).crmSelect2({
68 formatSelection: function(item
) {
69 return '<span class="icon ui-icon-link"></span> API ' + item
.text
;
71 placeholder
: '<span class="icon ui-icon-link"></span> ' + ts('Entity'),
72 escapeMarkup: function(m
) {return m
}
77 * Fetch fields for entity+action
79 function getFields() {
83 // Special case for getfields
84 if (action
=== 'getfields') {
89 options
.api_action
= _
.transform(actions
, function(ret
, item
) {ret
.push({value
: item
, key
: item
})});
90 showFields(['api_action']);
93 CRM
.api3(entity
, 'getFields', {'api_action': action
, sequential
: 1, options
: {get_options
: 'all'}}).done(function(data
) {
94 _
.each(data
.values
, function(field
) {
98 text
: field
.title
|| field
.name
,
99 required
: field
['api.required'] || false
101 if (field
['api.required']) {
102 required
.push(field
.name
);
105 options
[field
.name
] = field
.options
;
109 showFields(required
);
110 if (action
=== 'get' || action
=== 'getsingle') {
117 * For "get" actions show the "return" options
119 function showReturn() {
120 $('#api-params').prepend($(returnTpl({})));
121 $('#api-return-value').crmSelect2({data
: fields
, multiple
: true});
125 * Fetch actions for entity
127 function getActions() {
129 $('#api-action').addClass('loading');
130 CRM
.api3(entity
, 'getactions').done(function(data
) {
131 actions
= data
.values
|| ['get'];
141 * Called after getActions to populate action list
144 function populateActions(el
) {
145 var val
= $('#api-action').val();
146 $('#api-action').removeClass('loading').select2({
147 data
: _
.transform(actions
, function(ret
, item
) {ret
.push({text
: item
, id
: item
})})
149 // If previously selected action is not available, set it to 'get' if possible
150 if (_
.indexOf(actions
, val
) < 0) {
151 $('#api-action').select2('val', _
.indexOf(actions
, 'get') < 0 ? actions
[0] : 'get', true);
156 * Called after getfields to show buttons and required fields
159 function showFields(required
) {
160 $('#api-params').empty();
161 $('#api-param-buttons').show();
162 if (required
.length
) {
163 _
.each(required
, addField
);
170 * Render value input as a textfield, option list, or hidden,
171 * Depending on selected param name and operator
173 function renderValueField() {
174 var $row
= $(this).closest('tr'),
175 name
= $('input.api-param-name', $row
).val(),
176 operator
= $('.api-param-op', $row
).val(),
177 operatorType
= $.inArray(operator
, MULTI
) > -1 ? 'multi' : ($.inArray(operator
, BOOL
) > -1 ? 'bool' : 'single'),
178 $valField
= $('input.api-param-value', $row
),
179 currentVal
= $valField
.val();
180 // Boolean fields only have 1 possible value
181 if (operatorType
== 'bool') {
182 if ($valField
.data('select2')) {
183 $valField
.select2('destroy');
185 $valField
.css('visibility', 'hidden').val('1');
188 $valField
.css('visibility', '');
190 if (options
[name
] && $.inArray(operator
, TEXT
) < 0) {
191 // Reset value before switching to a select from something else
192 if ($(this).is('.api-param-name') || !$valField
.data('select2')) {
195 // When switching from multi-select to single select
196 else if (operatorType
== 'single' && currentVal
.indexOf(',') > -1) {
197 $valField
.val(currentVal
.split(',')[0]);
200 multiple
: (operatorType
=== 'multi'),
201 data
: _
.transform(options
[name
], function(result
, option
) {
202 result
.push({id
: option
.key
, text
: option
.value
});
208 if ($valField
.data('select2')) {
209 $valField
.select2('destroy');
214 * Attempt to parse a string into a value of the intended type
216 * @param makeArray bool
218 function evaluate(val
, makeArray
) {
221 return makeArray
? [] : '';
223 var first
= val
.charAt(0),
224 last
= val
.slice(-1);
226 if (val
=== 'true' || val
=== 'false' || val
=== 'null') {
230 if ((first
=== '"' || first
=== "'") && last
=== first
) {
231 return val
.slice(1, -1);
234 if ((first
=== '[' && last
=== ']') || (first
=== '{' && last
=== '}')) {
235 return eval('(' + val
+ ')');
237 // Transform csv to array
240 $.each(val
.split(','), function(k
, v
) {
241 result
.push(evaluate($.trim(v
)) || v
);
245 // Integers - quote any number that starts with 0 to avoid oddities
246 if (!isNaN(val
) && val
.search(/[^\d]/) < 0 && (val
.length
=== 1 || first
!== '0')) {
247 return parseInt(val
, 10);
249 // Ok ok it's really a string
252 // If eval crashed return undefined
258 * Format value to look like php code
261 function phpFormat(val
) {
263 if ($.isPlainObject(val
)) {
264 $.each(val
, function(k
, v
) {
265 ret
+= (ret
? ', ' : '') + "'" + k
+ "' => " + phpFormat(v
);
267 return 'array(' + ret
+ ')';
269 if ($.isArray(val
)) {
270 $.each(val
, function(k
, v
) {
271 ret
+= (ret
? ', ' : '') + phpFormat(v
);
273 return 'array(' + ret
+ ')';
275 return JSON
.stringify(val
).replace(/\$/g, '\\$');
279 * Smarty doesn't support array literals so we provide a stub
282 function smartyFormat(js
, key
) {
283 if (js
.indexOf('[') > -1 || js
.indexOf('{') > -1) {
285 return '$' + key
.replace(/[. -]/g, '_');
291 * Create the params array from user input
294 function buildParams(e
) {
296 $('.api-param-checkbox:checked').each(function() {
297 params
[this.name
] = 1;
299 $('input.api-param-value, input.api-option-value').each(function() {
300 var $row
= $(this).closest('tr'),
301 op
= $('select.api-param-op', $row
).val() || '=',
302 name
= $('input.api-param-name', $row
).val(),
303 val
= evaluate($(this).val(), $.inArray(op
, MULTI
) > -1);
305 // Ignore blank values for the return field
306 if ($(this).is('#api-return-value') && !val
) {
309 // Special syntax for api chaining
310 if (!name
&& $('select.api-chain-entity', $row
).val()) {
311 name
= 'api.' + $('select.api-chain-entity', $row
).val() + '.' + $('select.api-chain-action', $row
).val();
313 // Special handling for options
314 if ($(this).is('.api-option-value')) {
315 op
= $('input.api-option-name', $row
).val();
320 if (name
&& val
!== undefined) {
321 params
[name
] = op
=== '=' ? val
: (params
[name
] || {});
323 params
[name
][op
] = val
;
325 if ($(this).hasClass('crm-error')) {
329 else if (name
&& (!e
|| e
.type
!== 'keyup')) {
333 if (entity
&& action
) {
338 function setError(el
) {
339 if (!$(el
).hasClass('crm-error')) {
340 var msg
= ts('Syntax error: input should be valid JSON or a quoted string.');
342 .addClass('crm-error')
345 .before('<div class="icon red-icon ui-icon-alert" title="'+msg
+'"/>')
350 function clearError(el
) {
352 .removeClass('crm-error')
356 .siblings('.ui-icon-alert').remove();
359 function formatQuery() {
361 smarty
: "{crmAPI var='result' entity='" + entity
+ "' action='" + action
+ "'",
362 php
: "$result = civicrm_api3('" + entity
+ "', '" + action
+ "'",
363 json
: "CRM.api3('" + entity
+ "', '" + action
+ "'",
364 drush
: "drush cvapi " + entity
+ '.' + action
+ ' ',
365 wpcli
: "wp cv api " + entity
+ '.' + action
+ ' ',
366 rest
: CRM
.config
.resourceBase
+ "extern/rest.php?entity=" + entity
+ "&action=" + action
+ "&json=" + JSON
.stringify(params
) + "&api_key=yoursitekey&key=yourkey"
369 $.each(params
, function(key
, value
) {
370 var js
= JSON
.stringify(value
);
372 q
.php
+= ", array(\n";
377 q
.php
+= " '" + key
+ "' => " + phpFormat(value
) + ",\n";
378 q
.json
+= " \"" + key
+ '": ' + js
;
379 q
.smarty
+= ' ' + key
+ '=' + smartyFormat(js
, key
);
380 // FIXME: This is not totally correct cli syntax
381 q
.drush
+= key
+ '=' + js
+ ' ';
382 q
.wpcli
+= key
+ '=' + js
+ ' ';
389 q
.json
+= ").done(function(result) {\n // do something\n});";
390 q
.smarty
+= "}\n{foreach from=$result.values item=" + entity
.toLowerCase() + "}\n {$" + entity
.toLowerCase() + ".some_field}\n{/foreach}";
391 if (action
.indexOf('get') < 0) {
392 q
.smarty
= '{* Smarty API only works with get actions *}';
393 } else if (smartyStub
) {
394 q
.smarty
= "{* Smarty does not have a syntax for array literals; assign complex variables from php *}\n" + q
.smarty
;
396 $.each(q
, function(type
, val
) {
397 $('#api-' + type
).removeClass('prettyprinted').text(val
);
404 if (!entity
|| !action
) {
405 alert(ts('Select an entity.'));
408 if (action
.indexOf('get') < 0 && action
!= 'check') {
409 var msg
= action
=== 'delete' ? ts('This will delete data from CiviCRM. Are you sure?') : ts('This will write to the database. Continue?');
410 CRM
.confirm({title
: ts('Confirm %1', {1: action
}), message
: msg
}).on('crmConfirm:yes', execute
);
417 * Execute api call and display the results
418 * Note: We have to manually execute the ajax in order to add the secret extra "prettyprint" param
421 $('#api-result').html('<div class="crm-loading-element"></div>');
423 url
: CRM
.url('civicrm/ajax/rest'),
428 json
: JSON
.stringify(params
)
430 type
: action
.indexOf('get') < 0 ? 'POST' : 'GET',
432 }).done(function(text
) {
433 $('#api-result').addClass('prettyprint').removeClass('prettyprinted').text(text
);
438 $(document
).ready(function() {
439 $('form#api-explorer')
440 .on('change', '#api-entity, #api-action', function() {
441 entity
= $('#api-entity').val();
442 if ($(this).is('#api-entity')) {
445 action
= $('#api-action').val();
446 if (entity
&& action
) {
447 $('#api-params').html('<tr><td colspan="4" class="crm-loading-element"></td></tr>');
448 $('#api-params-table thead').show();
452 $('#api-params, #api-generated pre').empty();
453 $('#api-param-buttons, #api-params-table thead').hide();
456 .on('change keyup', 'input.api-input, #api-params select', buildParams
)
457 .on('submit', submit
);
459 .on('change', 'input.api-param-name, select.api-param-op', renderValueField
)
460 .on('change', 'input.api-param-name, .api-option-name', function() {
461 if ($(this).val() === '-') {
462 $(this).select2('destroy');
463 $(this).val('').focus();
466 .on('click', '.api-param-remove', function(e
) {
468 $(this).closest('tr').remove();
471 $('#api-params-add').on('click', function(e
) {
475 $('#api-option-add').on('click', function(e
) {
479 $('#api-chain-add').on('click', function(e
) {
483 $('#api-entity').change();