PCR-360 Wiki
2026.1 2025.2 2025.1 2024.2
2026.1 2025.2 2025.1 2024.2

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 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 (default null)

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 or empty values.

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: ' . json_encode($entry));

$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, save a service).

Parameter

Type

Required

Description

$method

string

Yes

API shortcut name — must be one of the allowed values below

$params

array

Yes

Parameters passed to the API method

$commitOnSuccess

bool

No (default false)

Commit the DB transaction immediately on success. Ignored when called from Custom Validation scripts.

Allowed $method values:

  • renderCableViewPath

  • renderCustomReport

  • saveCable

  • saveContact

  • saveEquipment

  • saveGla

  • saveLocation

  • saveService

  • saveServiceDesk

Any other value returns ['status' => false, 'message' => '{method} is not a valid call method.'].

Capabilities: The save* methods can create (insert) or update records — pass a RECID to update an existing record, omit it to insert a new one. Delete operations are not supported through call(); there are no delete* methods in the whitelist.

Returns: array with at minimum:

  • status — 'success' (string) or false

  • message — description of the result

  • params — included on failure

Side effects:

  • Automatically injects a permissions key into $params before dispatch.

  • Always clears the aliased class's instance cache via clearInstances() after the call completes (regardless of success/failure or whether a commit happened).

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
// Save a service desk ticket
$result = $this->call('saveServiceDesk', [
    'RECID'       => $data['sd_recid'],
    'DESCRIPTION' => 'Updated via custom logic',
], true); // commit on success

$this->debug('saveServiceDesk 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 — passed through to the debug writer

Returns: void

Note: Non-scalar values (arrays, booleans, objects) are serialized by the downstream debug writer. For readable output of booleans and small arrays in your own logs, encode first (e.g., json_encode($value)).

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: string, array, bool, or null — whatever the called event returns. Returns null and logs an error if either parameter is the wrong type.

Warning — reserved keys silently overwritten: The following keys in $data are always overwritten before the call:

  • custom_identifier — set to the $identifier passed in

  • called_by_custom_identifier — set to {callingClass}:{previousIdentifier}

  • checkStatus — forced to true

Do not rely on your own values for these keys.

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: ' . json_encode($result));

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 — any path separators are stripped via basename()


$content

string\

array

Yes

File content. Arrays are concatenated with no separator (PHP's file_put_contents behavior) — JSON-encode first if that's what you want

$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.

Note: The target directory is created automatically (mkdir(..., 0777, true)) if it does not exist.

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');
$csv  = $this->arrayToCsv(['Service Name', 'Status', 'Monthly Cost']);

foreach ($rows as $row) {
    $csv .= $this->arrayToCsv($row);
}

$this->createFile('services-export.csv', $csv, 'OUTBOUND', true);
PHP
// Write JSON — encode explicitly, do not rely on auto-encoding
$payload = ['count' => 42, 'items' => $items];
$this->createFile('export.json', json_encode($payload), 'OUTBOUND', true);

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

Convert a flat array into a single CSV row string.

Parameter

Type

Required

Description

$data

array

Yes

Flat array of values representing a single CSV row

$delimiter

string

No (default ',')

Column separator

$enclosure

string

No (default '"')

Value quoting character

Returns: string — CSV row on success, '' on invalid input.

Errors logged when: $data is not an array.

PHP
// Single row
$csv = $this->arrayToCsv(['Alice Brown', '1001', 'Engineering']);
// "Alice Brown",1001,Engineering

// Multiple rows — loop and concatenate
$rows = [
    ['Name',        'Extension', 'Department'],
    ['Alice Brown', '1001',      'Engineering'],
    ['Bob Jones',   '1002',      'Finance'],
];

$csv = '';
foreach ($rows as $row) {
    $csv .= $this->arrayToCsv($row);
}
$this->createFile('directory.csv', $csv);

// Pipe-delimited
$csv = '';
foreach ($rows as $row) {
    $csv .= $this->arrayToCsv($row, '|');
}

$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 — path separators are stripped via basename()


$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 — path separators are stripped


$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.

Warning: When $hasHeader is true, any data row whose column count does not match the header count is silently skipped (an error is logged but no exception is raised). The returned array will omit mismatched rows.

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

Structured associative array — see keys below

$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

$requestOptions keys:

Key

Type

Description

httpMethod

string

'GET', 'POST', or any other HTTP method (used as CURLOPT_CUSTOMREQUEST).

params

array

Request parameters. For GET they are appended to the URL as a query string; for all other methods they are sent as the body via http_build_query (form-encoded).

headers

array

Associative array of header name → value. See Content-Type note below.

cookies

array

Associative array of cookie name → value. Sent as a single Cookie: header.

curl

array

Raw CURLOPT_* options merged in first (e.g., CURLOPT_TIMEOUT, CURLOPT_SSL_VERIFYPEER).

Important — Content-Type is forced: This wrapper always sends Content-Type: application/x-www-form-urlencoded. Any Content-Type key you supply in headers is silently dropped. If you need to send a JSON body or any other content type, you must use the lower-level curl_init(), curl_setopt(), and $this->curlExec() helpers instead.

Also enforced at exec time: CURLOPT_RETURNTRANSFER is always true, and CURLOPT_PROTOCOLS is locked to HTTP/HTTPS/SFTP. curlRequest additionally rejects any URL starting with s<ftp://> via a separate URL-scheme guard — if you need SFTP, use the lower-level curl_init() / curl_setopt() / $this->curlExec() helpers instead.

Returns: array with keys:

  • success (bool) — true for HTTP 2xx responses

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

  • errors (array) — error messages (on failure; key is removed on success)

  • 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', [
    'httpMethod' => 'GET',
    'params'     => ['format' => 'json'],
    'headers'    => ['Accept' => 'application/json'],
    'curl'       => [
        CURLOPT_TIMEOUT => 10,
    ],
]);

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 (form-encoded — Content-Type cannot be overridden)
$result = $this->curlRequest('https://api.example.com/services', [
    'httpMethod' => 'POST',
    'params'     => [
        'service_id' => 1234,
        'action'     => 'activate',
    ],
    'headers'    => [
        'Authorization' => 'Bearer ' . $apiToken,
    ],
    'curl'       => [
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_SSL_VERIFYPEER => true,
    ],
]);

$this->debug('POST result: ' . json_encode($result['success']));
PHP
// Calling another PCR-360 Custom API (API key is embedded in the URL — no auth header needed)
$result = $this->curlRequest(
    'https://pcr360.example.com/api/{API_KEY_TOKEN}/get_dept_from_gl.json',
    [
        'httpMethod' => 'POST',
        'params'     => ['account_number' => $gl],
        'curl'       => [
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_SSL_VERIFYPEER => 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

No (default null)

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


Returns: bool — true if the message was created successfully, false otherwise.

Note — auto-appended footer: A footer is automatically appended to $messageText: \\n\\nGenerated From: {customerName} {logicType}: {identifier} where logicType comes from the calling custom logic class's $customLogicType property (e.g., 'Custom Validation', 'Custom Report'), falling back to 'Custom Logic' when not set.

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: ' . json_encode($sent));
}

Validation (Custom Validation scripts only)

$this->setMessage($message, $messageKey)

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

$messageKey

string\

null

No (default null → self::ERROR)

Message key used by the validator

Returns: self (fluent) — can be chained.

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

$this->setError($message)

Add an error message to the validation result. Side effect: marks the validator as invalid (calls _error(self::ERROR) internally).

Parameter

Type

Required

Description

$message

string

Yes

Error message text

Returns: self (fluent) — can be chained.

PHP
if (!preg_match('/^[^\s@]+@[^\s@]+\.[^\s@]+$/', $data['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). Side effect: calls _error(self::WARNING) internally.

Parameter

Type

Required

Description

$message

string

Yes

Warning message text

Returns: self (fluent) — can be chained.

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, returning its rendered 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: string — the rendered report HTML.

Side effect: The sub-report's Smarty assigns and errors are merged into the calling report (via addAssigns / addErrors).

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

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

$this->barcode($code)

Generate a barcode image HTML snippet for embedding in a report.

Parameter

Type

Required

Description

$code

string

Yes

The value to encode in the barcode

Returns: string — HTML <img> tag for the barcode.

Note: Barcode format/type is not configurable through this helper — the view helper controls the format.

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