1 (function(angular
, $, _
, undefined) {
4 var schema
= CRM
.vars
.api4
.schema
;
6 var links
= CRM
.vars
.api4
.links
;
7 // Cache list of entities
9 // Cache list of actions
12 var fieldOptions
= {};
17 angular
.module('api4Explorer').config(function($routeProvider
) {
18 $routeProvider
.when('/explorer/:api4entity?/:api4action?', {
19 controller
: 'Api4Explorer',
20 templateUrl
: '~/api4Explorer/Explorer.html',
25 angular
.module('api4Explorer').controller('Api4Explorer', function($scope
, $routeParams
, $location
, $timeout
, $http
, crmUiHelp
, crmApi4
, dialogService
) {
26 var ts
= $scope
.ts
= CRM
.ts(),
27 ctrl
= $scope
.$ctrl
= this;
28 $scope
.entities
= entities
;
29 $scope
.actions
= actions
;
31 $scope
.havingOptions
= [];
32 $scope
.fieldsAndJoins
= [];
33 $scope
.fieldsAndJoinsAndFunctions
= [];
34 $scope
.fieldsAndJoinsAndFunctionsWithSuffixes
= [];
35 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
= [];
36 $scope
.availableParams
= {};
37 params
= $scope
.params
= {};
39 $scope
.selectedTab
= {result
: 'result', code
: 'php'};
41 accessDebugOutput
: CRM
.checkPerm('access debug output'),
42 editGroups
: CRM
.checkPerm('edit groups')
44 marked
.setOptions({highlight
: prettyPrintOne
});
45 var getMetaParams
= {},
46 objectParams
= {orderBy
: 'ASC', values
: '', defaults
: '', chain
: ['Entity', '', '{}']},
47 docs
= CRM
.vars
.api4
.docs
,
50 $scope
.helpTitle
= '';
51 $scope
.helpContent
= {};
52 $scope
.entity
= $routeParams
.api4entity
;
55 $scope
.status
= 'default';
56 $scope
.loading
= false;
58 $scope
.langs
= ['php', 'js', 'ang', 'cli'];
59 $scope
.joinTypes
= [{k
: 'LEFT', v
: 'LEFT JOIN'}, {k
: 'INNER', v
: 'INNER JOIN'}, {k
: 'EXCLUDE', v
: 'EXCLUDE'}];
60 $scope
.bridgeEntities
= _
.filter(schema
, function(entity
) {return _
.includes(entity
.type
, 'EntityBridge');});
63 {name
: 'oop', label
: ts('OOP Style'), code
: ''},
64 {name
: 'php', label
: ts('Traditional'), code
: ''}
67 {name
: 'js', label
: ts('Single Call'), code
: ''},
68 {name
: 'js2', label
: ts('Batch Calls'), code
: ''}
71 {name
: 'ang', label
: ts('Single Call'), code
: ''},
72 {name
: 'ang2', label
: ts('Batch Calls'), code
: ''}
75 {name
: 'short', label
: ts('CV (short)'), code
: ''},
76 {name
: 'long', label
: ts('CV (long)'), code
: ''},
77 {name
: 'pipe', label
: ts('CV (pipe)'), code
: ''}
81 if (!entities
.length
) {
82 formatForSelect2(schema
, entities
, 'name', ['description', 'icon']);
91 function ucfirst(str
) {
92 return str
[0].toUpperCase() + str
.slice(1);
95 function lcfirst(str
) {
96 return str
[0].toLowerCase() + str
.slice(1);
99 function pluralize(str
) {
100 var lastLetter
= str
[str
.length
- 1],
101 lastTwo
= str
[str
.length
- 2] + lastLetter
;
102 if (lastLetter
=== 's' || lastLetter
=== 'x' || lastTwo
=== 'ch') {
105 if (lastLetter
=== 'y' && !_
.includes(['ay', 'ey', 'iy', 'oy', 'uy'], lastTwo
)) {
106 return str
.slice(0, -1) + 'ies';
111 // Reformat an existing array of objects for compatibility with select2
112 function formatForSelect2(input
, container
, key
, extra
, prefix
) {
113 _
.each(input
, function(item
) {
114 var id
= (prefix
|| '') + item
[key
];
115 var formatted
= {id
: id
, text
: id
};
117 _
.merge(formatted
, _
.pick(item
, extra
));
119 container
.push(formatted
);
124 // Replaces contents of fieldList array with current fields formatted for select2
125 function getFieldList(fieldList
, action
, addPseudoconstant
) {
126 var fieldInfo
= _
.cloneDeep(_
.findWhere(getEntity().actions
, {name
: action
}).fields
);
127 fieldList
.length
= 0;
128 if (addPseudoconstant
) {
129 addPseudoconstants(fieldInfo
, addPseudoconstant
);
131 formatForSelect2(fieldInfo
, fieldList
, 'name', ['description', 'required', 'default_value']);
134 // Note: this function expects fieldList to be select2-formatted already
135 function addJoins(fieldList
, addWildcard
, addPseudoconstant
) {
136 // Add entities specified by the join param
137 _
.each(getExplicitJoins(), function(joinEntity
, joinAlias
) {
138 var wildCard
= addWildcard
? [{id
: joinAlias
+ '.*', text
: joinAlias
+ '.*', 'description': 'All core ' + joinEntity
+ ' fields'}] : [],
139 joinFields
= _
.cloneDeep(entityFields(joinEntity
));
141 if (addPseudoconstant
) {
142 addPseudoconstants(joinFields
, addPseudoconstant
);
145 text
: joinEntity
+ ' AS ' + joinAlias
,
146 description
: 'Explicit join to ' + joinEntity
,
147 children
: wildCard
.concat(formatForSelect2(joinFields
, [], 'name', ['description'], joinAlias
+ '.'))
151 // Add implicit joins based on schema links
152 _
.each(links
[$scope
.entity
], function(link
) {
153 var linkFields
= _
.cloneDeep(entityFields(link
.entity
)),
154 wildCard
= addWildcard
? [{id
: link
.alias
+ '.*', text
: link
.alias
+ '.*', 'description': 'All core ' + link
.entity
+ ' fields'}] : [];
156 if (addPseudoconstant
) {
157 addPseudoconstants(linkFields
, addPseudoconstant
);
161 description
: 'Implicit join to ' + link
.entity
,
162 children
: wildCard
.concat(formatForSelect2(linkFields
, [], 'name', ['description'], link
.alias
+ '.'))
168 // Note: this function transforms a raw list a-la getFields; not a select2-formatted list
169 function addPseudoconstants(fieldList
, toAdd
) {
170 var optionFields
= _
.filter(fieldList
, 'options');
171 _
.each(optionFields
, function(field
) {
172 var pos
= _
.findIndex(fieldList
, {name
: field
.name
}) + 1;
173 _
.each(toAdd
, function(suffix
) {
174 var newField
= _
.cloneDeep(field
);
175 newField
.name
+= ':' + suffix
;
176 fieldList
.splice(pos
, 0, newField
);
181 $scope
.help = function(title
, content
) {
183 $scope
.helpTitle
= helpTitle
;
184 $scope
.helpContent
= helpContent
;
186 $scope
.helpTitle
= title
;
187 $scope
.helpContent
= formatHelp(content
);
191 // Sets the static help text (which gets overridden by mousing over other elements)
192 function setHelp(title
, content
) {
193 $scope
.helpTitle
= helpTitle
= title
;
194 $scope
.helpContent
= helpContent
= formatHelp(content
);
197 // Format help text with markdown; replace variables and format links
198 function formatHelp(rawContent
) {
199 function formatRefs(see
) {
200 _
.each(see
, function(ref
, idx
) {
201 var match
= ref
.match(/^(\\Civi\\Api4\\)?([a-zA-Z]+)$/);
203 ref
= '#/explorer/' + match
[2];
205 // Link to php classes on GitHub.
206 // Fixme: Only works for files in the core repo
207 if (ref
[0] === '\\' || ref
.indexOf('Civi\\') === 0 || ref
.indexOf('CRM_') === 0) {
208 var classFunction
= _
.trim(ref
, '\\').split('::'),
209 replacement
= new RegExp(classFunction
[0].indexOf('CRM_') === 0 ? '_' : '\\\\', 'g');
210 ref
= 'https://github.com/civicrm/civicrm-core/blob/master/' + classFunction
[0].replace(replacement
, '/') + '.php';
212 see
[idx
] = '<a target="' + (ref
[0] === '#' ? '_self' : '_blank') + '" href="' + ref
+ '">' + see
[idx
] + '</a>';
215 var formatted
= _
.cloneDeep(rawContent
);
216 if (formatted
.description
) {
217 formatted
.description
= marked(formatted
.description
);
219 if (formatted
.comment
) {
220 formatted
.comment
= marked(formatted
.comment
);
222 formatRefs(formatted
.see
);
226 $scope
.fieldHelp = function(fieldName
) {
227 var field
= getField(fieldName
, $scope
.entity
, $scope
.action
);
232 description
: field
.description
,
233 type
: field
.data_type
235 if (field
.default_value
) {
236 info
.default = field
.default_value
;
238 if (field
.required_if
) {
239 info
.required_if
= field
.required_if
;
240 } else if (field
.required
) {
241 info
.required
= 'true';
246 // Returns field list for write params (values, defaults)
247 $scope
.fieldList = function(param
) {
250 getFieldList(fields
, $scope
.action
=== 'getFields' ? ($scope
.params
.action
|| 'get') : $scope
.action
, ['name']);
251 // Disable fields that are already in use
252 _
.each($scope
.params
[param
] || [], function(val
) {
253 var usedField
= val
[0].replace(':name', '');
254 (_
.findWhere(fields
, {id
: usedField
}) || {}).disabled
= true;
255 (_
.findWhere(fields
, {id
: usedField
+ ':name'}) || {}).disabled
= true;
257 return {results
: fields
};
261 $scope
.formatSelect2Item = function(row
) {
262 return _
.escape(row
.text
) +
263 (row
.required
? '<span class="crm-marker"> *</span>' : '') +
264 (row
.description
? '<div class="crm-select2-row-description"><p>' + _
.escape(row
.description
) + '</p></div>' : '');
267 $scope
.clearParam = function(name
, idx
) {
268 if (typeof idx
=== 'undefined') {
269 $scope
.params
[name
] = $scope
.availableParams
[name
].default;
271 $scope
.params
[name
].splice(idx
, 1);
275 // Gets params that should be represented as generic input fields in the explorer
276 // This fn doesn't have to be particularly efficient as its output is cached in one-time bindings
277 $scope
.getGenericParams = function(paramType
, defaultNull
) {
278 // Returns undefined if params are not yet set; one-time bindings will stabilize when this function returns a value
279 if (_
.isEmpty($scope
.availableParams
)) {
282 var specialParams
= ['select', 'fields', 'action', 'where', 'values', 'defaults', 'orderBy', 'chain', 'groupBy', 'having', 'join'];
283 if ($scope
.availableParams
.limit
&& $scope
.availableParams
.offset
) {
284 specialParams
.push('limit', 'offset');
286 return _
.transform($scope
.availableParams
, function(genericParams
, param
, name
) {
287 if (!_
.contains(specialParams
, name
) &&
288 !(typeof paramType
!== 'undefined' && !_
.contains(paramType
, param
.type
[0])) &&
289 !(typeof defaultNull
!== 'undefined' && ((param
.default === null) !== defaultNull
))
291 genericParams
[name
] = param
;
296 $scope
.selectRowCount = function() {
297 var index
= params
.select
.indexOf('row_count');
299 $scope
.params
.select
.push('row_count');
301 $scope
.params
.select
.splice(index
, 1);
305 $scope
.isSelectRowCount = function() {
306 return isSelectRowCount($scope
.params
);
309 $scope
.selectLang = function(lang
) {
310 $scope
.selectedTab
.code
= lang
;
314 function isSelectRowCount(params
) {
315 return params
&& params
.select
&& params
.select
.indexOf('row_count') >= 0;
318 function getEntity(entityName
) {
319 return _
.findWhere(schema
, {name
: entityName
|| $scope
.entity
});
322 // Get name of entity given join alias
323 function entityNameFromAlias(alias
) {
324 var joins
= getExplicitJoins(),
325 entity
= $scope
.entity
,
326 path
= alias
.split('.');
327 // First check explicit joins
331 // Then lookup implicit links
332 _
.each(path
, function(node
) {
333 var link
= _
.find(links
[entity
], {alias
: node
});
337 entity
= link
.entity
;
342 // Get all params that have been set
343 function getParams() {
345 _
.each($scope
.params
, function(param
, key
) {
346 if (param
!= $scope
.availableParams
[key
].default && !(typeof param
=== 'object' && _
.isEmpty(param
))) {
347 if (_
.contains($scope
.availableParams
[key
].type
, 'array') && (typeof objectParams
[key
] === 'undefined')) {
348 params
[key
] = parseYaml(JSON
.parse(angular
.toJson(param
)));
354 _
.each(objectParams
, function(defaultVal
, key
) {
357 _
.each(params
[key
], function(item
) {
358 var val
= _
.cloneDeep(item
[1]);
359 // Remove blank items from "chain" array
360 if (_
.isArray(val
)) {
361 _
.eachRight(item
[1], function(v
, k
) {
368 newParam
[item
[0]] = parseYaml(val
);
370 params
[key
] = newParam
;
376 function parseYaml(input
) {
377 if (typeof input
=== 'undefined' || input
=== '') {
380 // Return literal quoted string without removing quotes - for the sake of JOIN ON clauses
381 if (_
.isString(input
) && input
[0] === input
[input
.length
- 1] && _
.includes(["'", '"'], input
[0])) {
384 if (_
.isObject(input
) || _
.isArray(input
)) {
385 _
.each(input
, function(item
, index
) {
386 input
[index
] = parseYaml(item
);
391 var output
= (input
=== '>') ? '>' : jsyaml
.safeLoad(input
);
392 // We don't want dates parsed to js objects
393 return _
.isDate(output
) ? input
: output
;
399 this.buildFieldList = function() {
400 var actionInfo
= _
.findWhere(actions
, {id
: $scope
.action
});
401 getFieldList($scope
.fields
, $scope
.action
);
402 getFieldList($scope
.fieldsAndJoins
, $scope
.action
, ['name']);
403 getFieldList($scope
.fieldsAndJoinsAndFunctions
, $scope
.action
);
404 getFieldList($scope
.fieldsAndJoinsAndFunctionsWithSuffixes
, $scope
.action
, ['name', 'label']);
405 getFieldList($scope
.fieldsAndJoinsAndFunctionsAndWildcards
, $scope
.action
, ['name', 'label']);
406 if (_
.contains(['get', 'update', 'delete', 'replace'], $scope
.action
)) {
407 addJoins($scope
.fieldsAndJoins
);
408 // SQL functions are supported if HAVING is
409 if (actionInfo
.params
.having
) {
411 text
: ts('FUNCTION'),
412 description
: ts('Calculate result of a SQL function'),
413 children
: _
.transform(CRM
.vars
.api4
.functions
, function(result
, fn
) {
415 id
: fn
.name
+ '() AS ' + fn
.name
.toLowerCase(),
416 text
: fn
.name
+ '()',
417 description
: fn
.name
+ '(' + describeSqlFn(fn
.params
) + ')'
421 $scope
.fieldsAndJoinsAndFunctions
.push(functions
);
422 $scope
.fieldsAndJoinsAndFunctionsWithSuffixes
.push(functions
);
423 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
.push(functions
);
425 addJoins($scope
.fieldsAndJoinsAndFunctions
, true);
426 addJoins($scope
.fieldsAndJoinsAndFunctionsWithSuffixes
, false, ['name', 'label']);
427 addJoins($scope
.fieldsAndJoinsAndFunctionsAndWildcards
, true, ['name', 'label']);
429 // Custom fields are supported if HAVING is
430 if (actionInfo
.params
.having
) {
431 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
.unshift({id
: 'custom.*', text
: 'custom.*', 'description': 'All custom fields'});
433 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
.unshift({id
: '*', text
: '*', 'description': 'All core ' + $scope
.entity
+ ' fields'});
436 function selectAction() {
437 $scope
.action
= $routeParams
.api4action
;
438 if (!actions
.length
) {
439 formatForSelect2(getEntity().actions
, actions
, 'name', ['description', 'params']);
442 var actionInfo
= _
.findWhere(actions
, {id
: $scope
.action
});
443 _
.each(actionInfo
.params
, function (param
, name
) {
445 defaultVal
= _
.cloneDeep(param
.default);
447 switch (param
.type
[0]) {
450 format
= param
.type
[0];
461 if (name
=== 'limit') {
464 if (name
=== 'debug') {
467 if (name
=== 'values') {
468 defaultVal
= defaultValues(defaultVal
);
470 if (name
=== 'loadOptions' && $scope
.action
=== 'getFields') {
474 ['id', 'name', 'label'],
475 ['id', 'name', 'label', 'abbr', 'description', 'color', 'icon']
479 param
.type
= ['string'];
481 $scope
.$bindToRoute({
482 expr
: 'params["' + name
+ '"]',
486 deep
: format
=== 'json'
489 if (typeof objectParams
[name
] !== 'undefined' && name
!== 'orderBy') {
490 $scope
.$watch('params.' + name
, function (values
) {
491 // Remove empty values
492 _
.each(values
, function (clause
, index
) {
493 if (!clause
|| !clause
[0]) {
494 $scope
.clearParam(name
, index
);
499 if (name
=== 'select' && actionInfo
.params
.having
) {
500 $scope
.$watchCollection('params.select', function(newSelect
) {
501 // Ignore row_count, it can't be used in HAVING clause
502 var select
= _
.without(newSelect
, 'row_count');
503 $scope
.havingOptions
.length
= 0;
504 // An empty select is an implicit *
505 if (!select
.length
) {
508 _
.each(select
, function(item
) {
510 pieces
= item
.split(' AS '),
511 alias
= _
.trim(pieces
[pieces
.length
- 1]).replace(':label', ':name');
513 if (alias
[alias
.length
- 1] === '*') {
514 if (alias
.length
> 1) {
515 joinEntity
= entityNameFromAlias(alias
.slice(0, -2));
517 var fieldList
= _
.filter(getEntity(joinEntity
).fields
, {custom_field_id
: null});
518 formatForSelect2(fieldList
, $scope
.havingOptions
, 'name', ['description', 'required', 'default_value'], alias
.slice(0, -1));
521 $scope
.havingOptions
.push({id
: alias
, text
: alias
});
526 if (typeof objectParams
[name
] !== 'undefined' || name
=== 'groupBy' || name
=== 'select' || name
=== 'join') {
527 $scope
.$watch('controls.' + name
, function(value
) {
529 $timeout(function() {
531 if (name
=== 'join') {
532 $scope
.params
[name
].push([field
+ ' AS ' + _
.snakeCase(field
), 'LEFT']);
533 ctrl
.buildFieldList();
535 else if (typeof objectParams
[name
] === 'undefined') {
536 $scope
.params
[name
].push(field
);
538 var defaultOp
= _
.cloneDeep(objectParams
[name
]);
539 if (name
=== 'chain') {
540 var num
= $scope
.params
.chain
.length
;
541 defaultOp
[0] = field
;
542 field
= 'name_me_' + num
;
544 $scope
.params
[name
].push([field
, defaultOp
]);
546 $scope
.controls
[name
] = null;
552 ctrl
.buildFieldList();
553 $scope
.availableParams
= actionInfo
.params
;
558 function describeSqlFn(params
) {
560 _
.each(params
, function(param
) {
563 desc
+= _
.filter(param
.prefix
).join('|') + ' ';
565 if (param
.expr
=== 1) {
567 } else if (param
.expr
> 1) {
568 desc
+= 'expr, ... ';
571 desc
+= ' ' + _
.filter(param
.suffix
).join('|') + ' ';
574 return desc
.replace(/[ ]+/g, ' ');
577 function defaultValues(defaultVal
) {
578 _
.each($scope
.fields
, function(field
) {
579 if (field
.required
) {
580 defaultVal
.push([field
.id
, '']);
586 function stringify(value
, trim
) {
587 if (typeof value
=== 'undefined') {
590 var str
= JSON
.stringify(value
).replace(/,/g
, ', ');
592 str
= str
.slice(1, -1);
597 function writeCode() {
599 entity
= $scope
.entity
,
600 action
= $scope
.action
,
601 params
= getParams(),
602 index
= isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
),
604 if ($scope
.entity
&& $scope
.action
) {
606 if (action
.slice(0, 3) === 'get') {
607 result
= entity
.substr(0, 7) === 'Custom_' ? _
.camelCase(entity
.substr(7)) : entity
;
608 result
= lcfirst(action
.replace(/s$/, '').slice(3) || result
);
610 var results
= lcfirst(_
.isNumber(index
) ? result
: pluralize(result
)),
611 paramCount
= _
.size(params
),
614 switch ($scope
.selectedTab
.code
) {
618 var js
= "'" + entity
+ "', '" + action
+ "', {";
619 _
.each(params
, function(param
, key
) {
620 js
+= "\n " + key
+ ': ' + stringify(param
) +
621 (++i
< paramCount
? ',' : '');
622 if (key
=== 'checkPermissions') {
623 js
+= ' // IGNORED: permissions are always enforced from client-side requests';
627 if (index
|| index
=== 0) {
628 js
+= ', ' + JSON
.stringify(index
);
630 code
.js
= "CRM.api4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
631 code
.js2
= "CRM.api4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
632 code
.ang
= "crmApi4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
633 code
.ang2
= "crmApi4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
638 code
.php
= '$' + results
+ " = civicrm_api4('" + entity
+ "', '" + action
+ "', [";
639 _
.each(params
, function(param
, key
) {
640 code
.php
+= "\n '" + key
+ "' => " + phpFormat(param
, 4) + ',';
643 if (index
|| index
=== 0) {
644 code
.php
+= ', ' + phpFormat(index
);
649 code
.oop
= '$' + results
+ " = " + formatOOP(entity
, action
, params
, 2) + "\n ->execute()";
650 if (_
.isNumber(index
)) {
651 code
.oop
+= !index
? '\n ->first()' : (index
=== -1 ? '\n ->last()' : '\n ->itemAt(' + index
+ ')');
653 if (_
.isString(index
) || (_
.isPlainObject(index
) && !index
[0] && !index
['0'])) {
654 code
.oop
+= "\n ->indexBy('" + (_
.isPlainObject(index
) ? _
.keys(index
)[0] : index
) + "')";
656 if (_
.isArray(index
) || _
.isPlainObject(index
)) {
657 code
.oop
+= "\n ->column('" + (_
.isArray(index
) ? index
[0] : _
.values(index
)[0]) + "')";
661 if (!_
.isNumber(index
)) {
662 code
.oop
+= "foreach ($" + results
+ ' as $' + ((_
.isString(index
) && index
) ? index
+ ' => $' : '') + result
+ ') {\n // do something\n}';
667 // Cli code using json input
668 code
.long = 'cv api4 ' + entity
+ '.' + action
+ ' ' + cliFormat(JSON
.stringify(params
));
669 code
.pipe
= 'echo ' + cliFormat(JSON
.stringify(params
)) + ' | cv api4 ' + entity
+ '.' + action
+ ' --in=json';
671 // Cli code using short syntax
672 code
.short = 'cv api4 ' + entity
+ '.' + action
;
673 var limitSet
= false;
674 _
.each(params
, function(param
, key
) {
676 case (key
=== 'select' && !_
.includes(param
.join(), ' ')):
677 code
.short += ' +s ' + cliFormat(param
.join(','));
679 case (key
=== 'where' && !_
.intersection(_
.map(param
, 0), ['AND', 'OR', 'NOT']).length
):
680 _
.each(param
, function(clause
) {
681 code
.short += ' +w ' + cliFormat(clause
[0] + ' ' + clause
[1] + (clause
.length
> 2 ? (' ' + JSON
.stringify(clause
[2])) : ''));
684 case (key
=== 'orderBy'):
685 _
.each(param
, function(dir
, field
) {
686 code
.short += ' +o ' + cliFormat(field
+ ' ' + dir
);
689 case (key
=== 'values'):
690 _
.each(param
, function(val
, field
) {
691 code
.short += ' +v ' + cliFormat(field
+ '=' + val
);
694 case (key
=== 'limit' || key
=== 'offset'):
695 // These 2 get combined
698 code
.short += ' +l ' + (params
.limit
|| '0') + (params
.offset
? ('@' + params
.offset
) : '');
702 code
.short += ' ' + key
+ '=' + (typeof param
=== 'string' ? cliFormat(param
) : cliFormat(JSON
.stringify(param
)));
707 _
.each($scope
.code
, function(vals
) {
708 _
.each(vals
, function(style
) {
709 style
.code
= code
[style
.name
] ? prettyPrintOne(_
.escape(code
[style
.name
])) : '';
715 function formatOOP(entity
, action
, params
, indent
) {
717 newLine
= "\n" + _
.repeat(' ', indent
),
718 perm
= params
.checkPermissions
=== false ? 'FALSE' : '';
719 if (entity
.substr(0, 7) !== 'Custom_') {
720 code
= "\\Civi\\Api4\\" + entity
+ '::' + action
+ '(' + perm
+ ')';
722 code
= "\\Civi\\Api4\\CustomValue::" + action
+ "('" + entity
.substr(7) + "'" + (perm
? ', ' : '') + perm
+ ")";
724 _
.each(params
, function(param
, key
) {
726 if (typeof objectParams
[key
] !== 'undefined' && key
!== 'chain') {
727 _
.each(param
, function(item
, index
) {
728 val
= phpFormat(index
) + ', ' + phpFormat(item
, 2 + indent
);
729 code
+= newLine
+ "->add" + ucfirst(key
).replace(/s$/, '') + '(' + val
+ ')';
731 } else if (key
=== 'where') {
732 _
.each(param
, function (clause
) {
733 if (clause
[0] === 'AND' || clause
[0] === 'OR' || clause
[0] === 'NOT') {
734 code
+= newLine
+ "->addClause(" + phpFormat(clause
[0]) + ", " + phpFormat(clause
[1]).slice(1, -1) + ')';
736 code
+= newLine
+ "->addWhere(" + phpFormat(clause
).slice(1, -1) + ")";
739 } else if (key
=== 'select') {
740 // selectRowCount() is a shortcut for addSelect('row_count')
741 if (isSelectRowCount(params
)) {
742 code
+= newLine
+ '->selectRowCount()';
743 param
= _
.without(param
, 'row_count');
745 // addSelect() is a variadic function & can take multiple arguments
747 code
+= newLine
+ '->addSelect(' + phpFormat(param
).slice(1, -1) + ')';
749 } else if (key
=== 'chain') {
750 _
.each(param
, function(chain
, name
) {
751 code
+= newLine
+ "->addChain('" + name
+ "', " + formatOOP(chain
[0], chain
[1], chain
[2], 2 + indent
);
752 code
+= (chain
.length
> 3 ? ',' : '') + (!_
.isEmpty(chain
[2]) ? newLine
: ' ') + (chain
.length
> 3 ? phpFormat(chain
[3]) : '') + ')';
755 else if (key
!== 'checkPermissions') {
756 code
+= newLine
+ "->set" + ucfirst(key
) + '(' + phpFormat(param
, 2 + indent
) + ')';
762 function isInt(value
) {
763 if (_
.isFinite(value
)) {
766 if (!_
.isString(value
)) {
769 return /^-{0,1}\d+$/.test(value
);
772 function formatMeta(resp
) {
774 _
.each(resp
, function(val
, key
) {
775 if (key
!== 'values' && !_
.isPlainObject(val
) && !_
.isFunction(val
)) {
776 ret
+= (ret
.length
? ', ' : '') + key
+ ': ' + (_
.isArray(val
) ? '[' + val
+ ']' : val
);
779 return prettyPrintOne(_
.escape(ret
));
782 $scope
.execute = function() {
783 $scope
.status
= 'info';
784 $scope
.loading
= true;
785 $http
.post(CRM
.url('civicrm/ajax/api4/' + $scope
.entity
+ '/' + $scope
.action
, {
786 params
: angular
.toJson(getParams()),
787 index
: isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
)
790 'X-Requested-With': 'XMLHttpRequest'
792 }).then(function(resp
) {
793 $scope
.loading
= false;
794 $scope
.status
= resp
.data
&& resp
.data
.debug
&& resp
.data
.debug
.log
? 'warning' : 'success';
795 $scope
.debug
= debugFormat(resp
.data
);
797 formatMeta(resp
.data
),
798 prettyPrintOne((_
.isArray(resp
.data
.values
) ? '(' + resp
.data
.values
.length
+ ') ' : '') + _
.escape(JSON
.stringify(resp
.data
.values
, null, 2)), 'js', 1)
801 $scope
.loading
= false;
802 $scope
.status
= 'danger';
803 $scope
.debug
= debugFormat(resp
.data
);
806 prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
, null, 2)))
811 function debugFormat(data
) {
812 var debug
= data
.debug
? prettyPrintOne(_
.escape(JSON
.stringify(data
.debug
, null, 2)).replace(/\\n/g, "\n")) : null;
818 * Format value to look like php code
820 function phpFormat(val
, indent
) {
821 if (typeof val
=== 'undefined') {
824 if (val
=== null || val
=== true || val
=== false) {
825 return JSON
.stringify(val
).toUpperCase();
827 indent
= (typeof indent
=== 'number') ? _
.repeat(' ', indent
) : (indent
|| '');
829 baseLine
= indent
? indent
.slice(0, -2) : '',
830 newLine
= indent
? '\n' : '',
831 trailingComma
= indent
? ',' : '';
832 if ($.isPlainObject(val
)) {
833 $.each(val
, function(k
, v
) {
834 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ "'" + k
+ "' => " + phpFormat(v
);
836 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
838 if ($.isArray(val
)) {
839 $.each(val
, function(k
, v
) {
840 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ phpFormat(v
);
842 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
844 if (_
.isString(val
) && !_
.contains(val
, "'")) {
845 return "'" + val
+ "'";
847 return JSON
.stringify(val
).replace(/\$/g, '\\$');
850 // Format string to be cli-input-safe
851 function cliFormat(str
) {
852 if (!_
.includes(str
, ' ') && !_
.includes(str
, '"') && !_
.includes(str
, "'")) {
855 if (!_
.includes(str
, "'")) {
856 return "'" + str
+ "'";
858 if (!_
.includes(str
, '"')) {
859 return '"' + str
+ '"';
861 return "'" + str
.replace(/'/g, "\\'") + "'";
864 function fetchMeta() {
865 crmApi4(getMetaParams)
866 .then(function(data) {
868 getEntity().actions = data.actions;
874 // Help for an entity with no action selected
875 function showEntityHelp(entityName) {
876 var entityInfo = getEntity(entityName);
877 setHelp($scope.entity, {
878 description: entityInfo.description,
879 comment: entityInfo.comment,
880 type: entityInfo.type,
885 if (!$scope.entity) {
886 setHelp(ts('APIv4 Explorer
'), {description: docs.description, comment: docs.comment, see: docs.see});
887 } else if (!actions.length && !getEntity().actions) {
888 getMetaParams.actions = [$scope.entity, 'getActions
', {chain: {fields: [$scope.entity, 'getFields
', {action: '$name
'}]}}];
895 showEntityHelp($scope.entity);
898 // Update route when changing entity
899 $scope.$watch('entity
', function(newVal, oldVal) {
900 if (oldVal !== newVal) {
901 // Flush actions cache to re-fetch for new entity
903 $location.url('/explorer/' + newVal);
907 // Update route when changing actions
908 $scope.$watch('action
', function(newVal, oldVal) {
909 if ($scope.entity && $routeParams.api4action !== newVal && !_.isUndefined(newVal)) {
910 $location.url('/explorer/' + $scope.entity + '/' + newVal);
912 setHelp($scope.entity + '::' + newVal, _.pick(_.findWhere(getEntity().actions, {name: newVal}), ['description
', 'comment
', 'see
']));
916 $scope.paramDoc = function(name) {
917 return docs.params[name];
920 $scope.executeDoc = function() {
922 description: ts('Runs API call on the CiviCRM database
.'),
923 comment: ts('Results and debugging info will be displayed below
.')
925 if ($scope.action === 'delete') {
926 doc.WARNING = ts('This API call will be executed on the real database
. Deleting data cannot be undone
.');
928 else if ($scope.action && $scope.action.slice(0, 3) !== 'get') {
929 doc.WARNING = ts('This API call will be executed on the real database
. It cannot be undone
.');
934 $scope.saveDoc = function() {
936 description: ts('Save API call as a smart group
.'),
937 comment: ts('Create a SavedSearch using these API params to populate a smart group
.') +
938 '\n\n' + ts('NOTE
: you must select contact id as the only field
.')
942 $scope.$watch('params
', writeCode, true);
943 $scope.$watch('index
', writeCode);
946 $scope.save = function() {
947 $scope.params.limit = $scope.params.offset = 0;
948 if ($scope.params.chain.length) {
949 CRM.alert(ts('Smart groups are not compatible
with API chaining
.'), ts('Error
'), 'error
', {expires: 5000});
952 if ($scope.params.select.length !== 1 || !_.includes($scope.params.select[0], 'id
')) {
953 CRM.alert(ts('To create a smart group
, the API must select contact id and no other fields
.'), ts('Error
'), 'error
', {expires: 5000});
959 visibility: 'User and User Admin Only
',
962 entity: $scope.entity,
963 params: JSON.parse(angular.toJson($scope.params))
965 model.params.version = 4;
966 delete model.params.chain;
967 delete model.params.debug;
968 delete model.params.limit;
969 delete model.params.offset;
970 delete model.params.orderBy;
971 delete model.params.checkPermissions;
972 var options = CRM.utils.adjustDialogDefaults({
975 title: ts('Save smart group
')
977 dialogService.open('saveSearchDialog
', '~/api4Explorer/SaveSearch
.html
', model, options);
981 angular.module('api4Explorer
').controller('SaveSearchCtrl
', function($scope, crmApi4, dialogService) {
982 var ts = $scope.ts = CRM.ts(),
983 model = $scope.model;
984 $scope.groupEntityRefParams = {
987 params: {is_hidden: 0, is_active: 1, 'saved_search_id
.api_entity
': model.entity},
988 extra: ['saved_search_id
', 'description
', 'visibility
', 'group_type
']
992 minimumInputLength: 0,
993 placeholder: ts('Select existing group
')
996 if (!CRM.checkPerm('administer reserved groups
')) {
997 $scope.groupEntityRefParams.api.params.is_reserved = 0;
1000 administerReservedGroups: CRM.checkPerm('administer reserved groups
')
1002 $scope.options = CRM.vars.api4.groupOptions;
1003 $scope.$watch('model
.id
', function(id) {
1005 _.assign(model, $('#api
-save
-search
-select
-group
').select2('data
').extra);
1008 $scope.cancel = function() {
1009 dialogService.cancel('saveSearchDialog
');
1011 $scope.save = function() {
1012 $('.ui
-dialog
:visible
').block();
1013 var group = model.id ? {id: model.id} : {title: model.title};
1014 group.description = model.description;
1015 group.visibility = model.visibility;
1016 group.group_type = model.group_type;
1017 group.saved_search_id = '$id
';
1019 api_entity: model.entity,
1020 api_params: model.params
1023 savedSearch.id = model.saved_search_id;
1025 crmApi4('SavedSearch
', 'save
', {records: [savedSearch], chain: {group: ['Group
', 'save
', {'records
': [group]}]}})
1026 .then(function(result) {
1027 dialogService.close('saveSearchDialog
', result[0]);
1032 angular.module('api4Explorer
').component('crmApi4Clause
', {
1043 templateUrl: '~/api4Explorer/Clause
.html
',
1044 controller: function ($scope, $element, $timeout) {
1045 var ts = $scope.ts = CRM.ts(),
1047 this.conjunctions = {AND: ts('And
'), OR: ts('Or
'), NOT: ts('Not
')};
1048 this.operators = CRM.vars.api4.operators;
1049 this.sortOptions = {
1051 connectWith: '.api4
-clause
-group
-sortable
',
1052 containment: $element.closest('.api4
-clause
-fieldset
'),
1058 this.$onInit = function() {
1059 ctrl.hasParent = !!$element.attr('delete-group
');
1062 this.addGroup = function(op) {
1063 ctrl.clauses.push([op, []]);
1066 function onSort(event, ui) {
1067 $($element).closest('.api4
-clause
-fieldset
').toggleClass('api4
-sorting
', event.type === 'sortstart
');
1068 $('.api4
-input
.form
-inline
').css('margin
-left
', '');
1071 // Indent clause while dragging between nested groups
1072 function onSortOver(event, ui) {
1075 offset = $(ui.placeholder).offset().left - $(ui.sender).offset().left;
1077 $('.api4
-input
.form
-inline
.ui
-sortable
-helper
').css('margin
-left
', '' + offset + 'px
');
1080 this.addClause = function() {
1081 $timeout(function() {
1082 if (ctrl.newClause) {
1083 if (ctrl.skip && ctrl.clauses.length < ctrl.skip) {
1084 ctrl.clauses.push(null);
1086 ctrl.clauses.push([ctrl.newClause, '=', '']);
1087 ctrl.newClause = null;
1092 this.deleteRow = function(index) {
1093 ctrl.clauses.splice(index, 1);
1096 // Remove empty values
1097 this.changeClauseField = function(clause, index) {
1098 if (clause[0] === '') {
1099 ctrl.deleteRow(index);
1103 // Add/remove value if operator allows for one
1104 this.changeClauseOperator = function(clause) {
1105 if (_.contains(clause[1], 'IS
')) {
1107 } else if (clause.length === 2) {
1114 angular.module('api4Explorer
').directive('api4ExpValue
', function($routeParams, crmApi4) {
1117 data: '=api4ExpValue
'
1120 link: function (scope, element, attrs, ctrl) {
1121 var ts = scope.ts = CRM.ts(),
1122 multi = _.includes(['IN
', 'NOT IN
', 'BETWEEN
', 'NOT BETWEEN
'], scope.data.op),
1123 entity = $routeParams.api4entity,
1124 action = scope.data.action || $routeParams.api4action;
1126 function destroyWidget() {
1127 var $el = $(element);
1128 if ($el.is('.crm
-form
-date
-wrapper
.crm
-hidden
-date
')) {
1129 $el.crmDatepicker('destroy
');
1131 if ($el.is('.select2
-container
+ input
')) {
1132 $el.crmEntityRef('destroy
');
1134 $(element).removeData().removeAttr('type
').removeAttr('placeholder
').show();
1137 function makeWidget(field, op) {
1138 var $el = $(element),
1139 inputType = field.input_type,
1140 dataType = field.data_type;
1142 op = field.serialize || dataType === 'Array
' ? 'IN
' : '=';
1144 multi = _.includes(['IN
', 'NOT IN
', 'BETWEEN
', 'NOT BETWEEN
'], op);
1145 // IS NULL, IS EMPTY, etc.
1146 if (_.contains(op, 'IS
')) {
1150 if (inputType === 'Date
') {
1151 if (_.includes(['=', '!=', '<>', '<', '>=', '<', '<='], op)) {
1152 $el.crmDatepicker({time: (field.input_attrs && field.input_attrs.time) || false});
1154 } else if (_.includes(['=', '!=', '<>', 'IN
', 'NOT IN
'], op) && (field.fk_entity || field.options || dataType === 'Boolean
')) {
1155 if (field.options) {
1156 var id = field.pseudoconstant || 'id
';
1157 $el.addClass('loading
').attr('placeholder
', ts('- select
-')).crmSelect2({multiple: multi, data: [{id: '', text: ''}]});
1158 loadFieldOptions(field.entity || entity).then(function(data) {
1159 var options = _.transform(data[field.name].options, function(options, opt) {
1160 options.push({id: opt[id], text: opt.label, description: opt.description, color: opt.color, icon: opt.icon});
1162 $el.removeClass('loading
').crmSelect2({data: options, multiple: multi});
1164 } else if (field.fk_entity) {
1165 $el.crmEntityRef({entity: field.fk_entity, select:{multiple: multi}, static: field.fk_entity === 'Contact
' ? ['user_contact_id
'] : []});
1166 } else if (dataType === 'Boolean
') {
1167 $el.attr('placeholder
', ts('- select
-')).crmSelect2({allowClear: false, multiple: multi, placeholder: ts('- select
-'), data: [
1168 {id: 'true', text: ts('Yes
')},
1169 {id: 'false', text: ts('No
')}
1172 } else if (dataType === 'Integer
' && !multi) {
1173 $el.attr('type
', 'number
');
1177 function loadFieldOptions(entity) {
1178 if (!fieldOptions[entity + action]) {
1179 fieldOptions[entity + action] = crmApi4(entity, 'getFields
', {
1180 loadOptions: ['id
', 'name
', 'label
', 'description
', 'color
', 'icon
'],
1182 where: [['options
', '!=', false]],
1186 return fieldOptions[entity + action];
1189 // Copied from ng-list but applied conditionally if field is multi-valued
1190 var parseList = function(viewValue) {
1191 // If the viewValue is invalid (say required but empty) it will be `undefined`
1192 if (_.isUndefined(viewValue)) return;
1201 _.each(viewValue.split(','), function(value) {
1202 if (value) list.push(_.trim(value));
1209 // Copied from ng-list
1210 ctrl.$parsers.push(parseList);
1211 ctrl.$formatters.push(function(value) {
1212 return _.isArray(value) ? value.join(', ') : value;
1215 // Copied from ng-list
1216 ctrl.$isEmpty = function(value) {
1217 return !value || !value.length;
1220 scope.$watchCollection('data
', function(data) {
1222 var field = getField(data.field, entity, action);
1223 if (field && data.format !== 'plain
') {
1224 makeWidget(field, data.op);
1232 angular.module('api4Explorer
').directive('api4ExpChain
', function(crmApi4) {
1235 chain: '=api4ExpChain
',
1239 templateUrl: '~/api4Explorer/Chain
.html
',
1240 link: function (scope, element, attrs) {
1241 var ts = scope.ts = CRM.ts();
1243 function changeEntity(newEntity, oldEntity) {
1244 // When clearing entity remove this chain
1246 scope.chain[0] = '';
1249 // Reset action && index
1250 if (newEntity !== oldEntity) {
1251 scope.chain[1][1] = scope.chain[1][2] = '';
1253 if (getEntity(newEntity).actions) {
1256 crmApi4(newEntity, 'getActions
', {chain: {fields: [newEntity, 'getFields
', {action: '$name
'}]}})
1257 .then(function(data) {
1258 getEntity(data.entity).actions = data;
1259 if (data.entity === scope.chain[1][0]) {
1266 function setActions() {
1267 scope.actions = [''].concat(_.pluck(getEntity(scope.chain[1][0]).actions, 'name
'));
1270 // Set default params when choosing action
1271 function changeAction(newAction, oldAction) {
1273 // Prepopulate links
1274 if (newAction && newAction !== oldAction) {
1276 scope.chain[1][3] = '';
1277 // Look for links back to main entity
1278 _.each(entityFields(scope.chain[1][0]), function(field) {
1279 if (field.fk_entity === scope.mainEntity) {
1280 link = [field.name, '$id
'];
1283 // Look for links from main entity
1284 if (!link && newAction !== 'create
') {
1285 _.each(entityFields(scope.mainEntity), function(field) {
1286 if (field.fk_entity === scope.chain[1][0]) {
1287 link = ['id
', '$' + field.name];
1288 // Since we're specifying the id
, set index to getsingle
1289 scope
.chain
[1][3] = '0';
1293 if (link
&& _
.contains(['get', 'update', 'replace', 'delete'], newAction
)) {
1294 scope
.chain
[1][2] = '{where: [[' + link
[0] + ', =, ' + link
[1] + ']]}';
1296 else if (link
&& _
.contains(['create'], newAction
)) {
1297 scope
.chain
[1][2] = '{values: {' + link
[0] + ': ' + link
[1] + '}}';
1299 else if (link
&& _
.contains(['save'], newAction
)) {
1300 scope
.chain
[1][2] = '{records: [{' + link
[0] + ': ' + link
[1] + '}]}';
1302 scope
.chain
[1][2] = '{}';
1307 scope
.$watch("chain[1][0]", changeEntity
);
1308 scope
.$watch("chain[1][1]", changeAction
);
1313 function getEntity(entityName
) {
1314 return _
.findWhere(schema
, {name
: entityName
});
1317 function entityFields(entityName
, action
) {
1318 var entity
= getEntity(entityName
);
1319 if (entity
&& action
&& entity
.actions
) {
1320 return _
.findWhere(entity
.actions
, {name
: action
}).fields
;
1322 return _
.result(entity
, 'fields');
1325 function getExplicitJoins() {
1326 return _
.transform(params
.join
, function(joins
, join
) {
1327 var j
= join
[0].split(' AS '),
1328 joinEntity
= _
.trim(j
[0]),
1329 joinAlias
= _
.trim(j
[1]) || joinEntity
.toLowerCase();
1330 joins
[joinAlias
] = joinEntity
;
1334 function getField(fieldName
, entity
, action
) {
1335 var suffix
= fieldName
.split(':')[1];
1336 fieldName
= fieldName
.split(':')[0];
1337 var fieldNames
= fieldName
.split('.');
1338 var field
= get(entity
, fieldNames
);
1339 if (field
&& suffix
) {
1340 field
.pseudoconstant
= suffix
;
1344 function get(entity
, fieldNames
) {
1345 if (fieldNames
.length
=== 1) {
1346 return _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0]});
1348 var comboName
= _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0] + '.' + fieldNames
[1]});
1352 var linkName
= fieldNames
.shift(),
1353 newEntity
= getExplicitJoins()[linkName
] || _
.findWhere(links
[entity
], {alias
: linkName
}).entity
;
1354 return get(newEntity
, fieldNames
);
1358 // Collapsible optgroups for select2
1361 .on('select2-open', function(e
) {
1362 if ($(e
.target
).hasClass('collapsible-optgroups')) {
1364 .off('.collapseOptionGroup')
1365 .addClass('collapsible-optgroups-enabled')
1366 .on('click.collapseOptionGroup', '.select2-result-with-children > .select2-result-label', function() {
1367 $(this).parent().toggleClass('optgroup-expanded');
1371 .on('select2-close', function() {
1372 $('#select2-drop').off('.collapseOptionGroup').removeClass('collapsible-optgroups-enabled');
1375 })(angular
, CRM
.$, CRM
._
);