PCR-360 Wiki

Custom Methods

Custom Logic Method Reference — $this-> Methods

All custom logic types (API, Event, Validation, Report) share these methods via $this-><method_name>();


IMPORTANT: When generating Custom Logic, Custom API, Custom Event, Custom Validation, or Custom Report code, you may only use these methods and functions from the from this Custom PHP Whitelist Reference . Any other function call will fail PHP validation.


Data & Queries


$this->query($sql, $bind)

Execute a SQL query and return all rows as an array.

Parameter

Type

Required

Description

$sql

string

Yes

SQL statement using :named bind placeholders

$bind

array\\|null

No

Associative array mapping placeholder names to values

Returns: array of rows on success, false on failure.
Check $this->getQueryError() after a false return.

Errors logged when: $sql is not a string, or $bind is not an array or null.

PHP
// Simple query — no binds
$services = $this->query('SELECT RECID, SERVICE_NAME FROM SERVICES');

if ($services === false) {
    $this->debug('Query failed: ' . $this->getQueryError());
} else {
    foreach ($services as $row) {
        $this->debug($row['SERVICE_NAME']);
    }
}
PHP
// Query with bind parameters
$status = 'ACTIVE';
$rows = $this->query(
    'SELECT RECID, SERVICE_NAME FROM SERVICES WHERE STATUS = :status',
    [':status' => $status]
);
PHP
// Query with an IN clause using createArrayBinds
$statuses = ['ACTIVE', 'PENDING', 'ON_HOLD'];
$binds    = $this->createArrayBinds(':status', $statuses);
$inClause = implode(', ', array_keys($binds));

$rows = $this->query(
    "SELECT RECID, SERVICE_NAME FROM SERVICES WHERE STATUS IN ($inClause)",
    $binds
);

$this->getQueryError()

Return the error message from the most recent failed query() call.

Parameter

Type

Required

Description

(none)

Returns: string error message, or null if the last query succeeded.

PHP
$rows = $this->query('SELECT * FROM NONEXISTENT_TABLE');

if ($rows === false) {
    $error = $this->getQueryError();
    $this->debug('Query error: ' . $error);
}

$this->createArrayBinds($bindKey, $bindValues)

Convert an array of values into a set of named bind parameters, for use in SQL IN clauses.

Parameter

Type

Required

Description

$bindKey

string

Yes

Base name for the bind params (with or without leading :)

$bindValues

array

Yes

Array of values to bind

Returns: array of bind params keyed as :wb_{bindKey}_{n}, or [] on invalid input.

Errors logged when: $bindKey is not a string, or $bindValues is not an array.

PHP
$types    = ['COPPER', 'FIBER', 'WIRELESS'];
$binds    = $this->createArrayBinds('cable_type', $types);
// Result: [':wb_cable_type_0' => 'COPPER', ':wb_cable_type_1' => 'FIBER', ':wb_cable_type_2' => 'WIRELESS']

$inClause = implode(', ', array_keys($binds));
$rows = $this->query(
    "SELECT RECID, CABLE_NAME FROM CABLES WHERE CABLE_TYPE IN ($inClause)",
    $binds
);

$this->listGetByCode($type, $code)

Look up a list entry by its type and code.

Parameter

Type

Required

Description

$type

string

Yes

List type identifier

$code

string

Yes

List code value

Returns: array (the list entry), int, or null if not found.

PHP
$entry = $this->listGetByCode('SERVICE_STATUS', 'ACTIVE');
$this->debug('List entry: ' . var_export($entry, true));

$this->listFindCode($recid)

Find the code for a list entry by its RECID.

Parameter

Type

Required

Description

$recid

int\\|string

Yes

RECID of the list entry

Returns: string code value.

PHP
$code = $this->listFindCode(42);
$this->debug('Code: ' . $code);

$this->listFindValue($recid)

Find the display value for a list entry by its RECID.

Parameter

Type

Required

Description

$recid

int\\|string

Yes

RECID of the list entry

Returns: string display value.

PHP
$value = $this->listFindValue(42);
$this->debug('Display value: ' . $value);

$this->call($method, $params, $commitOnSuccess)

Call a PCR-360 API shortcut method (e.g., save a contact, assign a workflow).

Parameter

Type

Required

Description

$method

string

Yes

API shortcut name (e.g., 'saveContact', 'assignWorkflow')

$params

array

Yes

Parameters passed to the API method

$commitOnSuccess

bool

No (default false)

Commit the DB transaction immediately on success

Returns: array with at minimum:

  • status'success' or false

  • message — description of the result

Errors logged when: $method is not a string, or $params is not an array.

PHP
// Save / update a contact
$result = $this->call('saveContact', [
    'RECID'      => $data['contact_recid'],
    'NAME_FIRST' => 'Jane',
    'NAME_LAST'  => 'Smith',
    'EMAIL'      => 'jane.smith@example.com',
]);

if ($result['status'] !== 'success') {
    $this->debug('saveContact failed: ' . $result['message']);
}
PHP
// Assign a workflow to a service desk ticket
$result = $this->call('assignWorkflow', [
    'PARENT_RECID'   => $data['sd_recid'],
    'PARENT_TYPE'    => 'SERVICEDESK',
    'WORKFLOW_RECID' => 15,
]);

$this->debug('assignWorkflow result: ' . $result['status']);

Debugging


$this->debug($data)

Write a value to the Custom Debug table. Output is visible on the Debug tab of the custom logic form.

Parameter

Type

Required

Description

$data

mixed

Yes

Any value — arrays, booleans, and objects are serialized automatically

Returns: void

PHP
// Log a simple string
$this->debug('Processing started');

// Log a variable
$this->debug('Current record: ' . $data['RECID']);

// Log a full array for inspection
$this->debug($data);

// Log the result of a query
$rows = $this->query('SELECT RECID FROM SERVICES WHERE STATUS = :s', [':s' => 'ACTIVE']);
$this->debug('Active service count: ' . count($rows));

Events


$this->callCustomEvent($identifier, $data)

Trigger another custom event by its identifier, passing data to it.

Parameter

Type

Required

Description

$identifier

string

Yes

The identifier of the custom event to call

$data

array

Yes

Data array passed to the called event (merged with context)

Returns: Whatever value the called event returns (string, array, bool, or null).
Returns null and logs an error if either parameter is the wrong type.

Errors logged when: $identifier is not a string, or $data is not an array.

PHP
// Trigger a notification event after processing
$result = $this->callCustomEvent('send-service-notification', [
    'service_recid' => $data['RECID'],
    'trigger'       => 'status-change',
    'new_status'    => 'ACTIVE',
]);

$this->debug('Notification event returned: ' . var_export($result, true));

File Operations


$this->createFile($filename, $content, $location, $overwrite)

Write a file to the INBOUND or OUTBOUND directory.

Parameter

Type

Required

Description

$filename

string

Yes

Filename only — no path separators allowed

$content

string\\|array

Yes

File content; arrays are JSON-encoded automatically

$location

string

No (default 'OUTBOUND')

'INBOUND' or 'OUTBOUND'

$overwrite

bool

No (default false)

Overwrite if the file already exists

Returns: int bytes written on success, false on failure.

PHP
// Write a plain text file to OUTBOUND
$bytes = $this->createFile('export-summary.txt', 'Export complete. 42 records processed.');

if ($bytes === false) {
    $this->debug('File write failed');
} else {
    $this->debug("Wrote $bytes bytes");
}
PHP
// Build a CSV and write it to OUTBOUND
$rows = $this->query('SELECT SERVICE_NAME, STATUS, MONTHLY_COST FROM SERVICES');

$csvData = [['Service Name', 'Status', 'Monthly Cost']];
foreach ($rows as $row) {
    $csvData[] = [$row['SERVICE_NAME'], $row['STATUS'], $row['MONTHLY_COST']];
}

$csv = $this->arrayToCsv($csvData);
$this->createFile('services-export.csv', $csv, 'OUTBOUND', true);

$this->arrayToCsv($data, $delimiter, $enclosure)

Convert a two-dimensional array into a CSV string.

Parameter

Type

Required

Description

$data

array

Yes

Array of rows; each row is an array of values

$delimiter

string

No (default ',')

Column separator

$enclosure

string

No (default '"')

Value quoting character

Returns: string CSV content on success, '' on invalid input.

Errors logged when: $data is not an array.

PHP
$rows = [
    ['Name',        'Extension', 'Department'],
    ['Alice Brown', '1001',      'Engineering'],
    ['Bob Jones',   '1002',      'Finance'],
];

$csv = $this->arrayToCsv($rows);
$this->createFile('directory.csv', $csv);
PHP
// Pipe-delimited
$csv = $this->arrayToCsv($rows, '|');

$this->readFile($filename, $location, $offset, $length)

Read the contents of a file from the INBOUND or OUTBOUND directory.

Parameter

Type

Required

Description

$filename

string

Yes

Filename only — no path separators

$location

string

No (default 'OUTBOUND')

'INBOUND' or 'OUTBOUND'

$offset

int

No (default 0)

Byte offset to start reading from

$length

int\\|null

No (default null)

Max bytes to read; null reads the whole file

Returns: string file contents on success, false on failure.

Errors logged when: $filename is not a string, $length is not an integer or null, or $location is not INBOUND/OUTBOUND.

PHP
// Read a full file from INBOUND
$content = $this->readFile('import-data.txt', 'INBOUND');

if ($content === false) {
    $this->debug('Could not read file');
} else {
    $lines = explode("\n", $content);
    $this->debug('Line count: ' . count($lines));
}
PHP
// Read only the first 512 bytes
$preview = $this->readFile('large-export.txt', 'OUTBOUND', 0, 512);
$this->debug('File preview: ' . $preview);

$this->readCsvFile($filename, $location, $hasHeader, $length, $delimiter, $enclosure, $escape)

Read a CSV file and return its rows as an array.

Parameter

Type

Required

Description

$filename

string

Yes

Filename only — no path separators

$location

string

No (default 'OUTBOUND')

'INBOUND' or 'OUTBOUND'

$hasHeader

bool

No (default true)

If true, first row is column headers and rows are returned as associative arrays

$length

int\\|null

No (default null)

Max bytes per row; null for no limit

$delimiter

string

No (default ',')

Column separator

$enclosure

string

No (default '"')

Value quoting character

$escape

string

No (default '\\\\')

Escape character

Returns: array of rows on success, false on failure.
Rows are associative arrays when $hasHeader is true, indexed arrays otherwise.

Errors logged when: $filename is not a string, $length is not an integer or null, or $location is not INBOUND/OUTBOUND.

PHP
// Read a CSV with headers from INBOUND
$rows = $this->readCsvFile('new-contacts.csv', 'INBOUND');

if ($rows === false) {
    $this->debug('Could not read CSV');
} else {
    foreach ($rows as $row) {
        // $row keys match the header row: $row['First Name'], $row['Email'], etc.
        $result = $this->call('saveContact', [
            'NAME_FIRST' => $row['First Name'],
            'NAME_LAST'  => $row['Last Name'],
            'EMAIL'      => $row['Email'],
        ]);
        $this->debug('Imported: ' . $row['First Name'] . ' — ' . $result['status']);
    }
}
PHP
// Read a CSV without headers (rows are indexed arrays)
$rows = $this->readCsvFile('raw-data.csv', 'INBOUND', false);

foreach ($rows as $row) {
    $this->debug('Col 0: ' . $row[0] . ', Col 1: ' . $row[1]);
}

HTTP / cURL


$this->curlRequest($url, $requestOptions, $closeCurl, $debug)

Make an HTTP or HTTPS request. SFTP is not supported.

Parameter

Type

Required

Description

$url

string

Yes

Full HTTP or HTTPS URL

$requestOptions

array

Yes

cURL options using PHP CURLOPT_* constants as keys

$closeCurl

bool

No (default true)

Close the cURL handle after execution; set false to reuse the handle

$debug

bool

No (default false)

Include curl info and resolved options in the return value

Returns: array with keys:

  • success (bool)true for HTTP 2xx responses

  • response (string) — response body (on success)

  • errors (array) — error messages (on failure)

  • debug (array) — curl info and options (only when $debug is true)

  • curlHandle — the curl resource (only when $closeCurl is false)

Errors logged when: $url is not a string, or $requestOptions is not an array.

PHP
// Simple GET request
$result = $this->curlRequest('https://api.example.com/status', [
    CURLOPT_TIMEOUT    => 10,
    CURLOPT_HTTPHEADER => ['Accept: application/json'],
]);

if ($result['success']) {
    $body = json_decode($result['response'], true);
    $this->debug('API status: ' . $body['status']);
} else {
    $this->debug('Request failed: ' . implode(', ', $result['errors']));
}
PHP
// POST request with JSON body
$payload = json_encode(['service_id' => 1234, 'action' => 'activate']);

$result = $this->curlRequest('https://api.example.com/services', [
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $payload,
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiToken,
    ],
    CURLOPT_TIMEOUT        => 30,
    CURLOPT_SSL_VERIFYPEER => true,
]);

$this->debug('POST result: ' . var_export($result['success'], true));

Messaging


$this->sendSystemMessage($subject, $messageText, $recipientContactsRecid, $logicIdentifier)

Send a PCR-360 system message to a contact.

Parameter

Type

Required

Description

$subject

string

Yes

Message subject line

$messageText

string

Yes

Message body

$recipientContactsRecid

string\\|int

Yes

RECID from the CONTACTS table

$logicIdentifier

string

Yes

Identifier of the calling custom logic (used for audit/logging)

Returns: booltrue if the message was created successfully, false otherwise.

Errors logged when: $recipientContactsRecid is not a string or numeric.

PHP
// Notify a contact when a service goes active
$rows = $this->query(
    'SELECT OWNER_RECID FROM SERVICES WHERE RECID = :recid',
    [':recid' => $data['RECID']]
);

if (!empty($rows)) {
    $ownerRecid = $rows[0]['OWNER_RECID'];

    $sent = $this->sendSystemMessage(
        'Your service is now active',
        'Service #' . $data['RECID'] . ' has been activated as of ' . date('Y-m-d') . '.',
        $ownerRecid,
        'service-activation-notify'
    );

    $this->debug('Message sent: ' . var_export($sent, true));
}

Validation (Custom Validation scripts only)


$this->setMessage($message)

Set a validation failure message. Always return false after calling this.

Parameter

Type

Required

Description

$message

string

Yes

The message displayed to the user on validation failure

Returns: void

PHP
if (empty($data['EMAIL'])) {
    $this->setMessage('Email address is required.');
    return false;
}

$this->setError($message)

Add an error message to the validation result.

Parameter

Type

Required

Description

$message

string

Yes

Error message text

Returns: void

PHP
if (!filter_var($data['EMAIL'], FILTER_VALIDATE_EMAIL)) {
    $this->setError('The email address "' . $data['EMAIL'] . '" is not valid.');
    return false;
}

$this->setWarning($message)

Add a warning message to the validation result (does not block the save).

Parameter

Type

Required

Description

$message

string

Yes

Warning message text

Returns: void

PHP
if (strlen($data['NOTES']) > 500) {
    $this->setWarning('Notes are very long and may be truncated in some views.');
}

Reports (Custom Report scripts only)


$this->assign($name, $value)

Assign a variable to the Smarty report template.

Parameter

Type

Required

Description

$name

string

Yes

Smarty template variable name

$value

mixed

Yes

Value to assign

Returns: void

PHP
$rows = $this->query(
    'SELECT SERVICE_NAME, STATUS, MONTHLY_COST FROM SERVICES WHERE GLA_RECID = :gla',
    [':gla' => $params['gla_recid']]
);

$this->assign('services', $rows);
$this->assign('report_date', date('Y-m-d'));
$this->assign('total_cost', array_sum(array_column($rows, 'MONTHLY_COST')));

$this->addError($message)

Add an error message to the report output.

Parameter

Type

Required

Description

$message

string

Yes

Error message text

Returns: void

PHP
if (empty($params['gla_recid'])) {
    $this->addError('A GLA is required to run this report.');
    return;
}

$this->loadReport($identifier, $params)

Load and execute another custom report, embedding its output.

Parameter

Type

Required

Description

$identifier

string

Yes

Identifier of the custom report to load

$params

array

Yes

Parameters passed to the loaded report

Returns: mixed — the result of the loaded report.

PHP
$subreport = $this->loadReport('service-cost-summary', [
    'gla_recid'  => $params['gla_recid'],
    'start_date' => $params['start_date'],
]);

$this->assign('cost_summary', $subreport);

$this->barcode($data, $type)

Generate a barcode image for embedding in a report.

Parameter

Type

Required

Description

$data

string

Yes

The value to encode in the barcode

$type

string

Yes

Barcode format (e.g., 'CODE128', 'QR')

Returns: string — barcode image HTML or data URI.

PHP
$barcode = $this->barcode($data['ASSET_TAG'], 'CODE128');
$this->assign('asset_barcode', $barcode);