Basics
This feature allows the admin to define customized API routines. These routines can be executed via an API call using the Custom API identifier.
This Grid allows Users to add custom API calls.
Identifier: This is the unique identifier for the specific API logic. This identifier is used to invoke this Custom Logic with an API Call.
Description: A description field to provide additional information as to the purpose of the API logic.
Logic tab
The Logic tab is where the Custom Logic can be written and reviewed.
A User can quickly review the code written for the specific event with the button.
Users will be limited to the white-listed functions for PHP in PCR-360. A list of the functions can be seen in PCR-360 by clicking on the button.
- 1 Allowed Functions
- 1.1 Array
- 1.2 Class/Object
- 1.3 Class/Interface Access
- 1.4 JSON
- 1.5 cURL
- 1.6 Date/Time
- 1.7 Exception Handling
- 1.8 Logical
- 1.9 Mathematical
- 1.10 PCR-360 Data
- 1.11 PCR-360 Debug
- 1.12 PCR-360 Events
- 1.13 PCR-360 Reports
- 1.14 PCR-360 Utility
- 1.15 PCR-360 Validation
- 1.16 Regular Expressions (Perl-Compatible)
- 1.17 String
- 1.18 URLs
- 1.19 Variable Handling
- 1.20 Additional Functions
For reference on all non-PCR-360 Functions, please refer to the PHP Documentation.
Allowed Functions
Array
array_column, array_chunk, array_combine, array_count_values, array_diff, array_diff_assoc, array_diff_key, array_fill, array_fill_keys, array_flip, array_intersect, array_intersect_assoc, array_intersect_key, array_intersect, array_is_list, array_key_exists, array_keys, array_merge, array_merge_recursive, array_multisort, array_pad, array_pop, array_product, array_push, array_rand, array_reduce, array_replace, array_replace_recursive, array_reverse, array_search, array_shift, array_slice, array_splice, array_sum, array_unique, array_unshift, array_values, compact, count, current, end, extract, in_array, key_exists, krsort, ksort, list, next, pos, prev, range, reset, rsort, shuffle, sort
Class/Object
get_called_class, get_class, is_a, is_subclass_of
Class/Interface Access
DateInterval, DateTime, Exception, PCR_Event, PCR_Exception, throwable
JSON
json_decode, json_encode, json_last_error, json_last_error_msg, json_validate
cURL
curl_close, curl_copy_handle, curl_errno, curl_error, curl_escape, curl_exec, curl_getinfo, curl_init, curl_pause, curl_reset, curl_setopt, curl_setopt_array, curl_strerror, curl_unescape
Date/Time
add, diff, date_add, date_create, date_create_from_format, date_diff, date_format, date_get_last_errors, date_interval_create_from_string, date_interval_format, date_parse, date_parse_from_format, date_sub, date_time_set, date_timestamp_get, date_timestamp_set, date_timezone_get, date_timezone_set, date, format, mktime, microtime, setDate, setTime, setTimestamp, strtotime, sub, time
Exception Handling
getPrevious, getCode, getLine
Logical
as, if, break, case, catch, continue, default, do, else, elseif, finally, for, foreach, function, match, new, return, switch, try, while
Mathematical
abs, base_convert, bindec, ceil, exp, floor, hexdec, max, min, octdec, pow, rand, round, srand, trunc
PCR-360 Data
call, listFindCode, listFindValue, listGetByCode, query
call Function: Calling API Logic
array $this->call(string $apiFunctionToCall, array $params, bool $commitOnSuccess);
query Function: Querying Data
array $this->query(string $sql, array $bind_parameters);
listGetByCode Function: Retrieving List Values
mixed $this->listGetByCode(string $list_type, mixed $list_code);
listFindValue Function: Retrieving List Values
string $this->listFindValue(int $recid);
listFindCode Function: Retrieving List Values
string $this->listFindCode(int $recid);
PCR-360 Debug
debug, error_log
debug Function: Debugging Custom Logic
$this->debug(mixed $debug);
PCR-360 Events
attach, attachDb, callCustomEvent, detach, detachDb, trigger
PCR-360 Reports
addError, assign, barcode, loadReport
PCR-360 Utility
arrayToCsv, createFile, sendSystemMessage
arrayToCsv Function: Building CSV Data
string $this->arrayToCsv(array $data, string $delimiter = ',', string $enclosure = '"')
createFile Function: Creating Inbound/Outbound Files
int|false $this->createFile(string $filename, string|array $content, string $location = 'OUTBOUND', bool $overwrite = false);
sendSystemMessage Function: Sending a System Message
bool $this->sendSystemMessage(string $subject, string $body, int $contactRecid, string $identifier);
PCR-360 Validation
setError, setMessage, setWarning
setError Function: Errors and Warning in Validation
Sets a validation error message. This messages output in the UI if the validation logic returns false. If this function is called multiple times, only the message from the last calls is displayed.
$this->setError(string $message);
setWarning Function: Errors and Warning in Validation
Sets the validation warning message. This messages output in the UI only if the logic does not return false. If this function is called multiple times, only the message from the last calls is displayed.
$this->setWarning(string $message);
Regular Expressions (Perl-Compatible)
preg_filter, preg_grep, preg_last_error, preg_match, preg_match_all, preg_quote, preg_replace, preg_split
String
addslashes, bin2hex, chr, explode, html_entity_decode, htmlentities, htmlspecialchars, htmlspecialchars_decode, implode, ltrim, nl2br, number_format, rtrim, sprintf, str_contains, str_ends_with, str_getcsv, str_ireplace, str_pad, str_repeat, str_replace, str_shuffle, str_split, str_starts_with, strcasecmp, strip_tags, stripslashes, strtolower, strtoupper, substr_compare, substr_count, substr_replace, substr, stristr, strlen, stripos, strpos, strripos, strrpos, strstr, trim, wordwrap
URLs
base64_decode, base64_encode, get_headers, http_build_query, parse_url, rawurldecode, rawurlencode, urldecode, urlencode
Variable Handling
gettype, is_array, is_bool, is_float, is_int, is_iterable, is_numeric, is_object, is_string, isset
Additional Functions
Contact PCR if you find a function that is not allowed, but would like to use.
Debug tab
The Debug tab shows the results of debug function calls. This debug information is cleared after 24 hours.
Prerequisites
This feature is intended for Administrators and an understanding of PHP language and syntax is required. You must also be aware of language compatibility for the version of PHP installed on the webserver. For logic that requires querying other data, an understanding of SQL is necessary, particularly variants specific to your database platform.
Usage
In a typical API routine, incoming request data is processed and an outgoing response is built.
Scope
API routines are written and executed within a subset of PHP syntax and at run time they have scope access to two arrays of data $request and $response. For security purposes, only a subset of PHP functions have been whitelisted.
$request
A key/value paired array of the data that is POSTED to the API REST request. The contents of this request will vary depending on how and what is making the API request. There is no need to decode the $request data.
$response
A key/value paired array of the data that should be returned in the API REST response.
Example
Using cURL, we invoke a Custom API called hello-world:
curl -X POST -d '{"foo":"bar"}' http://DOMAIN/api/API_KEY/hello-world.json -H Content-Type:application/json
The .json extension requests data returned JSON encoded
The Content-Type header directive for "application/json" specifies the incoming request data is JSON encoded
Within the Custom API logic, $request would contain the decoded request data:
array( "foo" => "bar" )
The response can be built by assigning data to $response.
$response["hello"] = "world";
The given cURL request will return a JSON formatted response:
{ "hello" : "world" }
Syntax
Custom API shares a set of common syntax and available functions with the other types of Custom Logic.
- 1 Allowed Functions
- 1.1 Array
- 1.2 Class/Object
- 1.3 Class/Interface Access
- 1.4 JSON
- 1.5 cURL
- 1.6 Date/Time
- 1.7 Exception Handling
- 1.8 Logical
- 1.9 Mathematical
- 1.10 PCR-360 Data
- 1.11 PCR-360 Debug
- 1.12 PCR-360 Events
- 1.13 PCR-360 Reports
- 1.14 PCR-360 Utility
- 1.15 PCR-360 Validation
- 1.16 Regular Expressions (Perl-Compatible)
- 1.17 String
- 1.18 URLs
- 1.19 Variable Handling
- 1.20 Additional Functions
For reference on all non-PCR-360 Functions, please refer to the PHP Documentation.
Allowed Functions
Array
array_column, array_chunk, array_combine, array_count_values, array_diff, array_diff_assoc, array_diff_key, array_fill, array_fill_keys, array_flip, array_intersect, array_intersect_assoc, array_intersect_key, array_intersect, array_is_list, array_key_exists, array_keys, array_merge, array_merge_recursive, array_multisort, array_pad, array_pop, array_product, array_push, array_rand, array_reduce, array_replace, array_replace_recursive, array_reverse, array_search, array_shift, array_slice, array_splice, array_sum, array_unique, array_unshift, array_values, compact, count, current, end, extract, in_array, key_exists, krsort, ksort, list, next, pos, prev, range, reset, rsort, shuffle, sort
Class/Object
get_called_class, get_class, is_a, is_subclass_of
Class/Interface Access
DateInterval, DateTime, Exception, PCR_Event, PCR_Exception, throwable
JSON
json_decode, json_encode, json_last_error, json_last_error_msg, json_validate
cURL
curl_close, curl_copy_handle, curl_errno, curl_error, curl_escape, curl_exec, curl_getinfo, curl_init, curl_pause, curl_reset, curl_setopt, curl_setopt_array, curl_strerror, curl_unescape
Date/Time
add, diff, date_add, date_create, date_create_from_format, date_diff, date_format, date_get_last_errors, date_interval_create_from_string, date_interval_format, date_parse, date_parse_from_format, date_sub, date_time_set, date_timestamp_get, date_timestamp_set, date_timezone_get, date_timezone_set, date, format, mktime, microtime, setDate, setTime, setTimestamp, strtotime, sub, time
Exception Handling
getPrevious, getCode, getLine
Logical
as, if, break, case, catch, continue, default, do, else, elseif, finally, for, foreach, function, match, new, return, switch, try, while
Mathematical
abs, base_convert, bindec, ceil, exp, floor, hexdec, max, min, octdec, pow, rand, round, srand, trunc
PCR-360 Data
call, listFindCode, listFindValue, listGetByCode, query
call Function: Calling API Logic
array $this->call(string $apiFunctionToCall, array $params, bool $commitOnSuccess);
query Function: Querying Data
array $this->query(string $sql, array $bind_parameters);
listGetByCode Function: Retrieving List Values
mixed $this->listGetByCode(string $list_type, mixed $list_code);
listFindValue Function: Retrieving List Values
string $this->listFindValue(int $recid);
listFindCode Function: Retrieving List Values
string $this->listFindCode(int $recid);
PCR-360 Debug
debug, error_log
debug Function: Debugging Custom Logic
$this->debug(mixed $debug);
PCR-360 Events
attach, attachDb, callCustomEvent, detach, detachDb, trigger
PCR-360 Reports
addError, assign, barcode, loadReport
PCR-360 Utility
arrayToCsv, createFile, sendSystemMessage
arrayToCsv Function: Building CSV Data
string $this->arrayToCsv(array $data, string $delimiter = ',', string $enclosure = '"')
createFile Function: Creating Inbound/Outbound Files
int|false $this->createFile(string $filename, string|array $content, string $location = 'OUTBOUND', bool $overwrite = false);
sendSystemMessage Function: Sending a System Message
bool $this->sendSystemMessage(string $subject, string $body, int $contactRecid, string $identifier);
PCR-360 Validation
setError, setMessage, setWarning
setError Function: Errors and Warning in Validation
Sets a validation error message. This messages output in the UI if the validation logic returns false. If this function is called multiple times, only the message from the last calls is displayed.
$this->setError(string $message);
setWarning Function: Errors and Warning in Validation
Sets the validation warning message. This messages output in the UI only if the logic does not return false. If this function is called multiple times, only the message from the last calls is displayed.
$this->setWarning(string $message);
Regular Expressions (Perl-Compatible)
preg_filter, preg_grep, preg_last_error, preg_match, preg_match_all, preg_quote, preg_replace, preg_split
String
addslashes, bin2hex, chr, explode, html_entity_decode, htmlentities, htmlspecialchars, htmlspecialchars_decode, implode, ltrim, nl2br, number_format, rtrim, sprintf, str_contains, str_ends_with, str_getcsv, str_ireplace, str_pad, str_repeat, str_replace, str_shuffle, str_split, str_starts_with, strcasecmp, strip_tags, stripslashes, strtolower, strtoupper, substr_compare, substr_count, substr_replace, substr, stristr, strlen, stripos, strpos, strripos, strrpos, strstr, trim, wordwrap
URLs
base64_decode, base64_encode, get_headers, http_build_query, parse_url, rawurldecode, rawurlencode, urldecode, urlencode
Variable Handling
gettype, is_array, is_bool, is_float, is_int, is_iterable, is_numeric, is_object, is_string, isset
Additional Functions
Contact PCR if you find a function that is not allowed, but would like to use.
UDF Identifiers
UDF parameters are all lower case when processed by PCR-360. Since Organizations can create their own UDF fields, the generic use of IDENTIFIER is used as a placeholder for actual UDF Identifiers.
Invoking Custom API
Read more about Making a Request for APIs and reading into the Custom API.
Example
This Custom API script was written to process incoming API calls from Slack (a team chat program we use internally at PCR).
<?php /** * Type: Custom Logic * Identifier: helpdesk */ // The incoming payload from Slack is JSON encoded so we need to decode it... // Usually there is no need to decode the request parameter. However, Slack // sends the "payload" parameter as a JSON encoded string $payload = json_decode($request["payload"], true); $user = $payload["user"]["name"]; $callbackId = explode("-",$payload["callback_id"]); $iconUrl = "https://www.iconexperience.com/_img/v_collection_png/24x24/plain/"; $icon = "error.png"; // find the Contact for this User - using the query function is best with // bound parameters instead of placing them directly into the query string. // This protects the database against injection threats $contacts = $this->query( "SELECT RECID FROM CONTACTS C LEFT JOIN V_UDF UDF ON UDF.VALUE_TABLE_NAME = 'CONTACTS' AND C.RECID = VALUE_TABLE_RECID WHERE UDF.VALUE = :slack_user", [":slack_user" => "@".$user] ); if(!empty($contacts)){ // the query function always returns an array // of rows so we need to look at the first index $contact = $contacts[0]; $incidents = $this->query( "SELECT SD.*, D.CODE, L.VALUE AS STATUS FROM SERVICE_DESK SD LEFT JOIN DEPT_HIERARCHY D ON SD.D_OWNER_DEPT_HIERARCHY_RECID = D.RECID LEFT JOIN LISTS L ON SD.SD_STATUS_LISTS_RECID = L.RECID WHERE SD_NUMBER = :incident", [":incident" => $callbackId[0]] ); if(!empty($incidents)){ $incident = $incidents[0]; $workflow = $this->query( "SELECT SDWF.*, CONCAT(C.LAST_NAME,', ',C.FIRST_NAME) AS WORKER, L.CODE AS STATUS FROM SERVICE_DESK_WORKFLOW SDWF LEFT JOIN CONTACTS C ON C.RECID = SDWF.WORKER_CONTACTS_RECID LEFT JOIN LISTS L ON SDWF.SD_WF_STATUS_LISTS_RECID = L.RECID WHERE SERVICE_DESK_RECID = :sd_recid AND SDWF.RECID = :recid", [ ":sd_recid" => $incident["RECID"], ":recid" => $callbackId[2] ] ); if(!empty($workflow)){ $wf = $workflow[0]; if(empty($wf["WORKER"])){ if($wf["STATUS"] == "PENDING"){ if(Core_Model_Api_Servicedesk::assignWorkflow( $wf["RECID"], $contact["RECID"] )){ $assigned = "Assigned to @{$user}"; $icon = "checkbox.png"; } else { $assigned = "Error: Failed to Assign Workflow..."; } } else { $assigned = "Error: WF is not Pending..."; } } else { $assigned = "WF Already Assigned to {$wf["WORKER"]}"; $icon = "information.png"; } } else { $assigned = "Error: Cannot find Workflow {$callbackId[1]} on {$callbackId[0]}..."; } } else { $assigned = "Error: Cannot find Incident [{$callbackId[0]}]..."; } } else { $assigned = "Error: Cannot find User [{$payload["user"]["name"]}]..."; } $orig = $payload["original_message"]; // the response array is the data that is returned to the original API request $response = [ "text" => $orig["text"], "attachments" => [[ "title" => $orig["attachments"][0]["title"], "title_link" => $orig["attachments"][0]["title_link"], "text" => $orig["attachments"][0]["text"], "footer" => $assigned, "footer_icon" => $iconUrl.$icon, "ts" => time(), ]] ];