Merge pull request #4126 from totten/4.5-wpcli-explr
[civicrm-core.git] / templates / CRM / Admin / Page / APIExplorer.js
1 (function($, _, undefined) {
2 var
3 entity,
4 action,
5 actions = ['get'],
6 fields = [],
7 options = {},
8 params = {},
9 smartyStub,
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());
14
15 /**
16 * Call prettyPrint function if it successfully loaded from the cdn
17 */
18 function prettyPrint() {
19 if (window.prettyPrint) {
20 window.prettyPrint();
21 }
22 }
23
24 /**
25 * Add a "fields" row
26 * @param name
27 */
28 function addField(name) {
29 $('#api-params').append($(fieldTpl({name: name || ''})));
30 var $row = $('tr:last-child', '#api-params');
31 $('.api-param-name', $row).crmSelect2({
32 data: fields.concat({id: '-', text: ts('Other') + '...'})
33 }).change();
34 }
35
36 /**
37 * Add a new "options" row
38 * @param name
39 */
40 function addOptionField(name) {
41 if ($('.api-options-row', '#api-params').length) {
42 $('.api-options-row:last', '#api-params').after($(optionsTpl({})));
43 } else {
44 $('#api-params').append($(optionsTpl({})));
45 }
46 var $row = $('.api-options-row:last', '#api-params');
47 $('.api-option-name', $row).crmSelect2({data: [
48 {id: 'limit', text: 'limit'},
49 {id: 'offset', text: 'offset'},
50 {id: 'sort', text: 'sort'},
51 {id: 'metadata', text: 'metadata'},
52 {id: '-', text: ts('Other') + '...'}
53 ]});
54 }
55
56 /**
57 * Add an "api chain" row
58 */
59 function addChainField() {
60 $('#api-params').append($(chainTpl({})));
61 var $row = $('tr:last-child', '#api-params');
62 $('.api-chain-entity', $row).crmSelect2({
63 formatSelection: function(item) {
64 return '<span class="icon ui-icon-link"></span> API ' + item.text;
65 },
66 placeholder: '<span class="icon ui-icon-link"></span> ' + ts('Entity'),
67 escapeMarkup: function(m) {return m}
68 });
69 }
70
71 /**
72 * Fetch fields for entity+action
73 */
74 function getFields() {
75 var required = [];
76 fields = [];
77 options = {};
78 // Special case for getfields
79 if (action === 'getfields') {
80 fields.push({
81 id: 'api_action',
82 text: 'Action'
83 });
84 options.api_action = [];
85 $('option', '#api-action').each(function() {
86 if (this.value) {
87 options.api_action.push({key: this.value, value: $(this).text()});
88 }
89 });
90 showFields(['api_action']);
91 return;
92 }
93 CRM.api3(entity, 'getFields', {'api_action': action, sequential: 1, options: {get_options: 'all'}}).done(function(data) {
94 _.each(data.values, function(field) {
95 if (field.name) {
96 fields.push({
97 id: field.name,
98 text: field.title || field.name,
99 required: field['api.required'] || false
100 });
101 if (field['api.required']) {
102 required.push(field.name);
103 }
104 if (field.options) {
105 options[field.name] = field.options;
106 }
107 }
108 });
109 showFields(required);
110 if (action === 'get' || action === 'getsingle') {
111 showReturn();
112 }
113 });
114 }
115
116 /**
117 * For "get" actions show the "return" options
118 */
119 function showReturn() {
120 $('#api-params').prepend($(returnTpl({})));
121 $('#api-return-value').crmSelect2({data: fields, multiple: true});
122 }
123
124 /**
125 * Fetch actions for entity
126 */
127 function getActions() {
128 if (entity) {
129 CRM.api3(entity, 'getactions').done(function(data) {
130 actions = data.values || ['get'];
131 populateActions();
132 });
133 } else {
134 actions = ['get'];
135 populateActions();
136 }
137 }
138
139 /**
140 * Called after getActions to populate action list
141 * @param el
142 */
143 function populateActions(el) {
144 var val = $('#api-action').val();
145 $('#api-action').select2({
146 data: _.transform(actions, function(ret, item) {ret.push({text: item, id: item})})
147 });
148 // If previously selected action is not available, set it to 'get' if possible
149 if (_.indexOf(actions, val) < 0) {
150 $('#api-action').select2('val', _.indexOf(actions, 'get') < 0 ? actions[0] : 'get', true);
151 }
152 }
153
154 /**
155 * Called after getfields to show buttons and required fields
156 * @param required
157 */
158 function showFields(required) {
159 $('#api-params').empty();
160 $('#api-param-buttons').show();
161 if (required.length) {
162 _.each(required, addField);
163 } else {
164 addField();
165 }
166 }
167
168 /**
169 * Add/remove option list for selected field's pseudoconstant
170 */
171 function toggleOptions() {
172 var name = $(this).val(),
173 $valField = $(this).closest('tr').find('.api-param-value');
174 if (options[name]) {
175 $valField.val('').select2({
176 multiple: true,
177 data: _.transform(options[name], function(result, option) {
178 result.push({id: option.key, text: option.value});
179 })
180 });
181 }
182 else if ($valField.data('select2')) {
183 $valField.select2('destroy');
184 }
185 }
186
187 /**
188 * Attempt to parse a string into a value of the intended type
189 * @param val string
190 * @param makeArray bool
191 */
192 function evaluate(val, makeArray) {
193 try {
194 if (!val.length) {
195 return val;
196 }
197 var first = val.charAt(0),
198 last = val.slice(-1);
199 // Simple types
200 if (val === 'true' || val === 'false' || val === 'null' || !isNaN(val)) {
201 return eval(val);
202 }
203 // Quoted strings
204 if ((first === '"' || first === "'") && last === first) {
205 return val.slice(1, -1);
206 }
207 // Parse json
208 if ((first === '[' && last === ']') || (first === '{' && last === '}')) {
209 return eval('(' + val + ')');
210 }
211 // Transform csv to array
212 if (makeArray && val.indexOf(',') > 0) {
213 return val.split(',');
214 }
215 // Ok ok it's really a string
216 return val;
217 } catch(e) {
218 // If eval crashed return undefined
219 return undefined;
220 }
221 }
222
223 /**
224 * Format value to look like php code
225 * @param val
226 */
227 function phpFormat(val) {
228 var ret = '';
229 if ($.isPlainObject(val)) {
230 $.each(val, function(k, v) {
231 ret += (ret ? ', ' : '') + "'" + k + "' => " + phpFormat(v);
232 });
233 return 'array(' + ret + ')';
234 }
235 if ($.isArray(val)) {
236 $.each(val, function(k, v) {
237 ret += (ret ? ', ' : '') + phpFormat(v);
238 });
239 return 'array(' + ret + ')';
240 }
241 return JSON.stringify(val).replace(/\$/g, '\\$');
242 }
243
244 /**
245 * Smarty doesn't support array literals so we provide a stub
246 * @param js string
247 */
248 function smartyFormat(js, key) {
249 if (js.indexOf('[') > -1 || js.indexOf('{') > -1) {
250 smartyStub = true;
251 return '$' + key.replace(/[. -]/g, '_');
252 }
253 return js;
254 }
255
256 /**
257 * Create the params array from user input
258 * @param e
259 */
260 function buildParams(e) {
261 params = {};
262 $('.api-param-checkbox:checked').each(function() {
263 params[this.name] = 1;
264 });
265 $('input.api-param-value, input.api-option-value').each(function() {
266 var $row = $(this).closest('tr'),
267 val = evaluate($(this).val(), $(this).is('.select2-offscreen')),
268 name = $('input.api-param-name', $row).val(),
269 op = $('select.api-param-op', $row).val() || '=';
270
271 // Ignore blank values for the return field
272 if ($(this).is('#api-return-value') && !val) {
273 return;
274 }
275 // Special syntax for api chaining
276 if (!name && $('select.api-chain-entity', $row).val()) {
277 name = 'api.' + $('select.api-chain-entity', $row).val() + '.' + $('select.api-chain-action', $row).val();
278 }
279 // Special handling for options
280 if ($(this).is('.api-option-value')) {
281 op = $('input.api-option-name', $row).val();
282 if (op) {
283 name = 'options';
284 }
285 }
286 if (name && val !== undefined) {
287 params[name] = op === '=' ? val : (params[name] || {});
288 if (op !== '=') {
289 params[name][op] = val;
290 }
291 if ($(this).hasClass('crm-error')) {
292 clearError(this);
293 }
294 }
295 else if (name && (!e || e.type !== 'keyup')) {
296 setError(this);
297 }
298 });
299 if (entity && action) {
300 formatQuery();
301 }
302 }
303
304 function setError(el) {
305 if (!$(el).hasClass('crm-error')) {
306 var msg = ts('Syntax error: input should be valid JSON or a quoted string.');
307 $(el)
308 .addClass('crm-error')
309 .css('width', '82%')
310 .attr('title', msg)
311 .before('<div class="icon red-icon ui-icon-alert" title="'+msg+'"/>')
312 .tooltip();
313 }
314 }
315
316 function clearError(el) {
317 $(el)
318 .removeClass('crm-error')
319 .attr('title', '')
320 .css('width', '85%')
321 .tooltip('destroy')
322 .siblings('.ui-icon-alert').remove();
323 }
324
325 function formatQuery() {
326 var i = 0, q = {
327 smarty: "{crmAPI var='result' entity='" + entity + "' action='" + action + "'",
328 php: "$result = civicrm_api3('" + entity + "', '" + action + "'",
329 json: "CRM.api3('" + entity + "', '" + action + "'",
330 drush: "drush cvapi " + entity + '.' + action + ' ',
331 wpcli: "wp cv api " + entity + '.' + action + ' ',
332 rest: CRM.config.resourceBase + "extern/rest.php?entity=" + entity + "&action=" + action + "&json=" + JSON.stringify(params) + "&api_key=yoursitekey&key=yourkey"
333 };
334 smartyStub = false;
335 $.each(params, function(key, value) {
336 var js = JSON.stringify(value);
337 if (!i++) {
338 q.php += ", array(\n";
339 q.json += ", {\n";
340 } else {
341 q.json += ",\n";
342 }
343 q.php += " '" + key + "' => " + phpFormat(value) + ",\n";
344 q.json += " \"" + key + '": ' + js;
345 q.smarty += ' ' + key + '=' + smartyFormat(js, key);
346 q.drush += key + '=' + js + ' ';
347 q.wpcli += key + '=' + js + ' ';
348 });
349 if (i) {
350 q.php += ")";
351 q.json += "\n}";
352 }
353 q.php += ");";
354 q.json += ").done(function(result) {\n // do something\n});";
355 q.smarty += "}\n{foreach from=$result.values item=" + entity.toLowerCase() + "}\n {$" + entity.toLowerCase() + ".some_field}\n{/foreach}";
356 if (action.indexOf('get') < 0) {
357 q.smarty = '{* Smarty API only works with get actions *}';
358 } else if (smartyStub) {
359 q.smarty = "{* Smarty does not have a syntax for array literals; assign complex variables from php *}\n" + q.smarty;
360 }
361 $.each(q, function(type, val) {
362 $('#api-' + type).removeClass('prettyprinted').text(val);
363 });
364 prettyPrint();
365 }
366
367 function submit(e) {
368 e.preventDefault();
369 if (!entity || !action) {
370 alert(ts('Select an entity.'));
371 return;
372 }
373 if (action.indexOf('get') < 0 && action != 'check') {
374 var msg = action === 'delete' ? ts('This will delete data from CiviCRM. Are you sure?') : ts('This will write to the database. Continue?');
375 CRM.confirm({title: ts('Confirm %1', {1: action}), message: msg}).on('crmConfirm:yes', execute);
376 } else {
377 execute();
378 }
379 }
380
381 function execute() {
382 $('#api-result').html('<div class="crm-loading-element"></div>');
383 $.ajax({
384 url: CRM.url('civicrm/ajax/rest'),
385 data: {
386 entity: entity,
387 action: action,
388 prettyprint: 1,
389 json: JSON.stringify(params)
390 },
391 type: action.indexOf('get') < 0 ? 'POST' : 'GET',
392 dataType: 'text'
393 }).done(function(text) {
394 $('#api-result').addClass('prettyprint').removeClass('prettyprinted').text(text);
395 prettyPrint();
396 });
397 }
398
399 $(document).ready(function() {
400 $('form#api-explorer')
401 .on('change', '#api-entity, #api-action', function() {
402 entity = $('#api-entity').val();
403 if ($(this).is('#api-entity')) {
404 getActions();
405 }
406 action = $('#api-action').val();
407 if (entity && action) {
408 $('#api-params').html('<tr><td colspan="4" class="crm-loading-element"></td></tr>');
409 $('#api-params-table thead').show();
410 getFields();
411 buildParams();
412 } else {
413 $('#api-params, #api-generated pre').empty();
414 $('#api-param-buttons, #api-params-table thead').hide();
415 }
416 })
417 .on('change keyup', 'input.api-input, #api-params select', buildParams)
418 .on('submit', submit);
419 $('#api-params')
420 .on('change', '.api-param-name', toggleOptions)
421 .on('change', '.api-param-name, .api-option-name', function() {
422 if ($(this).val() === '-') {
423 $(this).select2('destroy');
424 $(this).val('').focus();
425 }
426 })
427 .on('click', '.api-param-remove', function(e) {
428 e.preventDefault();
429 $(this).closest('tr').remove();
430 buildParams();
431 });
432 $('#api-params-add').on('click', function(e) {
433 e.preventDefault();
434 addField();
435 });
436 $('#api-option-add').on('click', function(e) {
437 e.preventDefault();
438 addOptionField();
439 });
440 $('#api-chain-add').on('click', function(e) {
441 e.preventDefault();
442 addChainField();
443 });
444 $('#api-entity').change();
445 });
446 }(CRM.$, CRM._));