Skip to main content
Skip table of contents

Custom API

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 

Validate PHP
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

Help
button.

Allowed Functions

Array

explode , implode , is_array , in_array , array_diff , array_diff_keycount

JSON

json_decode , json_encode

cURL

curl_init , curl_setopt , curl_exec , curl_errno , curl_error , curl_getinfo , curl_close , http_build_query

Date/Time

date , time , mktime , strtotime , DateTime , DateInterval , add , sub, diff, format , setTimestamp , setTime , setDate

Debug

error_log, debug

Debug Function
PHP
$this->debug();

Note: The debug command outputs to a cache which is then displayed in the Debug tab/grid for the Custom Logic you are debugging.

Logical

if , elseif , else , switch , case , default , break , for , foreach , as , while , do-while , return , new

Mathematical

round , trunc ,ceil , floor , rand , srand , pow , exp , abs , max , min , bindec , hexdec , octdec , base_convert

PCR-360 Data

call , query , listGetByCode , listFindValue , listFindCode

Call Function
PHP
// $apiFunction Examples: saveService, saveServiceDesk, saveContact, saveCable, saveGla, saveEquipment, etc.
$this->call(string $apiFunctionToCall, array $params)


Query Function
PHP
array $this->query ( string $sql, array $bind_parameters );


listGetByCode Function
PHP
mixed $this->listGetByCode ( string $list_type, mixed $list_code );


listFindValue Function
PHP
string $this->listGetByCode ( int $recid );


listFindCode Function
PHP
string $this->listGetByCode ( int $recid );

String

is_numeric , strtolower , strtoupper , substr , stristr , strstr , stripos , strpos , strripos , strrpos , addslashes , chr , trim , ltrim , rtrim , str_replace , preg_match , preg_replace , preg_splitstr_pad , sprintf , substr_replace , strlen

Additional Functions

Contact PCR if you find a function that is not allowed, but would like to use. 

Validation functions

setError

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.

setError Function
PHP
$this->setError ( string $message );

setWarning

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.

setWarning Function
PHP
$this->setWarning ( string $message );

Triggering Events

PCR_Event, trigger, attach, attachDb

In this example the GLA Replace Event is triggered with specific parameters. For detailed information on which Events can be triggered, and how to trigger those Events, please navigate to the Triggerable Events List page.

PCR_Event Functions
PHP
PCR_Event::attachDb("replace-gla", [
    "Application_Model_Gla_Gla" => "eventReplaceGla"
]);
PCR_Event::trigger("replace-gla", [
	"contact" => 12345,        // Contact RECID
    "users_recid" => 456,      // Users RECID
    "glaRecid" => [1111],      // Old GLA RECID
    "replaceGlaRecid" => 2222, // Replacement GLA RECID
    "setInactiveGla" => true,
    "comment" => "This is a comment",
]);


Debug tab

Debug Tab Example

Debug Tab Example

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:

PHP
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:

PHP
array(
  "foo" => "bar"
)


The response can be built by assigning data to $response.

PHP
$response["hello"] = "world";


The given cURL request will return a JSON formatted response:

PHP
{ "hello" : "world" }


Syntax

Custom API shares a set of common syntax and available functions with the other types of Custom Logic.

Allowed Functions

Array

explode , implode , is_array , in_array , array_diff , array_diff_keycount

JSON

json_decode , json_encode

cURL

curl_init , curl_setopt , curl_exec , curl_errno , curl_error , curl_getinfo , curl_close , http_build_query

Date/Time

date , time , mktime , strtotime , DateTime , DateInterval , add , sub, diff, format , setTimestamp , setTime , setDate

Debug

error_log, debug

Debug Function
PHP
$this->debug();

Note: The debug command outputs to a cache which is then displayed in the Debug tab/grid for the Custom Logic you are debugging.

Logical

if , elseif , else , switch , case , default , break , for , foreach , as , while , do-while , return , new

Mathematical

round , trunc ,ceil , floor , rand , srand , pow , exp , abs , max , min , bindec , hexdec , octdec , base_convert

PCR-360 Data

call , query , listGetByCode , listFindValue , listFindCode

Call Function
PHP
// $apiFunction Examples: saveService, saveServiceDesk, saveContact, saveCable, saveGla, saveEquipment, etc.
$this->call(string $apiFunctionToCall, array $params)


Query Function
PHP
array $this->query ( string $sql, array $bind_parameters );


listGetByCode Function
PHP
mixed $this->listGetByCode ( string $list_type, mixed $list_code );


listFindValue Function
PHP
string $this->listGetByCode ( int $recid );


listFindCode Function
PHP
string $this->listGetByCode ( int $recid );

String

is_numeric , strtolower , strtoupper , substr , stristr , strstr , stripos , strpos , strripos , strrpos , addslashes , chr , trim , ltrim , rtrim , str_replace , preg_match , preg_replace , preg_splitstr_pad , sprintf , substr_replace , strlen

Additional Functions

Contact PCR if you find a function that is not allowed, but would like to use. 

Validation functions

setError

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.

setError Function
PHP
$this->setError ( string $message );

setWarning

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.

setWarning Function
PHP
$this->setWarning ( string $message );

Triggering Events

PCR_Event, trigger, attach, attachDb

In this example the GLA Replace Event is triggered with specific parameters. For detailed information on which Events can be triggered, and how to trigger those Events, please navigate to the Triggerable Events List page.

PCR_Event Functions
PHP
PCR_Event::attachDb("replace-gla", [
    "Application_Model_Gla_Gla" => "eventReplaceGla"
]);
PCR_Event::trigger("replace-gla", [
	"contact" => 12345,        // Contact RECID
    "users_recid" => 456,      // Users RECID
    "glaRecid" => [1111],      // Old GLA RECID
    "replaceGlaRecid" => 2222, // Replacement GLA RECID
    "setInactiveGla" => true,
    "comment" => "This is a comment",
]);


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
<?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(),
    ]]
];



JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.