Merge remote-tracking branch 'upstream/4.4' into 4.4-4.5-2014-09-01-22-48-29
[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 civicrm-api " + entity + '.' + action + ' ',
331 rest: CRM.config.resourceBase + "extern/rest.php?entity=" + entity + "&action=" + action + "&json=" + JSON.stringify(params) + "&api_key=yoursitekey&key=yourkey"
332 };
333 smartyStub = false;
334 $.each(params, function(key, value) {
335 var js = JSON.stringify(value);
336 if (!i++) {
337 q.php += ", array(\n";
338 q.json += ", {\n";
339 } else {
340 q.json += ",\n";
341 }
342 q.php += " '" + key + "' => " + phpFormat(value) + ",\n";
343 q.json += " \"" + key + '": ' + js;
344 q.smarty += ' ' + key + '=' + smartyFormat(js, key);
345 q.drush += key + '=' + js + ' ';
346 });
347 if (i) {
348 q.php += ")";
349 q.json += "\n}";
350 }
351 q.php += ");";
352 q.json += ").done(function(result) {\n // do something\n});";
353 q.smarty += "}\n{foreach from=$result.values item=" + entity.toLowerCase() + "}\n {$" + entity.toLowerCase() + ".some_field}\n{/foreach}";
354 if (action.indexOf('get') < 0) {
355 q.smarty = '{* Smarty API only works with get actions *}';
356 } else if (smartyStub) {
357 q.smarty = "{* Smarty does not have a syntax for array literals; assign complex variables from php *}\n" + q.smarty;
358 }
359 $.each(q, function(type, val) {
360 $('#api-' + type).removeClass('prettyprinted').text(val);
361 });
362 prettyPrint();
363 }
364
365 function submit(e) {
366 e.preventDefault();
367 if (!entity || !action) {
368 alert(ts('Select an entity.'));
369 return;
370 }
371 if (action.indexOf('get') < 0 && action != 'check') {
372 var msg = action === 'delete' ? ts('This will delete data from CiviCRM. Are you sure?') : ts('This will write to the database. Continue?');
373 CRM.confirm({title: ts('Confirm %1', {1: action}), message: msg}).on('crmConfirm:yes', execute);
374 } else {
375 execute();
376 }
377 }
378
379 function execute() {
380 $('#api-result').html('<div class="crm-loading-element"></div>');
381 $.ajax({
382 url: CRM.url('civicrm/ajax/rest'),
383 data: {
384 entity: entity,
385 action: action,
386 prettyprint: 1,
387 json: JSON.stringify(params)
388 },
389 type: action.indexOf('get') < 0 ? 'POST' : 'GET',
390 dataType: 'text'
391 }).done(function(text) {
392 $('#api-result').addClass('prettyprint').removeClass('prettyprinted').text(text);
393 prettyPrint();
394 });
395 }
396
397 $(document).ready(function() {
398 $('form#api-explorer')
399 .on('change', '#api-entity, #api-action', function() {
400 entity = $('#api-entity').val();
401 if ($(this).is('#api-entity')) {
402 getActions();
403 }
404 action = $('#api-action').val();
405 if (entity && action) {
406 $('#api-params').html('<tr><td colspan="4" class="crm-loading-element"></td></tr>');
407 $('#api-params-table thead').show();
408 getFields();
409 buildParams();
410 } else {
411 $('#api-params, #api-generated pre').empty();
412 $('#api-param-buttons, #api-params-table thead').hide();
413 }
414 })
415 .on('change keyup', 'input.api-input, #api-params select', buildParams)
416 .on('submit', submit);
417 $('#api-params')
418 .on('change', '.api-param-name', toggleOptions)
419 .on('change', '.api-param-name, .api-option-name', function() {
420 if ($(this).val() === '-') {
421 $(this).select2('destroy');
422 $(this).val('').focus();
423 }
424 })
425 .on('click', '.api-param-remove', function(e) {
426 e.preventDefault();
427 $(this).closest('tr').remove();
428 buildParams();
429 });
430 $('#api-params-add').on('click', function(e) {
431 e.preventDefault();
432 addField();
433 });
434 $('#api-option-add').on('click', function(e) {
435 e.preventDefault();
436 addOptionField();
437 });
438 $('#api-chain-add').on('click', function(e) {
439 e.preventDefault();
440 addChainField();
441 });
442 $('#api-entity').change();
443 });
444 }(CRM.$, CRM._));