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
: false, v
: ts('Optional')}, {k
: true, v
: ts('Required')}];
62 {name
: 'oop', label
: ts('OOP Style'), code
: ''},
63 {name
: 'php', label
: ts('Traditional'), code
: ''}
66 {name
: 'js', label
: ts('Single Call'), code
: ''},
67 {name
: 'js2', label
: ts('Batch Calls'), code
: ''}
70 {name
: 'ang', label
: ts('Single Call'), code
: ''},
71 {name
: 'ang2', label
: ts('Batch Calls'), code
: ''}
74 {name
: 'cv', label
: ts('CV'), code
: ''}
78 if (!entities
.length
) {
79 formatForSelect2(schema
, entities
, 'name', ['description', 'icon']);
88 function ucfirst(str
) {
89 return str
[0].toUpperCase() + str
.slice(1);
92 function lcfirst(str
) {
93 return str
[0].toLowerCase() + str
.slice(1);
96 function pluralize(str
) {
97 var lastLetter
= str
[str
.length
- 1],
98 lastTwo
= str
[str
.length
- 2] + lastLetter
;
99 if (lastLetter
=== 's' || lastLetter
=== 'x' || lastTwo
=== 'ch') {
102 if (lastLetter
=== 'y' && lastTwo
!== 'ey') {
103 return str
.slice(0, -1) + 'ies';
108 // Reformat an existing array of objects for compatibility with select2
109 function formatForSelect2(input
, container
, key
, extra
, prefix
) {
110 _
.each(input
, function(item
) {
111 var id
= (prefix
|| '') + item
[key
];
112 var formatted
= {id
: id
, text
: id
};
114 _
.merge(formatted
, _
.pick(item
, extra
));
116 container
.push(formatted
);
121 // Replaces contents of fieldList array with current fields formatted for select2
122 function getFieldList(fieldList
, action
, addPseudoconstant
) {
123 var fieldInfo
= _
.cloneDeep(_
.findWhere(getEntity().actions
, {name
: action
}).fields
);
124 fieldList
.length
= 0;
125 if (addPseudoconstant
) {
126 addPseudoconstants(fieldInfo
, addPseudoconstant
);
128 formatForSelect2(fieldInfo
, fieldList
, 'name', ['description', 'required', 'default_value']);
131 // Note: this function expects fieldList to be select2-formatted already
132 function addJoins(fieldList
, addWildcard
, addPseudoconstant
) {
133 // Add entities specified by the join param
134 _
.each(getExplicitJoins(), function(joinEntity
, joinAlias
) {
135 var wildCard
= addWildcard
? [{id
: joinAlias
+ '.*', text
: joinAlias
+ '.*', 'description': 'All core ' + joinEntity
+ ' fields'}] : [],
136 joinFields
= _
.cloneDeep(entityFields(joinEntity
));
138 if (addPseudoconstant
) {
139 addPseudoconstants(joinFields
, addPseudoconstant
);
142 text
: joinEntity
+ ' AS ' + joinAlias
,
143 description
: 'Explicit join to ' + joinEntity
,
144 children
: wildCard
.concat(formatForSelect2(joinFields
, [], 'name', ['description'], joinAlias
+ '.'))
148 // Add implicit joins based on schema links
149 _
.each(links
[$scope
.entity
], function(link
) {
150 var linkFields
= _
.cloneDeep(entityFields(link
.entity
)),
151 wildCard
= addWildcard
? [{id
: link
.alias
+ '.*', text
: link
.alias
+ '.*', 'description': 'All core ' + link
.entity
+ ' fields'}] : [];
153 if (addPseudoconstant
) {
154 addPseudoconstants(linkFields
, addPseudoconstant
);
158 description
: 'Implicit join to ' + link
.entity
,
159 children
: wildCard
.concat(formatForSelect2(linkFields
, [], 'name', ['description'], link
.alias
+ '.'))
165 // Note: this function transforms a raw list a-la getFields; not a select2-formatted list
166 function addPseudoconstants(fieldList
, toAdd
) {
167 var optionFields
= _
.filter(fieldList
, 'options');
168 _
.each(optionFields
, function(field
) {
169 var pos
= _
.findIndex(fieldList
, {name
: field
.name
}) + 1;
170 _
.each(toAdd
, function(suffix
) {
171 var newField
= _
.cloneDeep(field
);
172 newField
.name
+= ':' + suffix
;
173 fieldList
.splice(pos
, 0, newField
);
178 $scope
.help = function(title
, content
) {
180 $scope
.helpTitle
= helpTitle
;
181 $scope
.helpContent
= helpContent
;
183 $scope
.helpTitle
= title
;
184 $scope
.helpContent
= formatHelp(content
);
188 // Sets the static help text (which gets overridden by mousing over other elements)
189 function setHelp(title
, content
) {
190 $scope
.helpTitle
= helpTitle
= title
;
191 $scope
.helpContent
= helpContent
= formatHelp(content
);
194 // Convert plain-text help to markdown; replace variables and format links
195 function formatHelp(rawContent
) {
196 function formatRefs(see
) {
197 _
.each(see
, function(ref
, idx
) {
198 var match
= ref
.match(/^\\Civi\\Api4\\([a-zA-Z]+)$/);
200 ref
= '#/explorer/' + match
[1];
202 if (ref
[0] === '\\') {
203 ref
= 'https://github.com/civicrm/civicrm-core/blob/master' + ref
.replace(/\\/i, '/') + '.php
';
205 see[idx] = '<a target
="' + (ref[0] === '#' ? '_self' : '_blank') + '" href
="' + ref + '">' + see[idx] + '</a
>';
208 var formatted = _.cloneDeep(rawContent);
209 if (formatted.description) {
210 formatted.description = marked(formatted.description);
212 if (formatted.comment) {
213 formatted.comment = marked(formatted.comment);
215 formatRefs(formatted.see);
219 $scope.fieldHelp = function(fieldName) {
220 var field = getField(fieldName, $scope.entity, $scope.action);
225 description: field.description,
226 type: field.data_type
228 if (field.default_value) {
229 info.default = field.default_value;
231 if (field.required_if) {
232 info.required_if = field.required_if;
233 } else if (field.required) {
234 info.required = 'true';
239 // Returns field list for write params (values, defaults)
240 $scope.fieldList = function(param) {
243 getFieldList(fields, $scope.action === 'getFields
' ? ($scope.params.action || 'get') : $scope.action, ['name
']);
244 // Disable fields that are already in use
245 _.each($scope.params[param] || [], function(val) {
246 var usedField = val[0].replace(':name
', '');
247 (_.findWhere(fields, {id: usedField}) || {}).disabled = true;
248 (_.findWhere(fields, {id: usedField + ':name
'}) || {}).disabled = true;
250 return {results: fields};
254 $scope.formatSelect2Item = function(row) {
255 return _.escape(row.text) +
256 (row.required ? '<span
class="crm-marker"> *</span
>' : '') +
257 (row.description ? '<div
class="crm-select2-row-description"><p
>' + _.escape(row.description) + '</p></div>' : '');
260 $scope.clearParam = function(name, idx) {
261 if (typeof idx === 'undefined') {
262 $scope.params[name] = $scope.availableParams[name].default;
264 $scope.params[name].splice(idx, 1);
268 // Gets params that should be represented as generic input fields in the explorer
269 // This fn doesn't have to be particularly efficient as its output is cached
in one
-time bindings
270 $scope
.getGenericParams = function(paramType
, defaultNull
) {
271 // Returns undefined if params are not yet set; one-time bindings will stabilize when this function returns a value
272 if (_
.isEmpty($scope
.availableParams
)) {
275 var specialParams
= ['select', 'fields', 'action', 'where', 'values', 'defaults', 'orderBy', 'chain', 'groupBy', 'having', 'join'];
276 if ($scope
.availableParams
.limit
&& $scope
.availableParams
.offset
) {
277 specialParams
.push('limit', 'offset');
279 return _
.transform($scope
.availableParams
, function(genericParams
, param
, name
) {
280 if (!_
.contains(specialParams
, name
) &&
281 !(typeof paramType
!== 'undefined' && !_
.contains(paramType
, param
.type
[0])) &&
282 !(typeof defaultNull
!== 'undefined' && ((param
.default === null) !== defaultNull
))
284 genericParams
[name
] = param
;
289 $scope
.selectRowCount = function() {
290 var index
= params
.select
.indexOf('row_count');
292 $scope
.params
.select
.push('row_count');
294 $scope
.params
.select
.splice(index
, 1);
298 $scope
.isSelectRowCount = function() {
299 return isSelectRowCount($scope
.params
);
302 $scope
.selectLang = function(lang
) {
303 $scope
.selectedTab
.code
= lang
;
307 function isSelectRowCount(params
) {
308 return params
&& params
.select
&& params
.select
.indexOf('row_count') >= 0;
311 function getEntity(entityName
) {
312 return _
.findWhere(schema
, {name
: entityName
|| $scope
.entity
});
315 // Get name of entity given join alias
316 function entityNameFromAlias(alias
) {
317 var joins
= getExplicitJoins(),
318 entity
= $scope
.entity
,
319 path
= alias
.split('.');
320 // First check explicit joins
324 // Then lookup implicit links
325 _
.each(path
, function(node
) {
326 entity
= _
.find(links
[entity
], {alias
: node
}).entity
;
331 // Get all params that have been set
332 function getParams() {
334 _
.each($scope
.params
, function(param
, key
) {
335 if (param
!= $scope
.availableParams
[key
].default && !(typeof param
=== 'object' && _
.isEmpty(param
))) {
336 if (_
.contains($scope
.availableParams
[key
].type
, 'array') && (typeof objectParams
[key
] === 'undefined')) {
337 params
[key
] = parseYaml(JSON
.parse(angular
.toJson(param
)));
343 _
.each(objectParams
, function(defaultVal
, key
) {
346 _
.each(params
[key
], function(item
) {
347 var val
= _
.cloneDeep(item
[1]);
348 // Remove blank items from "chain" array
349 if (_
.isArray(val
)) {
350 _
.eachRight(item
[1], function(v
, k
) {
357 newParam
[item
[0]] = parseYaml(val
);
359 params
[key
] = newParam
;
365 function parseYaml(input
) {
366 if (typeof input
=== 'undefined' || input
=== '') {
369 // Return literal quoted string without removing quotes - for the sake of JOIN ON clauses
370 if (_
.isString(input
) && input
[0] === input
[input
.length
- 1] && _
.includes(["'", '"'], input
[0])) {
373 if (_
.isObject(input
) || _
.isArray(input
)) {
374 _
.each(input
, function(item
, index
) {
375 input
[index
] = parseYaml(item
);
380 var output
= (input
=== '>') ? '>' : jsyaml
.safeLoad(input
);
381 // We don't want dates parsed to js objects
382 return _
.isDate(output
) ? input
: output
;
388 this.buildFieldList = function() {
389 var actionInfo
= _
.findWhere(actions
, {id
: $scope
.action
});
390 getFieldList($scope
.fields
, $scope
.action
);
391 getFieldList($scope
.fieldsAndJoins
, $scope
.action
, ['name']);
392 getFieldList($scope
.fieldsAndJoinsAndFunctions
, $scope
.action
);
393 getFieldList($scope
.fieldsAndJoinsAndFunctionsWithSuffixes
, $scope
.action
, ['name', 'label']);
394 getFieldList($scope
.fieldsAndJoinsAndFunctionsAndWildcards
, $scope
.action
, ['name', 'label']);
395 if (_
.contains(['get', 'update', 'delete', 'replace'], $scope
.action
)) {
396 addJoins($scope
.fieldsAndJoins
);
397 // SQL functions are supported if HAVING is
398 if (actionInfo
.params
.having
) {
400 text
: ts('FUNCTION'),
401 description
: ts('Calculate result of a SQL function'),
402 children
: _
.transform(CRM
.vars
.api4
.functions
, function(result
, fn
) {
404 id
: fn
.name
+ '() AS ' + fn
.name
.toLowerCase(),
405 text
: fn
.name
+ '()',
406 description
: fn
.name
+ '(' + describeSqlFn(fn
.params
) + ')'
410 $scope
.fieldsAndJoinsAndFunctions
.push(functions
);
411 $scope
.fieldsAndJoinsAndFunctionsWithSuffixes
.push(functions
);
412 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
.push(functions
);
414 addJoins($scope
.fieldsAndJoinsAndFunctions
, true);
415 addJoins($scope
.fieldsAndJoinsAndFunctionsWithSuffixes
, false, ['name', 'label']);
416 addJoins($scope
.fieldsAndJoinsAndFunctionsAndWildcards
, true, ['name', 'label']);
418 $scope
.fieldsAndJoinsAndFunctionsAndWildcards
.unshift({id
: '*', text
: '*', 'description': 'All core ' + $scope
.entity
+ ' fields'});
421 function selectAction() {
422 $scope
.action
= $routeParams
.api4action
;
423 if (!actions
.length
) {
424 formatForSelect2(getEntity().actions
, actions
, 'name', ['description', 'params']);
427 var actionInfo
= _
.findWhere(actions
, {id
: $scope
.action
});
428 _
.each(actionInfo
.params
, function (param
, name
) {
430 defaultVal
= _
.cloneDeep(param
.default);
432 switch (param
.type
[0]) {
435 format
= param
.type
[0];
446 if (name
=== 'limit') {
449 if (name
=== 'debug') {
452 if (name
=== 'values') {
453 defaultVal
= defaultValues(defaultVal
);
455 if (name
=== 'loadOptions' && $scope
.action
=== 'getFields') {
459 ['id', 'name', 'label'],
460 ['id', 'name', 'label', 'abbr', 'description', 'color', 'icon']
464 param
.type
= ['string'];
466 $scope
.$bindToRoute({
467 expr
: 'params["' + name
+ '"]',
471 deep
: format
=== 'json'
474 if (typeof objectParams
[name
] !== 'undefined' && name
!== 'orderBy') {
475 $scope
.$watch('params.' + name
, function (values
) {
476 // Remove empty values
477 _
.each(values
, function (clause
, index
) {
478 if (!clause
|| !clause
[0]) {
479 $scope
.clearParam(name
, index
);
484 if (name
=== 'select' && actionInfo
.params
.having
) {
485 $scope
.$watchCollection('params.select', function(newSelect
) {
486 // Ignore row_count, it can't be used in HAVING clause
487 var select
= _
.without(newSelect
, 'row_count');
488 $scope
.havingOptions
.length
= 0;
489 // An empty select is an implicit *
490 if (!select
.length
) {
493 _
.each(select
, function(item
) {
495 pieces
= item
.split(' AS '),
496 alias
= _
.trim(pieces
[pieces
.length
- 1]).replace(':label', ':name');
498 if (alias
[alias
.length
- 1] === '*') {
499 if (alias
.length
> 1) {
500 joinEntity
= entityNameFromAlias(alias
.slice(0, -2));
502 var fieldList
= _
.filter(getEntity(joinEntity
).fields
, {custom_field_id
: null});
503 formatForSelect2(fieldList
, $scope
.havingOptions
, 'name', ['description', 'required', 'default_value'], alias
.slice(0, -1));
506 $scope
.havingOptions
.push({id
: alias
, text
: alias
});
511 if (typeof objectParams
[name
] !== 'undefined' || name
=== 'groupBy' || name
=== 'select' || name
=== 'join') {
512 $scope
.$watch('controls.' + name
, function(value
) {
514 $timeout(function() {
516 if (name
=== 'join') {
517 $scope
.params
[name
].push([field
+ ' AS ' + _
.snakeCase(field
), false]);
518 ctrl
.buildFieldList();
520 else if (typeof objectParams
[name
] === 'undefined') {
521 $scope
.params
[name
].push(field
);
523 var defaultOp
= _
.cloneDeep(objectParams
[name
]);
524 if (name
=== 'chain') {
525 var num
= $scope
.params
.chain
.length
;
526 defaultOp
[0] = field
;
527 field
= 'name_me_' + num
;
529 $scope
.params
[name
].push([field
, defaultOp
]);
531 $scope
.controls
[name
] = null;
537 ctrl
.buildFieldList();
538 $scope
.availableParams
= actionInfo
.params
;
543 function describeSqlFn(params
) {
545 _
.each(params
, function(param
) {
548 desc
+= _
.filter(param
.prefix
).join('|') + ' ';
550 if (param
.expr
=== 1) {
552 } else if (param
.expr
> 1) {
553 desc
+= 'expr, ... ';
556 desc
+= ' ' + _
.filter(param
.suffix
).join('|') + ' ';
559 return desc
.replace(/[ ]+/g, ' ');
562 function defaultValues(defaultVal
) {
563 _
.each($scope
.fields
, function(field
) {
564 if (field
.required
) {
565 defaultVal
.push([field
.id
, '']);
571 function stringify(value
, trim
) {
572 if (typeof value
=== 'undefined') {
575 var str
= JSON
.stringify(value
).replace(/,/g
, ', ');
577 str
= str
.slice(1, -1);
582 function writeCode() {
584 entity
= $scope
.entity
,
585 action
= $scope
.action
,
586 params
= getParams(),
587 index
= isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
),
589 if ($scope
.entity
&& $scope
.action
) {
591 if (action
.slice(0, 3) === 'get') {
592 result
= entity
.substr(0, 7) === 'Custom_' ? _
.camelCase(entity
.substr(7)) : entity
;
593 result
= lcfirst(action
.replace(/s$/, '').slice(3) || result
);
595 var results
= lcfirst(_
.isNumber(index
) ? result
: pluralize(result
)),
596 paramCount
= _
.size(params
),
599 switch ($scope
.selectedTab
.code
) {
603 var js
= "'" + entity
+ "', '" + action
+ "', {";
604 _
.each(params
, function(param
, key
) {
605 js
+= "\n " + key
+ ': ' + stringify(param
) +
606 (++i
< paramCount
? ',' : '');
607 if (key
=== 'checkPermissions') {
608 js
+= ' // IGNORED: permissions are always enforced from client-side requests';
612 if (index
|| index
=== 0) {
613 js
+= ', ' + JSON
.stringify(index
);
615 code
.js
= "CRM.api4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
616 code
.js2
= "CRM.api4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
617 code
.ang
= "crmApi4(" + js
+ ").then(function(" + results
+ ") {\n // do something with " + results
+ " array\n}, function(failure) {\n // handle failure\n});";
618 code
.ang2
= "crmApi4({" + results
+ ': [' + js
+ "]}).then(function(batch) {\n // do something with batch." + results
+ " array\n}, function(failure) {\n // handle failure\n});";
623 code
.php
= '$' + results
+ " = civicrm_api4('" + entity
+ "', '" + action
+ "', [";
624 _
.each(params
, function(param
, key
) {
625 code
.php
+= "\n '" + key
+ "' => " + phpFormat(param
, 4) + ',';
628 if (index
|| index
=== 0) {
629 code
.php
+= ', ' + phpFormat(index
);
634 code
.oop
= '$' + results
+ " = " + formatOOP(entity
, action
, params
, 2) + "\n ->execute()";
635 if (_
.isNumber(index
)) {
636 code
.oop
+= !index
? '\n ->first()' : (index
=== -1 ? '\n ->last()' : '\n ->itemAt(' + index
+ ')');
638 if (_
.isString(index
) || (_
.isPlainObject(index
) && !index
[0] && !index
['0'])) {
639 code
.oop
+= "\n ->indexBy('" + (_
.isPlainObject(index
) ? _
.keys(index
)[0] : index
) + "')";
641 if (_
.isArray(index
) || _
.isPlainObject(index
)) {
642 code
.oop
+= "\n ->column('" + (_
.isArray(index
) ? index
[0] : _
.values(index
)[0]) + "')";
646 if (!_
.isNumber(index
)) {
647 code
.oop
+= "foreach ($" + results
+ ' as $' + ((_
.isString(index
) && index
) ? index
+ ' => $' : '') + result
+ ') {\n // do something\n}';
653 code
.cv
= 'cv api4 ' + entity
+ '.' + action
+ " '" + stringify(params
) + "'";
656 _
.each($scope
.code
, function(vals
) {
657 _
.each(vals
, function(style
) {
658 style
.code
= code
[style
.name
] ? prettyPrintOne(code
[style
.name
]) : '';
664 function formatOOP(entity
, action
, params
, indent
) {
666 newLine
= "\n" + _
.repeat(' ', indent
),
667 perm
= params
.checkPermissions
=== false ? 'FALSE' : '';
668 if (entity
.substr(0, 7) !== 'Custom_') {
669 code
= "\\Civi\\Api4\\" + entity
+ '::' + action
+ '(' + perm
+ ')';
671 code
= "\\Civi\\Api4\\CustomValue::" + action
+ "('" + entity
.substr(7) + "'" + (perm
? ', ' : '') + perm
+ ")";
673 _
.each(params
, function(param
, key
) {
675 if (typeof objectParams
[key
] !== 'undefined' && key
!== 'chain') {
676 _
.each(param
, function(item
, index
) {
677 val
= phpFormat(index
) + ', ' + phpFormat(item
, 2 + indent
);
678 code
+= newLine
+ "->add" + ucfirst(key
).replace(/s$/, '') + '(' + val
+ ')';
680 } else if (key
=== 'where') {
681 _
.each(param
, function (clause
) {
682 if (clause
[0] === 'AND' || clause
[0] === 'OR' || clause
[0] === 'NOT') {
683 code
+= newLine
+ "->addClause(" + phpFormat(clause
[0]) + ", " + phpFormat(clause
[1]).slice(1, -1) + ')';
685 code
+= newLine
+ "->addWhere(" + phpFormat(clause
).slice(1, -1) + ")";
688 } else if (key
=== 'select') {
689 // selectRowCount() is a shortcut for addSelect('row_count')
690 if (isSelectRowCount(params
)) {
691 code
+= newLine
+ '->selectRowCount()';
692 param
= _
.without(param
, 'row_count');
694 // addSelect() is a variadic function & can take multiple arguments
696 code
+= newLine
+ '->addSelect(' + phpFormat(param
).slice(1, -1) + ')';
698 } else if (key
=== 'chain') {
699 _
.each(param
, function(chain
, name
) {
700 code
+= newLine
+ "->addChain('" + name
+ "', " + formatOOP(chain
[0], chain
[1], chain
[2], 2 + indent
);
701 code
+= (chain
.length
> 3 ? ',' : '') + (!_
.isEmpty(chain
[2]) ? newLine
: ' ') + (chain
.length
> 3 ? phpFormat(chain
[3]) : '') + ')';
704 else if (key
!== 'checkPermissions') {
705 code
+= newLine
+ "->set" + ucfirst(key
) + '(' + phpFormat(param
, 2 + indent
) + ')';
711 function isInt(value
) {
712 if (_
.isFinite(value
)) {
715 if (!_
.isString(value
)) {
718 return /^-{0,1}\d+$/.test(value
);
721 function formatMeta(resp
) {
723 _
.each(resp
, function(val
, key
) {
724 if (key
!== 'values' && !_
.isPlainObject(val
) && !_
.isFunction(val
)) {
725 ret
+= (ret
.length
? ', ' : '') + key
+ ': ' + (_
.isArray(val
) ? '[' + val
+ ']' : val
);
728 return prettyPrintOne(_
.escape(ret
));
731 $scope
.execute = function() {
732 $scope
.status
= 'info';
733 $scope
.loading
= true;
734 $http
.post(CRM
.url('civicrm/ajax/api4/' + $scope
.entity
+ '/' + $scope
.action
, {
735 params
: angular
.toJson(getParams()),
736 index
: isInt($scope
.index
) ? +$scope
.index
: parseYaml($scope
.index
)
739 'X-Requested-With': 'XMLHttpRequest'
741 }).then(function(resp
) {
742 $scope
.loading
= false;
743 $scope
.status
= resp
.data
&& resp
.data
.debug
&& resp
.data
.debug
.log
? 'warning' : 'success';
744 $scope
.debug
= debugFormat(resp
.data
);
746 formatMeta(resp
.data
),
747 prettyPrintOne('(' + resp
.data
.values
.length
+ ') ' + _
.escape(JSON
.stringify(resp
.data
.values
, null, 2)), 'js', 1)
750 $scope
.loading
= false;
751 $scope
.status
= 'danger';
752 $scope
.debug
= debugFormat(resp
.data
);
755 prettyPrintOne(_
.escape(JSON
.stringify(resp
.data
, null, 2)))
760 function debugFormat(data
) {
761 var debug
= data
.debug
? prettyPrintOne(_
.escape(JSON
.stringify(data
.debug
, null, 2)).replace(/\\n/g, "\n")) : null;
767 * Format value to look like php code
769 function phpFormat(val
, indent
) {
770 if (typeof val
=== 'undefined') {
773 if (val
=== null || val
=== true || val
=== false) {
774 return JSON
.stringify(val
).toUpperCase();
776 indent
= (typeof indent
=== 'number') ? _
.repeat(' ', indent
) : (indent
|| '');
778 baseLine
= indent
? indent
.slice(0, -2) : '',
779 newLine
= indent
? '\n' : '',
780 trailingComma
= indent
? ',' : '';
781 if ($.isPlainObject(val
)) {
782 $.each(val
, function(k
, v
) {
783 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ "'" + k
+ "' => " + phpFormat(v
);
785 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
787 if ($.isArray(val
)) {
788 $.each(val
, function(k
, v
) {
789 ret
+= (ret
? ', ' : '') + newLine
+ indent
+ phpFormat(v
);
791 return '[' + ret
+ trailingComma
+ newLine
+ baseLine
+ ']';
793 if (_
.isString(val
) && !_
.contains(val
, "'")) {
794 return "'" + val
+ "'";
796 return JSON
.stringify(val
).replace(/\$/g, '\\$');
799 function fetchMeta() {
800 crmApi4(getMetaParams
)
801 .then(function(data
) {
803 getEntity().actions
= data
.actions
;
809 // Help for an entity with no action selected
810 function showEntityHelp(entityName
) {
811 var entityInfo
= getEntity(entityName
);
812 setHelp($scope
.entity
, {
813 description
: entityInfo
.description
,
814 comment
: entityInfo
.comment
,
819 if (!$scope
.entity
) {
820 setHelp(ts('APIv4 Explorer'), {description
: docs
.description
, comment
: docs
.comment
, see
: docs
.see
});
821 } else if (!actions
.length
&& !getEntity().actions
) {
822 getMetaParams
.actions
= [$scope
.entity
, 'getActions', {chain
: {fields
: [$scope
.entity
, 'getFields', {action
: '$name'}]}}];
829 showEntityHelp($scope
.entity
);
832 // Update route when changing entity
833 $scope
.$watch('entity', function(newVal
, oldVal
) {
834 if (oldVal
!== newVal
) {
835 // Flush actions cache to re-fetch for new entity
837 $location
.url('/explorer/' + newVal
);
841 // Update route when changing actions
842 $scope
.$watch('action', function(newVal
, oldVal
) {
843 if ($scope
.entity
&& $routeParams
.api4action
!== newVal
&& !_
.isUndefined(newVal
)) {
844 $location
.url('/explorer/' + $scope
.entity
+ '/' + newVal
);
846 setHelp($scope
.entity
+ '::' + newVal
, _
.pick(_
.findWhere(getEntity().actions
, {name
: newVal
}), ['description', 'comment', 'see']));
850 $scope
.paramDoc = function(name
) {
851 return docs
.params
[name
];
854 $scope
.executeDoc = function() {
856 description
: ts('Runs API call on the CiviCRM database.'),
857 comment
: ts('Results and debugging info will be displayed below.')
859 if ($scope
.action
=== 'delete') {
860 doc
.WARNING
= ts('This API call will be executed on the real database. Deleting data cannot be undone.');
862 else if ($scope
.action
&& $scope
.action
.slice(0, 3) !== 'get') {
863 doc
.WARNING
= ts('This API call will be executed on the real database. It cannot be undone.');
868 $scope
.saveDoc = function() {
870 description
: ts('Save API call as a smart group.'),
871 comment
: ts('Create a SavedSearch using these API params to populate a smart group.') +
872 '\n\n' + ts('NOTE: you must select contact id as the only field.')
876 $scope
.$watch('params', writeCode
, true);
877 $scope
.$watch('index', writeCode
);
880 $scope
.save = function() {
881 $scope
.params
.limit
= $scope
.params
.offset
= 0;
882 if ($scope
.params
.chain
.length
) {
883 CRM
.alert(ts('Smart groups are not compatible with API chaining.'), ts('Error'), 'error', {expires
: 5000});
886 if ($scope
.params
.select
.length
!== 1 || !_
.includes($scope
.params
.select
[0], 'id')) {
887 CRM
.alert(ts('To create a smart group, the API must select contact id and no other fields.'), ts('Error'), 'error', {expires
: 5000});
893 visibility
: 'User and User Admin Only',
896 entity
: $scope
.entity
,
897 params
: JSON
.parse(angular
.toJson($scope
.params
))
899 model
.params
.version
= 4;
900 delete model
.params
.chain
;
901 delete model
.params
.debug
;
902 delete model
.params
.limit
;
903 delete model
.params
.offset
;
904 delete model
.params
.orderBy
;
905 delete model
.params
.checkPermissions
;
906 var options
= CRM
.utils
.adjustDialogDefaults({
909 title
: ts('Save smart group')
911 dialogService
.open('saveSearchDialog', '~/api4Explorer/SaveSearch.html', model
, options
);
915 angular
.module('api4Explorer').controller('SaveSearchCtrl', function($scope
, crmApi4
, dialogService
) {
916 var ts
= $scope
.ts
= CRM
.ts(),
917 model
= $scope
.model
;
918 $scope
.groupEntityRefParams
= {
921 params
: {is_hidden
: 0, is_active
: 1, 'saved_search_id.api_entity': model
.entity
},
922 extra
: ['saved_search_id', 'description', 'visibility', 'group_type']
926 minimumInputLength
: 0,
927 placeholder
: ts('Select existing group')
930 if (!CRM
.checkPerm('administer reserved groups')) {
931 $scope
.groupEntityRefParams
.api
.params
.is_reserved
= 0;
934 administerReservedGroups
: CRM
.checkPerm('administer reserved groups')
936 $scope
.options
= CRM
.vars
.api4
.groupOptions
;
937 $scope
.$watch('model.id', function(id
) {
939 _
.assign(model
, $('#api-save-search-select-group').select2('data').extra
);
942 $scope
.cancel = function() {
943 dialogService
.cancel('saveSearchDialog');
945 $scope
.save = function() {
946 $('.ui-dialog:visible').block();
947 var group
= model
.id
? {id
: model
.id
} : {title
: model
.title
};
948 group
.description
= model
.description
;
949 group
.visibility
= model
.visibility
;
950 group
.group_type
= model
.group_type
;
951 group
.saved_search_id
= '$id';
953 api_entity
: model
.entity
,
954 api_params
: model
.params
957 savedSearch
.id
= model
.saved_search_id
;
959 crmApi4('SavedSearch', 'save', {records
: [savedSearch
], chain
: {group
: ['Group', 'save', {'records': [group
]}]}})
960 .then(function(result
) {
961 dialogService
.close('saveSearchDialog', result
[0]);
966 angular
.module('api4Explorer').directive('crmApi4Clause', function() {
969 data
: '<crmApi4Clause'
971 templateUrl
: '~/api4Explorer/Clause.html',
972 controller: function ($scope
, $element
, $timeout
) {
973 var ts
= $scope
.ts
= CRM
.ts(),
974 ctrl
= $scope
.$ctrl
= this;
975 this.conjunctions
= {AND
: ts('And'), OR
: ts('Or'), NOT
: ts('Not')};
976 this.operators
= CRM
.vars
.api4
.operators
;
979 connectWith
: '.api4-clause-group-sortable',
980 containment
: $element
.closest('.api4-clause-fieldset'),
986 this.addGroup = function(op
) {
987 $scope
.data
.clauses
.push([op
, []]);
990 this.removeGroup = function() {
991 $scope
.data
.groupParent
.splice($scope
.data
.groupIndex
, 1);
994 function onSort(event
, ui
) {
995 $($element
).closest('.api4-clause-fieldset').toggleClass('api4-sorting', event
.type
=== 'sortstart');
996 $('.api4-input.form-inline').css('margin-left', '');
999 // Indent clause while dragging between nested groups
1000 function onSortOver(event
, ui
) {
1003 offset
= $(ui
.placeholder
).offset().left
- $(ui
.sender
).offset().left
;
1005 $('.api4-input.form-inline.ui-sortable-helper').css('margin-left', '' + offset
+ 'px');
1008 this.addClause = function() {
1009 $timeout(function() {
1010 if (ctrl
.newClause
) {
1011 $scope
.data
.clauses
.push([ctrl
.newClause
, '=', '']);
1012 ctrl
.newClause
= null;
1016 $scope
.$watch('data.clauses', function(values
) {
1017 // Iterate in reverse order so index doesn't get out-of-sync during splice
1018 _
.forEachRight(values
, function(clause
, index
) {
1019 // Remove empty values
1020 if (index
>= ($scope
.data
.skip
|| 0)) {
1021 if (typeof clause
!== 'undefined' && !clause
[0]) {
1022 values
.splice(index
, 1);
1024 // Add/remove value if operator allows for one
1025 else if (typeof clause
[1] === 'string' && _
.contains(clause
[1], 'NULL')) {
1027 } else if (typeof clause
[1] === 'string' && clause
.length
=== 2) {
1037 angular
.module('api4Explorer').directive('api4ExpValue', function($routeParams
, crmApi4
) {
1040 data
: '=api4ExpValue'
1043 link: function (scope
, element
, attrs
, ctrl
) {
1044 var ts
= scope
.ts
= CRM
.ts(),
1045 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], scope
.data
.op
),
1046 entity
= $routeParams
.api4entity
,
1047 action
= scope
.data
.action
|| $routeParams
.api4action
;
1049 function destroyWidget() {
1050 var $el
= $(element
);
1051 if ($el
.is('.crm-form-date-wrapper .crm-hidden-date')) {
1052 $el
.crmDatepicker('destroy');
1054 if ($el
.is('.select2-container + input')) {
1055 $el
.crmEntityRef('destroy');
1057 $(element
).removeData().removeAttr('type').removeAttr('placeholder').show();
1060 function makeWidget(field
, op
) {
1061 var $el
= $(element
),
1062 inputType
= field
.input_type
,
1063 dataType
= field
.data_type
;
1065 op
= field
.serialize
|| dataType
=== 'Array' ? 'IN' : '=';
1067 multi
= _
.includes(['IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'], op
);
1068 if (op
=== 'IS NULL' || op
=== 'IS NOT NULL') {
1072 if (inputType
=== 'Date') {
1073 if (_
.includes(['=', '!=', '<>', '<', '>=', '<', '<='], op
)) {
1074 $el
.crmDatepicker({time
: (field
.input_attrs
&& field
.input_attrs
.time
) || false});
1076 } else if (_
.includes(['=', '!=', '<>', 'IN', 'NOT IN'], op
) && (field
.fk_entity
|| field
.options
|| dataType
=== 'Boolean')) {
1077 if (field
.options
) {
1078 var id
= field
.pseudoconstant
|| 'id';
1079 $el
.addClass('loading').attr('placeholder', ts('- select -')).crmSelect2({multiple
: multi
, data
: [{id
: '', text
: ''}]});
1080 loadFieldOptions(field
.entity
|| entity
).then(function(data
) {
1081 var options
= _
.transform(data
[field
.name
].options
, function(options
, opt
) {
1082 options
.push({id
: opt
[id
], text
: opt
.label
, description
: opt
.description
, color
: opt
.color
, icon
: opt
.icon
});
1084 $el
.removeClass('loading').crmSelect2({data
: options
, multiple
: multi
});
1086 } else if (field
.fk_entity
) {
1087 $el
.crmEntityRef({entity
: field
.fk_entity
, select
:{multiple
: multi
}});
1088 } else if (dataType
=== 'Boolean') {
1089 $el
.attr('placeholder', ts('- select -')).crmSelect2({allowClear
: false, multiple
: multi
, placeholder
: ts('- select -'), data
: [
1090 {id
: 'true', text
: ts('Yes')},
1091 {id
: 'false', text
: ts('No')}
1094 } else if (dataType
=== 'Integer' && !multi
) {
1095 $el
.attr('type', 'number');
1099 function loadFieldOptions(entity
) {
1100 if (!fieldOptions
[entity
+ action
]) {
1101 fieldOptions
[entity
+ action
] = crmApi4(entity
, 'getFields', {
1102 loadOptions
: ['id', 'name', 'label', 'description', 'color', 'icon'],
1104 where
: [['options', '!=', false]],
1108 return fieldOptions
[entity
+ action
];
1111 // Copied from ng-list but applied conditionally if field is multi-valued
1112 var parseList = function(viewValue
) {
1113 // If the viewValue is invalid (say required but empty) it will be `undefined`
1114 if (_
.isUndefined(viewValue
)) return;
1123 _
.each(viewValue
.split(','), function(value
) {
1124 if (value
) list
.push(_
.trim(value
));
1131 // Copied from ng-list
1132 ctrl
.$parsers
.push(parseList
);
1133 ctrl
.$formatters
.push(function(value
) {
1134 return _
.isArray(value
) ? value
.join(', ') : value
;
1137 // Copied from ng-list
1138 ctrl
.$isEmpty = function(value
) {
1139 return !value
|| !value
.length
;
1142 scope
.$watchCollection('data', function(data
) {
1144 var field
= getField(data
.field
, entity
, action
);
1145 if (field
&& data
.format
!== 'plain') {
1146 makeWidget(field
, data
.op
);
1154 angular
.module('api4Explorer').directive('api4ExpChain', function(crmApi4
) {
1157 chain
: '=api4ExpChain',
1161 templateUrl
: '~/api4Explorer/Chain.html',
1162 link: function (scope
, element
, attrs
) {
1163 var ts
= scope
.ts
= CRM
.ts();
1165 function changeEntity(newEntity
, oldEntity
) {
1166 // When clearing entity remove this chain
1168 scope
.chain
[0] = '';
1171 // Reset action && index
1172 if (newEntity
!== oldEntity
) {
1173 scope
.chain
[1][1] = scope
.chain
[1][2] = '';
1175 if (getEntity(newEntity
).actions
) {
1178 crmApi4(newEntity
, 'getActions', {chain
: {fields
: [newEntity
, 'getFields', {action
: '$name'}]}})
1179 .then(function(data
) {
1180 getEntity(data
.entity
).actions
= data
;
1181 if (data
.entity
=== scope
.chain
[1][0]) {
1188 function setActions() {
1189 scope
.actions
= [''].concat(_
.pluck(getEntity(scope
.chain
[1][0]).actions
, 'name'));
1192 // Set default params when choosing action
1193 function changeAction(newAction
, oldAction
) {
1195 // Prepopulate links
1196 if (newAction
&& newAction
!== oldAction
) {
1198 scope
.chain
[1][3] = '';
1199 // Look for links back to main entity
1200 _
.each(entityFields(scope
.chain
[1][0]), function(field
) {
1201 if (field
.fk_entity
=== scope
.mainEntity
) {
1202 link
= [field
.name
, '$id'];
1205 // Look for links from main entity
1206 if (!link
&& newAction
!== 'create') {
1207 _
.each(entityFields(scope
.mainEntity
), function(field
) {
1208 if (field
.fk_entity
=== scope
.chain
[1][0]) {
1209 link
= ['id', '$' + field
.name
];
1210 // Since we're specifying the id, set index to getsingle
1211 scope
.chain
[1][3] = '0';
1215 if (link
&& _
.contains(['get', 'update', 'replace', 'delete'], newAction
)) {
1216 scope
.chain
[1][2] = '{where: [[' + link
[0] + ', =, ' + link
[1] + ']]}';
1218 else if (link
&& _
.contains(['create'], newAction
)) {
1219 scope
.chain
[1][2] = '{values: {' + link
[0] + ': ' + link
[1] + '}}';
1221 else if (link
&& _
.contains(['save'], newAction
)) {
1222 scope
.chain
[1][2] = '{records: [{' + link
[0] + ': ' + link
[1] + '}]}';
1224 scope
.chain
[1][2] = '{}';
1229 scope
.$watch("chain[1][0]", changeEntity
);
1230 scope
.$watch("chain[1][1]", changeAction
);
1235 function getEntity(entityName
) {
1236 return _
.findWhere(schema
, {name
: entityName
});
1239 function entityFields(entityName
, action
) {
1240 var entity
= getEntity(entityName
);
1241 if (entity
&& action
&& entity
.actions
) {
1242 return _
.findWhere(entity
.actions
, {name
: action
}).fields
;
1244 return _
.result(entity
, 'fields');
1247 function getExplicitJoins() {
1248 return _
.transform(params
.join
, function(joins
, join
) {
1249 var j
= join
[0].split(' AS '),
1250 joinEntity
= _
.trim(j
[0]),
1251 joinAlias
= _
.trim(j
[1]) || joinEntity
.toLowerCase();
1252 joins
[joinAlias
] = joinEntity
;
1256 function getField(fieldName
, entity
, action
) {
1257 var suffix
= fieldName
.split(':')[1];
1258 fieldName
= fieldName
.split(':')[0];
1259 var fieldNames
= fieldName
.split('.');
1260 var field
= get(entity
, fieldNames
);
1261 if (field
&& suffix
) {
1262 field
.pseudoconstant
= suffix
;
1266 function get(entity
, fieldNames
) {
1267 if (fieldNames
.length
=== 1) {
1268 return _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0]});
1270 var comboName
= _
.findWhere(entityFields(entity
, action
), {name
: fieldNames
[0] + '.' + fieldNames
[1]});
1274 var linkName
= fieldNames
.shift(),
1275 newEntity
= getExplicitJoins()[linkName
] || _
.findWhere(links
[entity
], {alias
: linkName
}).entity
;
1276 return get(newEntity
, fieldNames
);
1280 // Collapsible optgroups for select2
1283 .on('select2-open', function(e
) {
1284 if ($(e
.target
).hasClass('collapsible-optgroups')) {
1286 .off('.collapseOptionGroup')
1287 .addClass('collapsible-optgroups-enabled')
1288 .on('click.collapseOptionGroup', '.select2-result-with-children > .select2-result-label', function() {
1289 $(this).parent().toggleClass('optgroup-expanded');
1293 .on('select2-close', function() {
1294 $('#select2-drop').off('.collapseOptionGroup').removeClass('collapsible-optgroups-enabled');
1297 })(angular
, CRM
.$, CRM
._
);