Tom Hauri
ServiceNow Employee
ServiceNow Employee

Global Tools

Welcome to Global Tools - created and maintained by Tom Hauri.

Overview

Yet Another Global Utility Script Include Solution (YAGUSIS). Every project has one, but are you sure that yours is not allowing delegated admins to escape the scope boundaries and do you have ATF tests for all your functions? Most developers prefer their own libraries, so feel free to steal the ideas and the code if it helps you!

Global tools provides generic functions that need to run in global scope while ensuring that delegated development security cannot be circumvented.

Disclaimer

Global Tools are NOT an officially supported ServiceNow products. Global Tools do NOT come with any kind of warranty. If you use it, you own it!

System Requirements

License

Copyright 2023-2024 by Tom Hauri

Licensed under the Apache License, Version 2.0 (the "License")


You may not use Global Tools except in compliance with the License.


You may obtain a copy of the License at: https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Release Notes

1.0.0 - 09.2023

  1. Initial Release

1.0.1 - 11.2023

  1. Added administration menues
  2. Added manual page
  3. Additional ATF Tests

1.0.2 - 12.2023

  1. Added function padNumber
  2. Added function formatBytes
  3. Added function getHTMLDiffFromXML
  4. Added function getInternalType
  5. Added function sumRecordsField
  6. Added function getRecord
  7. Added function convertGRtoXML
  8. Added function deleteMultiple
  9. Added function isValidDBView
  10. Added function isTableUpdateSynched
  11. Added script include GlobalToolsRESTAPI with functions to handle REST requests using connection & credential aliases and some shortcuts for instance to instance requests.
  12. Added script include GlobalToolsAttachment with functions to handle attachment operations.

1.0.3 - 03.2024

  1. Added function getFieldLabel
  2. Added parameter bReturnDictId to getFields function

1.0.4 - 05.2024

  1. Added getUrl function to overcome scopeing issue with workaround for workspaces getGlideURI issue (CS7215882) in GlobalTools
  2. Added parameters sDocument, sDocumentKey to scheduleScript function in GlobalTools
  3. Added parameter bRemoveEmpty to mergeArray function
  4. Fixed errors in ATF tests in GlobalToolsTable
  5. Added parameter bNoEngines to getRecord and getRecords functions in GlobalToolsRecordRead
  6. Added function doRecordByName to GlobalToolsRecordWrite
  7. Return SysId even if no update or insert happens in doRecord function in GlobalToolsRecordWrite
  8. Added error on delete without record found (code=004, message=error deleting: record not found) in doRecord function in GlobalToolsRecordWrite
  9. Added sLogLevel parameter to initiate and doRESTRequest functions, will be passed to the oRequest.setLogLevel function in GlobalToolsRESTAPI
  10. Added bOmitEmptyValues parameter (if true will NOT add empty values to the groupby results object, otherwise empty string is returned) in function doNOWRESTCount in GlobalToolsRESTAPI
  11. Made the following changes to GlobalToolsWriteValidate
    - Fixed write validate errors on empty values
    - Added parameter bErrorOnInvalidFieldsInValues
    - Added parameter bDataSourceIREfromValues to take IRE Data Source from "discovery_source" value if it is a valid choice entry in GlobalToolsWriteValidate
    - Ignore calculated fields (don't apply value, don't validate)
    - Added try error handling on field apply (500_009)
    - Fixed errors in ATF tests
    - Added new configuration error handling object
    - Added error type in returned error object:
    - Added new function to create default value in reference table
    - Added new error 400_039 Invalid value in reference field (not found, created)
    - Added new error 400_040 Invalid value in reference field (not found, not created)
    - Added aCustomScripts parameter to allow to execute custom scripts before or after the action (not available for validateAndReturnIREObject)
    - Added parameter sFixedValue to aFields

1.0.5 - 07.2024

  1. GlobalToolsWriteValidate: Fixed error handling to check also for base reference table (override with real table if required)
  2. Fixed isEqual to sort nested arrays and objects in GlobalTools
  3. Added deepSort function to GlobalTools
  4. Added getFieldParentTable function in GlobalToolsTable
  5. Fixed sSourceField parameter in GlobalToolsRecordWriteValidate
  6. Added parameter sFieldAction in GlobalToolsRecordWriteValidate
  7. Fixed ATF error output to contain arguments in the same order as provided
  8. Added parameter oErrorCode in oErrorHandling in GlobalToolsRecordWriteValidate
  9. Added ignore_reject option to block action but not report the error in GlobalToolsRecordWriteValidate

1.0.6 - 09.2024

  1. Added function to updatePlugins to GlobalTools
  2. Moved function getCommonTypeFromArray from GlobalTools to GlobalToolsArray
  3. Added isValidQuery to GlobalToolsRecordRead
  4. Added getTableId and getTableName to GlobalToolsTable
  5. Fixed issue with sAddlQuery in GlobalToolsRecordRead.getRecordByKeys
  6. Fixed issue with empty dependent field on reference qualifier in GlobalToolsRecordWriteValidate

1.0.7 - 10.2024

  1. Added sFieldAction parameters ignore_insert and ignore_update in GlobalToolsRecordWriteValidate
  2. Added reusable choice list lookup in getFieldChoices in GlobalToolsTable
  3. Changed IP fields validadtion respecting dictionary attribute in GlobalToolsRecordWriteValidate
  4. Added support for dependent choice lists with empty value in GlobalToolsRecordWriteValidate
  5. Added support for new Mapping Configuration Manager features in GlobalToolsRecordWriteValidate
  6. Improved documentation

1.0.8 - 11.2024

  1. Field values of type string are now trimmed by default. In case no trimming is wanted you can use the global or new field parameter "bNoTrim" in GlobalToolsRecordWriteValidate
  2. Added bRecordLookupUseBaseTable parameter in function getRecordByKeys in GlobalToolsRecordRead
  3. Added bAllowClassChange parameter that will ensure to call getRecordByKeys with bRecordLookupUseBaseTable with same value in GlobalToolsRecordWriteValidate
  4. Fixed error in IRE with class switching when using bUseIRE = true in combination with bKeepSysId = true because the SysId is looked up only in the current class contrary to regular IRE behavior
  5. Added deleteValue to GlobalToolsObject
  6. Added new GlobalToolsCache script include to handle transaction and session cache interactions
  7. Added new parameter sErrorHandlingCacheName name in GlobalToolsRecordWriteValidate
  8. Fixed check if Mapping Configuration Manager exists in GlobalToolsRecordWriteValidate
  9. Added bRunAsynch and iWaitForResponseSeconds to function doRESTRequest in GlobalToolsRESTAPI

1.0.9 - 12.2024

  1. Fixed typo in GlobalToolsRESTAPI that prevented proper error handling
  2. Added class GlobalToolsDateTime currently used only for performance measurement
  3. Added timer and caching to GlobalToolsRecordWriteValidate and GlobalToolsTable to optimize performance

1.0.10 - 02.2025

  1. Added days and hours in GlobalToolsDateTime.formatMS function
  2. New function to export ERD to Lucidchart to GlobalToolsTable.generateLucidChartERDInput

1.0.11 - 05.2025

  1. Added aExtraFields parameter to GlobalToolsRecordRead.getRecords using the new addExtraField function
  2. Added bDirectOnly parameter to GlobalToolsTable.getTableExtensions to retrieve only direct child tables
  3. Added GlobalToolsSecurity library to support security related functions and generate role related access reports
  4. Added installPlugins and isPluginActive functions to GlobalTools
  5. Added useTagUtil function to GlobalTools

1.0.12 - 06.2025

  1. Added bNoCount parameter to GlobalToolsRecordRead.getRecords using the setNoCount function (performance improvement)
  2. Added function getRecordsFields to GlobalToolsRecordRead to get only certain fields back (performance improvement)
  3. Added bDisplayValue parameter to GlobalToolsRecordWriteValidate configuration and parse different record values input formats correctly to support display values.

1.0.13 - 07.2025

  1. Add oRecordDisplayValues to the scripted ref lookup
  2. Add oRecordDisplayValues before and after scripts
 

 

Problem Statement

Many functions are not available in scoped applications which hinders the developent of reusable solution blocks and many functions are required across many different applications.

Overview

Global Tools to support different areas of (scoped) app development (like Array or Object handling and working with Glide objects). The functions are only available in global scope and specific scopes defined in the system properties "now.globaltools.access_from_scope" or "now.globaltools.access_from_scope_custom" for security reasons.

Installation and usage

  1. Create an account on GitHub - if not done already.
  2. Create a personal access token for your GitHub account.
  3. Add credentials to access GitHub - use "Basic Auth" (personal access token as password).
  4. Fork the repository https://github.com/haurit/now-globaltools.
  5. Go to Studio and import the Global Tools application from source control.
  6. Create the system property now.globaltools.access_from_scope_custom and add the list of comma separated scope names for all applications that can use the Global Tools suite.

ATF tests are meant to be run against a baseline instance with demo data. Due to the versatile nature of the functions not all tests create their own test data.

 

Script Include: global.GlobalTools

 

nsub

Purpose: This function substitutes null values in simple types, arrays.

Parameters:

  • sValue: The value to be checked and possibly substituted by sSubstitute if null.
  • sSubstitute: The value to use as a substitute if sValue is null.
  • sType: (Optional) The type of sSubstitute to be returned if sValue is null.
  • sObjKey: (Deprecated) Use new global.GlobalToolsObject().getValue() instead.

Returns: The sValue if not null or sSubstitute respecting the type specified in sType

getType

Purpose: This function determines the type of a given value.

Parameters:

  • oValue: The value for which you want to determine the type.
  • bDoNotConvertCase: (Optional) If true, the function returns the type in its original case else it's converted to lowercase.

Returns: The type of the provided oValue as a string.

 

isEqual

Purpose: This function compares two values and returns true if they are the same (object deep compare, uses deepSort function for nested arrays/objects to guarantee the same order of content)

Parameters:

  • oValue1: The first value.
  • oValue2: The second value.

Returns: True if oValue1 and oValue2 are the same, false if not.

deepSort

Purpose: This function sorts arrays and objects recursivly and also guarantees the same order of arrays and object (string sort). For arrays it uses the getCommonTypeFromArray function to determine if all elements of an array share the same type (to use caseinsensitive sorting for strings, precise sorting numbers, and converts arrays and objects to strings for comparison). This is mainly done to guarantee the same order if two multiple nested objects need to be compared.

Parameters:

  • oValue: The object/array to be sorted.

Returns: the sorted oValue array or object.

 

encodeNewLineToTag

Purpose: This function replaces newline characters "\n" in a string with a custom tag "!^br^!".

Parameters:

  • sValue: The input string containing newline characters.

Returns: The sValue with newline characters replaced by "!^br^!".

decodeTagToNewLine

Purpose: This function replaces a custom tag "!^br^!" in a string with newline characters "\n".

Parameters:

  • sValue: The input string containing the "!^br^!" tag.

Returns: The sValue with the "!^br^!" tag replaced by newline characters.

padNumber

Purpose: This function ensures a string has a specific length by prefixing zeros (0).

Parameters:

  • iNumber: The input integer with the actual number.
  • iDigits: The input integer with the desired lenght of the string.

Returns: The string with the required length.

formatBytes

Purpose: This function formats a number to the correct byte representation.

Parameters:

  • iNumber: The input integer with the actual number of bytes.
  • sNotation: (Optional) The string definining the notation to be used: si (base 1000) or iec (base 1024) Default: si.
  • iDecimals: (Optional) The number of decimals to be returned (Default: 2).

Returns: The string with the formated bytes value.

replacePlaceholders

Purpose: This function replaces placeholders in a string [field_name] with the respective field values from an object or GlideRecord.

Parameters:

  • sInputValue: The string containing the placeholders.
  • oRecord: An object or valid GlideRecord where the field values are looked up.
  • sValue: A value that will replace the sValue in the input string.
  • bJSON: If the input string is a JSON string this needs to be set to true.

Returns: The input string with all the placeholders replaced with actual values.

convertUnderscoretoCamelCase

Purpose: This function replaces _ (underscore) values and puts the string in camel case.

Parameters:

  • sInputValue: The string containing the original value.

Returns: The input string in camel case.

getHTMLDiffFromXML

Purpose: This function compares two XML strings and returns a HTML string with the differences.

Parameters:

  • sXMLLeft: The string containing the first XML string.
  • sXMLRight: The string containing the second XML string.
  • sHeaderLeft: The string containing the left title value.
  • sHeaderRight: The string containing the right title value.

Returns: The HTML string with the differences or undefined if there was an error.

scheduleScript

Purpose: This function schedules the execution of a script include function.

Parameters:

  • sScriptInclude: The name of the script include.
  • sFunction: The name of the function to be called within the script include.
  • iSeconds: The delay in seconds before execution.
  • aFunctionArgs: An array of arguments to pass to the function.
  • aClassArgs: An array of arguments to pass to the script include constructor.
  • sScheduleName: (Optional) The name of the scheduled script.
  • sDocument: (Optional) The document to be set in the trigger record.
  • sDocumentKey: (Optional) The document_key to be set in the trigger record.

scheduleHandler

Purpose: This function handles event scheduling and queuing.

Parameters:

  • sEvent: The name of the event to be scheduled.
  • sDelaySeconds: (Optional) The delay in seconds before scheduling the event.
  • sAction: (Optional) The default action is "start", use "stop" to stop active events.
  • sAddlQuery: (Optional) Additional query conditions for event selection.
  • grRecord: (Optional) A GlideRecord representing the record associated with the event.
  • oParam1 and oParam2: (Optional) Additional parameters for the event.
  • sQueue: (Optional) The queue to use for event scheduling.

 

sleep

Purpose: This function is used to pause script execution for a specified number of milliseconds.

Parameters:

  • iMilliseconds: The number of milliseconds to pause script execution.

getUrl

Purpose: This function is used to get the current URL (incl. workaround for batched graphql calls from workspaces).

Returns: The URL of the current transaction.

 

getExecutionTrackerbyId

Purpose: This function is used to get an execution tracker by id.

Parameters:

  • sId: The string with the id of the execution tracker to retrieve.

Returns: The GlideExecutionTracker specified by the sId parameter.

runFunction

Purpose: This function runs a given JavaScript function in global scope. The function to run is provided as a string.

Parameters:

  • sFunction: The JavaScript function to run, provided as a string.
  • arguments(1-n): Any argument passed after the function name will be passed to the function in the order provided.

Returns: The result of the executed function.

runFunctionInScope

Purpose: This function runs a specified JavaScript function within a specific scope. The function to run and scope ID are provided as arguments. This function is only available if the system property "glide.record.legacy_cross_scope_access_policy_in_script" is set to true. WARNING: this is NOT recommended to be done on any productive system as it breaks the delegated development security.

Parameters:

  • sFunction: The JavaScript function to run, provided as a string.
  • sScopeId: The ID of the scope in which to run the function.
  • arguments(2-n): Any argument passed after the function name will be passed to the function in the order provided.

Returns: The result of the executed function within the specified scope.

 

updatePlugins

Purpose: This function is used to update one or multiple plugins.

Parameters:

  • sQuery: A string representing the query to filter the App Store [sys_app_store] records.
  • bScheduled: If true will schedule the script in the background (automatically done if gs.interactive is true).

Returns: The result is written to the system log as warning, search for the message starting with GlobalTools.updatePlugins:

{
  "iStoreAppsFound": 1,
  "sStoreAppsQuery": "hide_on_ui=false^update_available=true^nameSTARTSWITHpl^sourceNOT INsn_playbook_exp",
  "aStoreAppsUpgraded":
    { "now_playbook_exp": {
        "sOldVersion": "26.0.4",
        "sNewVersion": "26.1.1",
        "sWorkerResult": "true"
    }
  }
}

 

installPlugins

Purpose: This function is used to install one or multiple plugins.

Parameters:

  • aPlugin: An array of plugin ids to be installed.
  • bLoadDemoData: If true will load demo data for each plugin.
  • bLog: If true will log some information about each plugin to the system log.
  • bScheduled: If true will schedule the script in the background (automatically done if gs.interactive is true).

 

isPluginActive

Purpose: This function is used to check if a plugin is active.

Parameters:

  • sPluginId: A string representing the plugin id to be validated.

Returns: True if the plugin is active and false if not.

 

useTagUtil

Purpose: This function is used to overcome scope barrier for the TagUtil script include.

Parameters:

  • sFunction: A string representing the function in TagUtil you want to use.
  • <arguments>: Any parameter you want to pass to the TagUtil function.

Returns: The result of the TagUtil function that was called is passed back.

Script Include: global.GlobalToolsArray

 

unique

Purpose: This function removes duplicate elements from an array. In ECMA 21 scripts you can use "Array.from(new Set(array));" instead.

Parameters:

  • aArray: The input array to remove duplicates from.
  • bRemoveEmpty: (Optional) A boolean flag to indicate whether to remove empty values (Default: false).

Returns: An array with duplicate elements removed.

isValidArray

Purpose: This function checks if an array is valid, not empty, and has at least one element.

Parameters:

  • aArray: The array to check for validity.

Returns: A boolean value indicating whether the array is valid.

mergeArray

Purpose: This function merges two arrays into one, removing duplicates.

Parameters:

  • aArray1: The first array to merge.
  • aArray2: The second array to merge.
  • bRemoveEmpty: (Optional) A boolean flag to indicate whether to remove empty values (Default: false).

Returns: A merged array with duplicates removed.

addRemoveFromArray

Purpose: This function adds elements to and removes elements from an array.

Parameters:

  • aArray: The original array.
  • aArrayAdd: An array of elements to add to the original array.
  • aArrayRemove: An array of elements to remove from the original array.

Returns: An array with elements added and removed as specified.

getAddRemoveFromArrays

Purpose: This function compares two arrays and returns the elements to add to and remove from one array to make it identical to the other.

Parameters:

  • aArray: The target array to be modified.
  • aArrayOld: The reference array to compare with.

Returns: An object containing three properties:

  • add: An array of elements to add to the target array.
  • remove: An array of elements to remove from the target array.
  • same: A boolean indicating whether the arrays are already identical.

convertCommaSepStringToArray

Purpose: This function cleans an comma separated string and returns an array.

Parameters:

  • sCommaSepString: The comma separated string.

Returns: An array with elements from the comma separated string.

 

getCommonTypeFromArray

Purpose: This function determines if the type of all elements in a given array are the same (using getType function) and returns the common type if one is found.

Parameters:

  • aArray: The array for which you want to determine the common type.
  • bDoNotConvertCase: (Optional) If true, the function returns the type in its original case else it's converted to lowercase.

Returns: The type of the provided aArray elements as a string or undefined if the types don't match.

 

Script Include: global.GlobalToolsObject

 

isObject

Purpose: This function checks if a given variable is an object. Does return true for all kind of objects that are not a primitive type. Use GlobalTools.getType to distinuish different object types.

Parameters:

  • oObj: The variable to check.

Returns: A boolean indicating whether the variable is an object (is false for arrays).

getValue

Purpose: This function retrieves a configuration value from an object, allowing up to 8 levels of depth. It supports replacing the value with a default if not found.

Parameters:

  • sConfigPath: A string representing the path to the desired value, separated by '/'.
  • sReplace: (Optional) A replacement value if the configuration value is not found.
  • oConfig: The object in which to get the configuration value.

Returns: The retrieved configuration value or the replacement value if not found.

setValue

Purpose: This function sets a configuration value in an object, allowing up to 8 levels of depth. It creates nested objects as needed to match the provided path.

Parameters:

  • sConfigPath: A string representing the path where the value should be set, separated by '/'.
  • oValue: The value to set in the object.
  • oConfig: The object in which to set the configuration value.

Returns: None. It modifies the input object oConfig in place.

hasValue

Purpose: This function checks if a configuration value in an object exists, allowing up to 8 levels of depth.

Parameters:

  • sConfigPath: A string representing the path where the value should be checked, separated by '/'.
  • oConfig: The object in which to check the configuration value.

Returns: If the last node exists returns true, else false.

 

deleteValue

Purpose: This function checks if a configuration value in an object exists, allowing up to 8 levels of depth.

Parameters:

  • sConfigPath: A string representing the path where the value should be deleted, separated by '/'.
  • oConfig: The object in which to delete the configuration value.

 

deepMerge

Purpose: This function performs a simple deep merge of two objects with an option to merge arrays.

Parameters:

  • oSource: The target object to merge into.
  • oMerge: The source object to merge from.
  • bMergeArrays: A boolean indicating whether to merge arrays.

Returns: The merged object.

 

getDepth

Purpose: This function returns the depth of a nested object.

Parameters:

  • oObj: The object where the depth should be evaluated.

Returns: The depth of the object as integer (-1 if it's not an object, 0 if the object is empty).

 

parseJSON

Purpose: This function returns an object from a valid JSON string.

Parameters:

  • sObj: The string that should be parsed as a JSON.

Returns: The object if successful or undefined in case of an error.

 

Script Include: global.GlobalToolsTable

 

initialize

Purpose: This initializes the class.

Parameters:

  • gtCache: Can inherit a shared GlobalToolsCache class.
  • oTimer: Can inherit a shared GlobalToolsDateTime class.

 

getTableId

Purpose: This function returns the sys_id of a given table name or array of table names.

Parameters:

  • oTable: A string or array representing one or multiple table names.

Returns: Returns tables sys_id if the table name is valid (array if input is array); otherwise, it returns undefined.

getTableName

Purpose: This function returns the name of a given table sys_id or array of sys_ids.

Parameters:

  • oTableId: A string or array representing one or multiple table sys_ids.

Returns: Returns the table name if the table sys_id is valid (array if input is array); otherwise, it returns undefined.

isValidTable

Purpose: This function checks if a given table name is valid in ServiceNow's GlideRecord context.

Parameters:

  • sTable: A string representing the table name to check.

Returns: Returns true if the table is valid; otherwise, it returns undefined.

isValidDBView

Purpose: This function checks if a given table name is a valid Database View sys_db_view.

Parameters:

  • sTable: A string representing the view name to check.

Returns: Returns true if the view is valid; otherwise, it returns undefined.

getRecordClass

Purpose: This function gets the class name of a GlideRecord object.

Parameters:

  • grRecord: A GlideRecord object to retrieve the class name from.

Returns: Returns the class name as a string if the input is a valid GlideRecord; otherwise, it returns undefined.

getAbsoluteBase

Purpose: This function gets the absolute base class for a given table name.

Parameters:

  • sTable: A string representing the table name to retrieve the absolute base class for.

Returns: Returns the absolute base class name as a string if the table is valid; otherwise, it returns undefined.

getTableHierarchy

Purpose: This function gets the hierarchy of tables for a given table name.

Parameters:

  • sTable: A string representing the table name to retrieve the table hierarchy for.

Returns: Returns an array of table names representing the hierarchy if the table is valid; otherwise, it returns undefined.

getTableExtensions

Purpose: This function gets the extensions or all extensions of a given table name.

Parameters:

  • sTable: A string representing the table name to retrieve the extensions for.
  • bAllExtensions: A boolean flag indicating whether to retrieve all extensions, including the initial table if true or just the extensions (if false).
  • bDirectOnly: A boolean flag indicating whether to retrieve only direct extensions or extensions of extentions (if false).

Returns: Returns an array of table names representing the extensions if the table is valid; otherwise, it returns undefined.

isTableUpdateSynched

Purpose: This function checks if a given table name is updated synched (changes are captured in update sets and scoped applications).

Parameters:

  • sTable: A string representing the table to check.

Returns: Returns true if the table is update synched; otherwise, it returns undefined.

getTableScopeInfo

Purpose: This function retrieves cross-scope access information for a given table.

Parameters:

  • sTable: A string representing the name of the table to retrieve access information for.

Returns: Returns an object containing cross-scope access information for the table. The object has the following properties:

  • id: A string representing the sys_scope ID.
  • access: A string representing the access level.
  • read: A boolean indicating if read access is granted.
  • create: A boolean indicating if create access is granted.
  • write: A boolean indicating if write access is granted.
  • delete: A boolean indicating if delete access is granted.

If the table is not valid, it returns undefined.

getInternalType

Purpose: This function returns the internal field type for a given table and field.

Parameters:

  • sTable: A string representing the name of the table for which to retrieve the field.
  • sField: A string representing the name of the field.

Returns: Returns a string representing the internal field type or undefined if not found.

getDisplayField

Purpose: This function retrieves the display field for a given table. It checks if a display field override is set and returns the overridden display field if available.

Parameters:

  • sTable: A string representing the name of the table for which to retrieve the display field.

Returns: Returns a string representing the display field of the table or undefined if not found.

getFieldLabel

Purpose: This function retrieves the field label for a given table and field in the language of the current user.

Parameters:

  • oTableOrRecord: A string representing the table name or a GlideRecord object.
  • sField: A string representing the name of the field.

Returns: Returns a string representing the label of the field or undefined if table or field is not found.

getFields

Purpose: This function retrieves the list of field names or dictionary ids for a given table or GlideRecord object.

Parameters:

  • oTableOrRecord: A string representing the table name or a GlideRecord object.
  • bOmitSysId: (Optional) if "true", don't add sys_id to the list.
  • bReturnDictId: (Optional) if "true", return the SysId of the Dictionary [sys_dictionary] record.

Returns: Returns an array of field names or dictionary ids for the specified table or GlideRecord object.

getFieldParentTable

Purpose: This function retrieves the first table where a field is defined in the table hierarchy for a given table and field.

Parameters:

  • oTableOrRecord: A string representing the table name or a GlideRecord object.
  • sField: A string representing the name of the field.

Returns: Returns a string representing the first table where a field is defined in the table hierarchy or undefined if table or field is not found.

getRefTable

Purpose: This function retrieves the reference table name based on the reference field and the table it belongs to.

Parameters:

  • sTable: A string representing the name of the table containing the reference field.
  • sField: A string representing the name of the reference field.

Returns: Returns a string representing the name of the reference table associated with the given field and table.

getRefFieldName

Purpose: This function retrieves the name of the reference field in a given table that points to a specified reference table. It can return either a single field name or an array of field names.

Parameters:

  • fRecord: A GlideRecord object representing the record.
  • sRefTable: A string representing the name of the reference table.
  • bCheckRefTableHierarchy: A boolean indicating whether to check the hierarchy of the sRefTable table.
  • sReturnType: A string specifying the return type, either 'array' or 'string'.

Returns: Returns either a single field name or an array of field names in the specified table that reference the given sRefTable table with or without respecting the hierarchy depending on bCheckRefTableHierarchy.

getDictOrOverrideValue

Purpose: This function retrieves dictionary records or values (depending wether bReturnRecord is set) while respecting overrides. It can return dictionary records or their attribute values.

Parameters:

  • sTable: A string representing the name of the table.
  • sField: A string representing the name of the field.
  • sAttributeName: A string representing the name of the attribute.
  • bReturnRecord: (Optional) A boolean indicating whether to return dictionary records.
  • sAddlDictQuery: (Optional) A string representing additional query conditions for the dictionary.

Returns: Returns dictionary records or their attribute values based on the provided parameters.

getFieldChoices

Purpose: This function retrieves the choices available for a specific field in a table. It can also filter choices based on a dependent field value.

Parameters:

  • sTable: A string representing the name of the table.
  • sField: A string representing the name of the field.
  • sDependentFieldValue: A string representing the value of the dependent field to filter choices (optional).

Returns: Returns an array containing three arrays: choices, dependent values, and choice display values.

getMandatoryFields

Purpose: This function retrieves an array of mandatory fields in a given table.

Parameters:

  • sTable: A string representing the name of the table.

Returns: Returns an array of mandatory field names in the specified table.

 

generateLucidChartERDInput

Purpose: This function retrieves data about the dictionary structure that can be used to create ERD in Lucid chart. Import the data returned by this function under "Entity Relationship" import as type "mysql" to get the tables. When you drag the tables onto the canvas relationships will automatically be built.

Parameters:

  • oConfig: The configuration on how to select tables and finetune the data returned.
    oConfig: {
    	bOnlyReferenceFields: false, // Default: true, if true will return only reference and list field types to the table, otherwise the whole schema
    	bOnlyTableWithoutHierarchy: true, // Default: false, if false will use all tables in the hierarchy to find references, otherwise just the table specified.
    	bFollowReferences: true, // Default: false, if true will follow references
    	iMaxNumberOfReferencesToFollow: 5, // Default: 3, if bFollowReferences will follow references this deep
    	bFollowInboundReferences: true,  // Default: false, if true will follow inbound references once for each table
    	aExcludeTables: ['sys_metadata', 'cmdb'], // Default: ['sys_metadata'], // will always exclude these tables
    	sTables: 'table_a,table_b', // Optional, comma separated list of tables
    	aTables: ['table_a', 'table_b'], // Optional, array of tables
    	aPackages: ['package_idOrname_a', 'package_idOrname_b'], // Optional, will search for all tables which belong to a specific packages (sys_id or starts with on id)
    	aApps: ['app_idOrname_a', 'app_idOrname_b'], // Optional, will search for all tables which belong to a specific application (sys_id or starts with on name)
    	sTableSchema: '', // Default: 'now', Schema to be used directly or as prefix when data is coming from different packages or apps
    	sSchemaType: 'package', // Default: '', If 'apps' or 'package' will add the respective app or package name as schema to the diagram
    }​

Returns: Returns a string that you can import directly to Lucid chart without reformatting.

 

Script Include: global.GlobalToolsRecordRead

 

isValidQuery

Purpose: This function validates a query.

Parameters:

  • sTable: A string representing the name of the table.
  • sQuery: A string representing the query validate.

Returns: Returns an boolean (true/false).

 

countRecords

Purpose: This function counts records in a specified table based on the provided query and field.

Parameters:

  • sTable: A string representing the name of the table.
  • sQuery: A string representing the query to filter records.
  • sField: (Optional) A string representing the field for which to count values.
  • bDisplayValue: (Optional) A boolean indicating whether to include display values.
  • bDisplayValueOnly: (Optional) A boolean indicating whether to include only display values.
  • bQueryNoDomain: (Optional) A boolean indicating whether to query without considering domains.

Returns: Returns an integer with the count or an array of record counts grouped by the provided sField parameter.

sumRecordsField

Purpose: This function sums up the field values for records.

Parameters:

  • sTable: A string representing the name of the table.
  • sField: (Optional) A string representing the field for which to sum up the values.
  • sQuery: A string representing the query to filter records.
  • bQueryNoDomain: (Optional) A boolean indicating whether to query without considering domains.

Returns: The number with the sum of all field values.

getRecord

Purpose: This function retrieves one records from a specified table based on the provided query or sys_id and options ensuring the record is return in the correct class.

Parameters:

  • sTable: A string representing the name of the table.
  • sQueryOrSysId: A string representing the query or the sys_id to find the record.
  • bWorkflow: A boolean indicating whether to include workflow information.
  • bAutoSysFields: A boolean indicating whether to include auto-system fields.
  • bQueryNoDomain: A boolean indicating whether to query without considering domains.
  • bNoEngines: A boolean indicating whether to use database engines (validate data dictionary).

Returns: Returns a GlideRecord object with the retrieved record in the real class.

getRecords

Purpose: This function retrieves records from a specified table based on the provided query and options.

Parameters:

  • sTable: A string representing the name of the table.
  • sQuery: A string representing the query to filter records.
  • aOrderBy: An array of strings representing fields to order records by.
  • aOrderByDesc: An array of strings representing fields to order records by in descending order.
  • iLimit: An integer representing the maximum number of records to retrieve.
  • bWorkflow: A boolean indicating whether to include workflow information.
  • bAutoSysFields: A boolean indicating whether to include auto-system fields.
  • bQueryNoDomain: A boolean indicating whether to query without considering domains.
  • bNoEngines: A boolean indicating whether to use database engines (validate data dictionary).
  • bNoCount: A boolean indicating whether to prevent the count to optimize performance.
  • aExtraFields: An array of extra fields to speed up the dot walked data retrieval function

Returns: Returns a GlideRecord object with the retrieved records.

getRecordsFields

Purpose: This function retrieves records fields from a specified table based on the provided query. This is usually faster than retrieving the whole GlideRecord and will return a GlideAggregate object that can be iterated.
Attention: There is a limit on the number of records returned defined in the property glide.db.max.aggregates (default: 100'000)

Parameters:

  • sTable: A string representing the name of the table.
  • sQuery: A string representing the query to filter records.
  • aFields: An array of strings representing fields to be returned.
  • aOrderBy: An array of strings representing fields to order records by.
  • bQueryNoDomain: A boolean indicating whether to query without considering domains.

Returns: Returns a GlideAggregate object with the retrieved records and fields or undefined if one of the parameters is missing or the returned count is bigger than the allowed count.

checkRecordByField

Purpose: This function checks if a record exists in a specified table with a given field-value pair.

Parameters:

  • sTable: A string representing the name of the table.
  • sField: A string representing the field to check.
  • sValue: A string representing the value to check for in the specified field.

Returns: Returns a boolean value indicating whether a record with the specified field-value pair exists.

getSysIdByQuery

Purpose: This function retrieves the sys_id of a record in a specified table based on the provided query.

Parameters:

  • sTable: A string representing the name of the table.
  • sQuery: A string representing the query to filter records.
  • bUniqueOnly: A boolean indicating whether to retrieve only unique records.

Returns: Returns the sys_id of the first matching recor . If bUniqueOnly is true returns undefined if more than one record is found.

getRelatedRecordByKeys

Purpose: This function retrieves a related record based on specified keys and configurations using the getRecordByKeys function below.

Parameters:

  • oRecordConfig: An object containing configuration for record retrieval.
  • oRecordValues: An object containing values for record retrieval.
  • aError: An array to store error messages.
  • oField: A field or configuration object for specifying the field to search.
  • sRefTable: The reference table to use if not specified in the field configuration.
  • iArrayField: An optional index for array fields.

Returns: Returns the unique value (sys_id) of the related record if found, or an empty string if not found.

getRecordByKeys

Purpose: This function retrieves a record based on specified keys and configurations.

Parameters:

  • oRecordConfig: An object containing configuration for record retrieval.
    sTargetTable: table to lookup record
    aKeys: array of keys to look for to identify record (first one that produces a result is taken)
      A key (string or object) or an array with key combinations (all must match) to uniquely identify a record
        2.1 'key_field': simple key field taking the value of the respective value field (fieldname in source body and target record are the same)
        2.2 Array of key fields ['key_field_1', 'key_field_2'], key combinations (all must match) to uniquely identify a record
          If the input field is different from the target field or the target field is a dot walk field you can replace the string with an object that contains the following properties:
            'sInputField': 'input_field', --> field from oRecordValues where the value is found
            'sTargetField': 'target_field', --> field in the sTargetTable record (can be a dot walk field like caller_id.email)
            'sAddlQuery': 'active=true', --> additional query to be applied to the target lookup
            'bQueryEmptyFields': 'true/false', --> if input_field is empty will add a query: input_fieldISEMPTY
    
  • oRecordValues: An object containing field / value pairs.
  • aError: An array to store error messages.
  • bRecordLookupUseBaseTable: (Default: false) If this is set to true and the record cannot be found on the original table, will search as well in the base table.

Returns: Returns a GlideRecord object with the retrieved record if found, or undefined if not found.

convertGRtoJSON

Purpose: This function converts a GlideRecord to JSON format.

Parameters:

  • grRecord: The GlideRecord object to be converted.
  • bStringify: (Optional) A boolean indicating whether to return a JSON string or a JSON object (default: false).
  • bDisplayValue: (Optional) A boolean indicating whether to get the Display Value (default: false).
  • bDisplayValueOwnField: (Optional) A boolean indicating whether to get the Display Value in its own field with the "_dv" postfix (default: false).

Returns: Returns JSON or a JSON string depending on the bStringify parameter or undefined if grRecord is not a valid GlideRecord.

convertGRtoXML

Purpose: This function converts a GlideRecord to XML format.

Parameters:

  • grRecord: The GlideRecord object to be converted.

Returns: Returns XML string or undefined if grRecord is not a valid GlideRecord.

makeQueryADotWalkQuery

Purpose: This function adds a dot walking field to a query string.

Parameters:

  • sQuery: The query string to which the dot walking field is added.
  • sDotWalkField: The dot walking field to add to the query.

Returns: Returns the modified query string.

combineQueries

Purpose: This function combines two queries, considerung that one of them could contains a big OR statements (^NQ).

Parameters:

  • sFirstQuery: The first query string.
  • sSecondQuery: The second query string.

Returns: Returns the combined query string or "false" if both queries contain a big OR statement.

 

Script Include: global.GlobalToolsRecordWrite

 

doRecord

Purpose: This function inserts, updates, or deletes a record based on values and a configuration object.

Parameters:

  • oValues: An object containing the values to be inserted or updated.
  • oConfig: A configuration object specifying the table, query, and other options for the operation.
    bLog: (Optional) if true does verbose logging (default: false)
    bQueryEmptyFields: (Optional) if true does add <field>ISEMTPY for empty values (default: false)
    aQueryFields: fields where the value will be used to query the record
    sTargetTable: table to be queried
    bInsert: (Optional) if true does allow insert (default: true)
    bUpdate: (Optional) if true does allow update (default: true)
    bDelete: (Optional) if true does delete (default: false)
    bNoWorkflow: (Optional) if true does grRecord.setWorkflow(false) (default: false)
    bNoEngine: (Optional) if true does grRecord.setUseEngine(false) (default: false)
    bNoAutoSysFields: (Optional) if true does grRecord.autoSysFields(false) (default: false)
    bNoDomain: (Optional) if true does grRecord.queryNoDomain() (default: false)
    bKeepSysId: (Optional) if true does grRecord.setNewGuidValue(<sys_id>) on insert (default: false)
    oValues: (Optional) list of hardcoded field/value pairs to be set on the target record (will be overwritten if also provided in the oValues parameter)
    aTargetFields: (Optional) if set, only these fields can be set, no matter what is defined in the oValues parameter.

 

  • oError: An object to store error information.
    001 = missing query
    002 = error updating: <errormessage>
    003 = error inserting: <errormessage>
    004 = missing table
    005 = exception: <exception>
    006 = error deleting: record not found

Returns: Returns the unique ID of the inserted or updated record or an error message.

doRecordByName

Purpose: This function creates a record in a table based only on the name. The function will evaluate the following fields in order to determine the name field: 'name', 'user_name', 'display_name', 'title', 'short_description'. If none of these fields exist it will use the display field, if that is not set it will do nothing.

Parameters:

  • sTargetTable: The table where the record shall be created.
  • sName: The name of the record.

Returns: sSysId of the record if it's created or exists, else undefined.

 

updateMultiple

Purpose: This function updates multiple records in a table based on values and a query.

Parameters:

  • oValues: An object containing the values to be updated.
  • oConfig: A configuration object specifying the table, query, and other options for the update.
    bLog: (Optional) if true does verbose logging (default: false)
    sTargetTable: table to be queried
    sQuery: query to be applied
    bNoWorkflow: (Optional) if true does grRecord.setWorkflow(false) (default: false)
    bNoEngine: (Optional) if true does grRecord.setUseEngine(false) (default: false)
    bNoAutoSysFields: (Optional) if true does grRecord.autoSysFields(false) (default: false)
    

Returns: true if update executed, else undefined.

deleteMultiple

Purpose: This function deletes multiple records in a table based on a query.

Parameters:

  • sTargetTable: The table where the records shall be deleted.
  • sQuery: The query to find the records to be deleted.

Returns: true if delete executed, else undefined.

setGRValue

Purpose: This function sets a value for a field in a GlideRecord object.

Parameters:

  • grRecord: The GlideRecord object to be updated.
  • sField: The name of the field to update.
  • oValue: The value to set for the field.

Returns: Updates the field value in the grRecord object.

abortGRAction

Purpose: This function aborts a grRecord action, such as an update or insert.

Parameters:

  • grRecord: The GlideRecord object for which to abort the action.

Returns: Aborts the specified action for the grRecord object.

 

Script Include: global.GlobalToolsRecordWriteValidate

This script will be documented in detail in a community article later.

initialize

Purpose: This initializes the class.

Parameters:

  • gtCache: Can inherit a shared GlobalToolsCache class.
  • oTimer: Can inherit a shared GlobalToolsDateTime class.

validateAndWrite

Purpose: This function validates and writes a record based on configuration and values.

Parameters:

  • oRecordConfig: A configuration object specifying the record target table, options, and other settings.
    bLog: (Optional) Default: false, will add additional logs depending on sLogLevel defined.
    sLogLevel: (Optional) Default: error, if bLog is true you can choose info or debug for verbose logging.
    bLogPrefix: (Optional) Default: GlobalToolsRecordWriteValidate -.
    
    sTargetTable: The table to update inserted/updated.
    sTableSequenceId: (Optional) Default: default, if provided will use this id in error object and as IRE internal_id.
    
    sErrorReturnType:
    	code: array of error codes
    	message: array of error messages (detailed)
    	normal (default): array of objects with error details (code, message, messagedetail)
    	full: like normal but additionally provide error type (runtime, config, value, system, record), message and message detail arguments
    
    bUseIRE: (Optional) Default: false, if true will use IRE to create/update records.
    bLogIREOutput: (Optional) Default: false, if true will log the IRE engine output to the system log.
    sDataSourceIRE: (Optional) Default: "Other Automated", first parameter for the IdentificationEngine.createOrUpdateCI function.
    bDataSourceIREfromValues: (Optional) Default: false, take IRE Data Source (first parameter of the IdentificationEngine.createOrUpdateCI function) from "discovery_source" field value if it is a valid choice entry. bDoAction: (Optional) Default: true, if false will not run final action. sAction: insert (only), update (only), save (insert/update) or delete. bInsert: (Optional) Default: false, is overwritten by sAction. bUpdate: (Optional) Default: false, is overwritten by sAction. bDelete: (Optional) Default: false, is overwritten by sAction. bUseGlideRecordSecure: (Optional) Default: false, if true will use GlideRecordSecure instead of GlideRecord. bNoDomain: (Optional) Default: false, if true will use GlideRecord.queryNoDomain() instead of GlideRecord.query(). bNoWorkflow: (Optional) Default: false, if true will set GlideRecord.setWorkflow(false). bNoAutoSysFields: (Optional) Default: false, if true will set GlideRecord.autoSysFields(false). bNoTrim: (Optional), Default: false, if true will not trim the value. bKeepSysId: (Optional) if sys_id is set and action is insert then apply this sys_id. bAllowClassChange: (Optional) if true, will use getRecordByKeys with the bRecordLookupUseBaseTable set to true. bTemplateIsMandatory: (Optional) Default: false, if true, either sTemplateName or sTemplateValueField must be set (and sTemplateValueField must have a valid template in the values object provided). sTemplateName: (Optional) name if the template is to be applied (is overwritten if a valid value in the values object for the field sTemplateValueField is provided). sTemplateValueField: (Optional) Default "template", if set uses this field to retrieve the template name from the values object. bTemplateDeleteFieldValue: (Optional) Default: false, if true will remove the template field from the payload before running throught the values. aMandatoryFields: (Optional) if set, these fields must have a value in the values object. bCheckDictionaryMandatory: (Optional) Default: true, if false will not check mandatory dictionary fields. bCheckDataPolicy: (Optional) Default: true, if false will not check data policy. bCheckDataPolicyMandatory: (Optional) Default: true, if false will not check data policy for mandatory fields. bCheckDataPolicyReadOnly: (Optional) Default: true, if false will not check data policy for read-only fields. sCheckDataPolicyAdditionalQuery: (Optional), if set will apply the query when looking for data policies. aIgnoreChoiceFields: (Optional) Default: ['short_description'], if set will not check these fields for valid choices. bErrorOnAddlFieldsInValues (Legacy: bErrorOnAddlFieldsInBody): (Optional) Default: false, if true will return error 400_010 if values object contains more fields than aFields. bErrorOnInvalidFieldsInValues: (Optional) Default: true, if true will return error 400_013 if values object contains fields that do not exist in target record table dictionary. oErrorHandling: (Optional) Default: "reject", Granularly define how you want to handle errors (reject = do not save record and show error, ignore = save record without error, warn = save record and show error, ignore_reject = do not save record and don't show error, this is valid only for oErrorType and oErrorCode configurations) sErrorHandlingCacheName: (Optional), Default "GlobalTools/oErrorMessages", business rules that abort insert/update operations can store proper error messages as string, array or object in this transaction cache location (using GlobalToolsCache.setValue). oErrorType: (Optional) Will override all other error handling settings on field type or field level, so be careful) runtime: errors that happen during runtime config: invalid configuration object errors value: invalid value object errors system: invalid system configuration errors record: errors during record action oFieldType: (Optional) Value errors for a specific internal field type --> can be overwritten on field level with parameter sErrorHandling all: (Optional) Default for all field types. sErrorHandling: Default "reject" or from oErrorType/value setting (valid values reject, warn, ignore) reference: (Optional) Specific error handling for reference fields, has additional options: mapping = use the Mapping Config Manager, replace = replace with a value from sDefaultValue on field (error if not defined), create = create default record (use sRecordName to generate record), leaveempty = replace with empty value sErrorHandling: (Optional) Default "reject" or from oFieldType/all setting (valid values reject, warn, ignore, mapping, replace, create, leaveempty) sRecordName: (Optional) name to be used to create reference values (Default: 'DataQualityIssue') --> can be overwritten on field level with parameter sErrorHandlingRecordName oByReferenceTable: (Optional) Specific error handling for all references to this reference table <table name or base table name>: (Optional) Default "reject" or from oFieldType/reference/sErrorHandling setting (valid values reject, warn, ignore, mapping, replace, create, leaveempty). Will first take real reference table and then check for base table entry (no hierarchy). choice: (Optional) Specific error handling for choice list fields, if Element Descriptor is choice independent of real field type, will ignore aIgnoreChoiceFields and sys_class_name fields, has additional options: mapping = use the Mapping Config Manager, replace = replace with a value from sDefaultValue on field (error if not defined), leaveempty = replace with empty value sErrorHandling: (Optional) Default "reject" or from oFieldType/all setting (valid values reject, warn, ignore, mapping, replace, leaveempty) sChoiceName: (Optional) name to be used to replace reference values (default: 'DataQualityIssue') --> can be overwritten on field level with parameter sDefaultValue oErrorCode: (Optional) Define specific error handling for a particular error code --> will override other definitions above. : (Optional) Default "reject" or (valid values reject, warn, ignore, ignore_reject) bStateFlowActionIsMandatory: (Optional) Default: false, if true, either sStateAction or sStateActionId must be valid (lookup of the sActionValueField must have a valid sStateFlowAction in the values object provided). sStateFlowActionValueField: (Optional) Default: "action", if set uses this field to retrieve the sStateFlowAction name from the values object. bStateFlowActionDeleteFieldValue: (Optional) Default: false, if true will remove the action field from the payload before running throught the values. oStateFlowActionConfig: (Optional), object with state flow actions: sStateFlowAction: Value from the sStateFlowActionValueField in the values object: sStateAction: Name of the state flow action. sStateActionId: SysId of the state flow action. bWorkNotesMandatory: if this action, worknotes are mandatory. aDynamicFieldConfig: (Optional), will evaluate a query condition or input value object checks and if true modifies the fields and mandatory fields. sQueryCondition: (Optional), will run a filter against the old record and dynamically modify fields if true. aInputValueChecks: (Optional), will run checks against the values object and dynamically modify fields if true. sField: field where the value check is run against. sRegExpPattern: (Optional), regular expression to be run against the value in the sField sRegExpFlags: (Optional), regular expression flags to be used in above regex check. sScript: (Optional), script to be evaluated. Before the script is run all occurrences of "sValue" will be replaced by the actual field value. aFields: (Optional), if any of the above evaluation methods is true these fields will be added to the field configuration (aFields). aFieldsRemoval: (Optional), if any of the above evaluation methods is true these fields will be removed from the field configuration (aFields). aMandatoryFields: (Optional), if any of the above evaluation methods is true these fields will be added to the mandatory fields configuration (aMandatoryFields). aMandatoryFieldsRemoval: (Optional), if any of the above evaluation methods is true these fields will be removed from the mandatory fields configuration (aMandatoryFields). aInputValueChecks: (Optional), validate input values before starting field validation. sField: field where the value check is run against. sRegExpPattern: (Optional), regular expression to be run against the value in the sField sRegExpFlags: (Optional), regular expression flags to be used in above regex check. sScript: (Optional), script to be evaluated. Before the script is run all occurrences of "sValue" will be replaced by the actual field value. sErrorMessage: if any of the above evaluation methods is true then this error will be set with the generic error: 400_038 Input values check failed aKeysDefaultReferenceFields: (Optional), Default: ["sys_id"], if set will use the array values as keys if "aKeys" is empty. bKeysDefaultReferenceDisplayField: (Optional) Default: false, if true will use the grRefRecord.getDisplayField from the reference table as key if "aKeys" is empty. aKeys: (Optional for insert, mandatory for update/delete) Default: see GlobalToolsRecordRead.getRecordByKeys for documentation. aFields: (Optional), if set is an array of fields to be updated including special field configurations for value mapping and lookup. sField: string with the effective field name. oField: object with a specific field configuration. sField: name of the field in the table. sSourceField: name of the field in the values object. bDisplayValue: if true replaces the value with the display value if available.
    sErrorHandling: see oErrorHandling for details for each field type. sFieldAction: ignore (will not use this field for validation and does not apply values), ignore_insert / ignore_update (will not apply values accordingly). sRefTable: (Optional), if set will use this table for lookup, if empty the sField dictionary reference table is used. aKeys: see GlobalToolsRecordRead.getRecordByKeys for documentation. sDefaultValue: (Optional), if set replaces an empty field value with this value. sFixedValue: (Optional), if set replaces any value with this value. bNoTrim: (Optional), Default: false, if true will not trim the value. sPrefix: (Optional), if set adds a prefix to the value. sPostfix: (Optional), if set adds a postfix to the value. sRelatedTableResultId: (Optional), if set, will lookup the value (usualy sys_id) from another table treated earlier in the integration (/oRelatedTableResultIds/sRelatedTableResultId in the configuration object). bAddValues: (Optional), Default false, if true and field is a list will preserve old values and add the new values if they are not present. sRefLookupScript: (Optional), will run function in sRefLookupScript this, if empty will look for a generic function in the "oTransformConfig/oTypeMap/reference/" + sRefTable + "/sRefLookupScript". Parameters passed to the sRefLookupScript: bLog: bLog from config. sField: sField from field object. sValue: sRefInput, value from values object. sTargetTable: main table for record. sRefTable: reference lookup table. oField: field object. grRecord: current record. oRecordConfig: configuration object. oRecordValues: values object. oRecordDisplayValues: display values object (if exists). Example: sRefLookupScript: "function (oParams) {gs.info('Demo sField: ' + oParams['sField'] + ' sValue: ' + oParams['sValue']);return oParams['sValue'];}" oTransformConfig: (Optional), if set is an object containing transform instructions. oFieldMap: (Optional), if set is an object containing value pairs for a specific field, if the key is found the value is replaced. "field_name": oMap: {"old_value": "new_value"} oTypeMap: (Optional), if set is an object containing value pairs for a specific field, if the key is found the value is replaced. "internal_field_type": oMap: {"old_value": "new_value"} "reference": "sRefTable": sRefLookupScript: (Optional), if set, uses this function to retrieve the reference value (same parameters as the function under aFields/oField config object) bImpersonateMandatory: (Optional) Default: false, if true, either sImpersonateDefaultUser or sImpersonateValueField must be set (and sImpersonateValueField must have a valid user in the values object provided). sImpersonateDefaultUser (Legacy: sDefaultUser): (Optional), if set a lookup is made on the sys_user table on sys_id, user_name and email. sImpersonateValueField: (Optional), Default "user", if set is used to find the property in the values object and a lookup is made on the sys_user table on sys_id, user_name and email. bImpersonateDeleteFieldValue: (Optional) Default: false, if true will remove the "sImpersonateValueField" field from the payload before running throught the values. aUpdateBusinessLogicChecks: (Optional) if set is an array of objects containing before and after queries that if not fulfilled, will generate the error specified. sBeforeQuery: (Optional), if set is run against the GlideRecord as retrieved by the aKeys definition. sAfterQuery: (Optional), if set is run against the GlideRecord after all values have been applied. sErrorMessage: the error message to be returned if either of the queries do not evaluate to true. aCustomScripts: (Optional) if set is an array of objects containing scripts to be run bRunBefore: (Optional) Default: false, if true script is run before action sScript: script to be executed The following variables are available in the script: bLog Boolean sAction String Values [insert, update, delete and save (could be insert or update)] bIsValidRecord Boolean oRecordConfig Object oRecordValues Object oRecordDisplayValues Object sTargetTable String grRecord GlideRecord grRecordOld GlideRecord
  • oRecordValues: An object containing the values to be validated  (field / value pair). This can be the result of a REST GET operation (optional also in the notation with the display value "all" parameter) or an object with values and display_values properties containing the already parsed objects.
  • oError: An object to store error information. Use sErrorReturnType property to define the returned values.
    400_001: Missing or empty record values object
    
    400_002: Template is mandatory
    400_003: Invalid Template
    
    400_004: Fields are mandatory (Data Policy)
    400_005: Fields are mandatory (Config)
    
    400_006: Stateflow action is mandatory
    400_007: Stateflow action is not valid
    400_008: Stateflow action not found
    400_009: Stateflow action worknotes are mandatory
    
    400_010: Fields that are not configured are not allowed
    
    400_011: Invalid field in config object
    400_012: Invalid field in mandatory fields
    400_013: Invalid field in values object
    
    400_014: Update business logic check failed
    
    400_015: Invalid value in reference field (not found)
    400_039: Invalid value in reference field (not found, created)
    400_040: Invalid value in reference field (not found, not created)
    400_016: Invalid dependent reference field configuration
    400_017: Invalid value in reference field (ref qualifier)
    400_018: Invalid choice list configuration
    400_019: Invalid value in choice list field
    400_020: User is not a member of the group
    400_021: Invalid boolean value
    400_022: Invalid array value
    400_023: Invalid date/time value
    400_024: Invalid date value
    400_025: Invalid time value
    400_026: Invalid integer number value
    400_027: Invalid floating point number value
    400_028: Invalid email address
    400_029: Invalid phone number
    400_030: Invalid ip address
    400_034: Invalid duration value
    400_035: Invalid document id or table
    400_036: Invalid table
    400_037: Invalid GUID value
    400_038: Input values check failed
    
    400_031: Invalid field configuration in config object (missing field property)
    400_032: Invalid field configuration in config object (invalid field type)
    400_033: Invalid key configuration in config object
    
    400_101: Access denied: record create
    400_102: Access denied: record write
    400_103: Access denied: record delete
    400_104: Access denied: field write
    400_105: Access denied (Data Policy): field write
    400_106: Access denied: field create
    
    403_001: Invalid impersonate user provided
    403_002: Impersonate user is mandatory
    403_003: Impersonating failed
    403_004: Impersonating failed and is mandatory
    
    404_001: Invalid action: record delete
    404_002: Invalid action: record insert
    404_003: Invalid action: record update
    
    405_001: Missing or empty configuration object or target table
    405_002: Invalid action: conflict
    405_003: Invalid action: empty
    
    406_001: Warning processing IRE
    406_002: Error processing IRE
    
    500_001: Error processing stateflow action
    500_002: Error processing business logic
    500_003: Error inserting record
    500_004: Error updating record
    500_005: Error deleting record
    500_006: Error getting reference field value
    500_007: Error processing input values check script
    500_008: Error processing business rules and engine
    500_009: Error validating and applying field value
    500_010: Error processing custom script
    500_011: Error updating record during class switch
    500_011: Error selecting record during class switch

 

Returns: Returns the unique ID of the written record or an error message.

validateAndReturnIREObject

Purpose: This function validates data and returns an object, such as an Incident Request (IRE), based on configuration and values.

Parameters:

  • oRecordConfig: A configuration object specifying the record target table, options, and other settings (same as validateAndWrite).
  • oRecordValues: An object containing the values to be validated (same as validateAndWrite).
  • oError: An object to store error information (same as validateAndWrite).

Returns: Returns an object with the IRE payload.

 

Script Include: global.GlobalToolsATF

 

initialize

Purpose: This function initializes the class with parameters.

Parameters:

  • sScriptIncludeName: The name of the Script Include to be tested.
  • _ScriptIncludeRef: The initialized Script Include to be tested var _si = new myScriptInclude(); is null.
  • outputs: The outputs parameter from ATF test step
  • steps: The steps parameter from ATF test step
  • params: The params parameter from ATF test step
  • stepResult: The stepResult parameter ATF from test step
  • assertEqual: The assertEqual parameter ATF from test step

 

runATF

Purpose: This function runs the specific function and passes all variables except script and expected value to it.

Parameters:

  • sFunction: The Script Include sFunction to be tested.
  • oExpectedResult: The expected return value from sFunction call.
    oExpectedResult is a number or a string containing a comparison and a number ("<10", ">10", "<=10", ">=10") and the result is of type, number, array or gliderecord it will return an error if the comparison is not true (e.g. if the number is 1 and the array does not contain exactly 1 element or the gliderecord count is not 1).
    oExpectedResult is a string and the oResult is a gliderecord then grRecord.getUniqueValue() will be compared against the string.
    oExpectedResult is a regex the then the result will converted to string and is tested against the regex.
    oExpectedResult is a function the then the function will be called with parameters:
    	oResult and sResultType and an error will be added if the function returns a value: (sErrorMessage)
    oExpectedResult is anything else it will be compared to the result (===).
    
  • arguments: (Optional) The arguments that will be passed to the sFunction.

Returns: The true if test is successful or undefined if it failed.

getRecord

Purpose: This function uses the GlobalTools.getRecords function and if successful does a grRecord.next() to get the first record.

Parameters:

  • sTable: The table where the record is located.
  • sQuery: The query to find the record.

Returns: The a GlideRecord if successful or undefined if no record is found.

addError

Purpose: This function adds an error to the error array.

Parameters:

  • sFunction: The Script Include sFunction that was tested.
  • sError: The error in validation of running the sFunction call.

 

endATF

Purpose: This function parses the result, sets the error message if any and ends the ATF test.

Returns: The true if test is successful or false if it failed.

Script Include: global.GlobalToolsRESTAPI

 

initialize

Purpose: This function initializes the class with parameters.

Parameters:

  • oConnectionAlias: The Connection & Credential Alias [sys_alias] to be used in the REST API (can be the GlideRecord or the value any of the fields: sys_id, id, name).
  • bLog: (Optional) if true does verbose logging (default: false)
  • bQueryNoDomain: (Optional) if true will add sysparm_query_no_domain=true (default: false)

 

getConnectionConfig

Purpose: This function returns an object with the configuration values determined from the initialize function parameters.

Parameters:

  • bStringify: (Optional) if true returns a stringified object (default: false)

Returns: The configuration object or string with the configuration details.

 

testNOWConnection

Purpose: This function does a REST call using the configuration to fetch one record from the task table.

Returns: Returns an object where property "success" is true if successful or false if there was an error or no record is found. The object also contains a message property with error messages.

 

getRemoteRecord

Purpose: This function uses the table API of a ServiceNow instance to retrieve a single record based on the parameters provided and return it as a glide record.

Parameters:

  • sTable: A string representing the name of the table.
  • sQuery: (Optional) A string representing the query to filter records (sysparm_query URL parameter).

Returns: The a glide record or a object with the error details.

{ 
'success': false, 
'message': sErrorMsg, 
'error_code': sStatus
}

 

doNOWRESTQuery

Purpose: This function uses the table API of a ServiceNow instance to retrieve records based on the parameters provided.

Parameters:

  • sTable: A string representing the name of the table.
  • sQuery: (Optional) A string representing the query to filter records (sysparm_query URL parameter).
  • sOffset: (Optional) A string representing the offset to be used when getting more records than defined in the limit (sysparm_offset URL parameter) Default: "0".
  • sLimit: (Optional) A string representing the maximum number of records to be returned (sysparm_limit URL parameter) Default: 1000.
  • aFields: (Optional) A array with the fields to be returned. If the URL length limit is reached the parameter is omited and an error is logged (sysparm_fields URL parameter) Default: [].
  • sDisplayValue: (Optional) If "true" will return display values instead of real values, "all" will return both real value and display value (sysparm_display_value URL parameter) Default: "false".
  • oRequestBodyOrAttachmentInfo: (Optional) An object containing the details on which record and filename the result body should be attached as a file:
    {
    	'sTable': 'incident',
    	'sSysId': 'd71f7935c0a8016700802b64c67c11c6',
    	'sFilename': 'RESTAttachment.json',
    }
    
  • bIncludeRefLink: (Optional) if true does return URLs for each reference fields (sysparm_exclude_reference_link=true URL parameter) Default: false.

Returns: The request result body array or a object with the error details.

{ 
'success': false, 
'message': sErrorMsg, 
'error_code': sStatus
}

 

doNOWRESTCount

Purpose: This function uses the stats API of a ServiceNow instance to count records based on the parameters provided.

Parameters:

  • sTable: A string representing the name of the table.
  • sQuery: (Optional) A string representing the query to filter records (sysparm_query URL parameter).
  • sGroupByField: (Optional) A string representing the field used to group the records (sysparm_group_by URL parameter).
  • bOrderByCount: (Optional) If true and group by field is not empty, will order the result descending by count, else by group by field name (sysparm_order_by URL parameter).
  • sDisplayValue: (Optional) If "true" will return display values instead of real values, "all" will return both real value and display value (sysparm_display_value URL parameter) Default: "false".
  • bOmitEmptyValues: (Optional) If true will not return count for empty values.

Returns: The the count as number or as object where the key is the group by field value and the value the count or a object with the error details.

Error:
{ 
'success': false, 
'message': sErrorMsg, 
'error_code': sStatus
}

Count result:
9

Count sGroupByField and  bOrderByCount:
{
'inquiry':18,
"software":8,
'hardware':5,
'network':4,
'database':1
}

 

doRESTRequest

Purpose: This function does a REST call using the configuration parameters provided.

Parameters:

  • sUrl: The string complimenting the connection URL.
  • sMethod: (Optional) A string representing the method (allowed values: GET, POST, PUT, PATCH) Default: GET.
  • oRequestBodyOrAttachmentInfo: (Optional) For GET method this is an object containing the details on which record and filename the result body should be attached as a file:
    {
    	'sTable': 'incident',
    	'sSysId': 'd71f7935c0a8016700802b64c67c11c6',
    	'sFilename': 'RESTAttachment.json',
    }
    
    For all other methods it's either the object (will be converted to string via JSON.stringify) or string to be used in the request body or a valid sys_id of an attachment [sys_attachment] that should be used as the request body.
  • oHeader: (Optional) An array (of arrays or objects) or an object containing the key/value pairs to be set as header information in the request.
  • sLogLevel: (Optional) Value will be passed to the setLogLevel function of the REST request to enable granular logging.
  • bTestConnection: (Optional) if true does return an object where property "success" is true if successful or false if there was an error or no record is found. The object also contains a message property with error messages but no further details.
  • bRunAsynch: (Optional) if true uses executeAsync instead of execute function.
  • iWaitForResponseSeconds: (Optional) Default: 5, number of seconds to wait for the response before a timeout occurs.

Returns: The request result body or a object with the error details.

{ 
'success': false, 
'message': sErrorMsg, 
'error_code': sStatus
}

 

Script Include: global.GlobalToolsAttachment

 

getAttachmentsByRecord

Purpose: This function gets the attachment information for a specific record based on the input parameters.

Parameters:

  • grRecord: The glide record for which the attachments are retrieved.
  • sQuery: (Optional) The query to be applied on the sys_attachment table.
  • sReturnType: (Optional) The return type if the attachment information: id, filename or object with both as array or record as glide record. Default: id
  • bHidden: (Optional) Use ZZ_YY prefix on table name for attachments that are hidden from the user.

Returns: The array or glide record respecting the type specified in sReturnType

getAttachmentsStartWithFilename

Purpose: This function gets the attachment information for a specific record and files starting with a specific string.

Parameters:

  • sTable: The glide record table for which the attachments are retrieved.
  • sId: The sys_id of the base record for which the attachments are retrieved.
  • sFilename: The filename to be applied as a "file_nameSTARTSWITH" query on the sys_attachment table.
  • sReturnType: (Optional) The return type if the attachment information: id, filename or object with both as array or record as glide record. Default: id
  • bHidden: (Optional) Use ZZ_YY prefix on table name for attachments that are hidden from the user.

Returns: The array or glide record respecting the type specified in sReturnType

getAttachments

Purpose: This function gets the attachment information for a specific record based and a specific query.

Parameters:

  • sTable: The glide record table for which the attachments are retrieved.
  • sId: The sys_id of the base record for which the attachments are retrieved.
  • sQuery: (Optional) The encoded query to be applied on the sys_attachment table.
  • sReturnType: (Optional) The return type if the attachment information: id, filename or object with both as array or record as glide record. Default: id
  • bHidden: (Optional) Use ZZ_YY prefix on table name for attachments that are hidden from the user.

Returns: The array or glide record respecting the type specified in sReturnType

readAttachmentStream

Purpose: This function reads the attachment information for a specific record and attachment filename.

Parameters:

  • sTable: The glide record table for which the attachment is retrieved.
  • sId: The sys_id of the base record for which the attachment is retrieved.
  • sFilename: The filename to be applied as a "file_name=" query on the sys_attachment table.
  • bHidden: (Optional) Use ZZ_YY prefix on table name for attachments that are hidden from the user.

Returns: The string of the attachment content.

readAttachmentStreamFromId

Purpose: This function reads the attachment information for a specific attachment.

Parameters:

  • sId: The sys_id of the attachment to be retrieved.

Returns: The string of the attachment content.

combineAttachments

Purpose: This function reads multiple attachments for a specific record and attachments that start with a specific filename.

Parameters:

  • sTable: The glide record table for which the attachment is retrieved.
  • sId: The sys_id of the base record for which the attachment is retrieved.
  • sFilename: The filename to be applied as a "file_nameSTARTSWITH" query on the sys_attachment table.
  • bReturnJSON: (Optional) Parses the text string to an JSON object.
  • bDeleteAfterRead: (Optional) If successful deletes the attachments after reading.
  • bHidden: (Optional) Use ZZ_YY prefix on table name for attachments that are hidden from the user.

Returns: The string or JSON of the combined attachment content.

getAttachmentSizePerRecord

Purpose: This function gets the total attachment size information for a specific record based and a specific query.

Parameters:

  • sTable: The glide record table for which the attachments are retrieved.
  • sId: The sys_id of the base record for which the attachments are retrieved.
  • sQuery: (Optional) The encoded query to be applied on the sys_attachment table.
  • sReturnType: (Optional) The return type if the attachment information: full, compressed or object with both. Default: compressed
  • sNotation: (Optional) The string definining the notation to be used to format the result: number (no notation), si (base 1000) or iec (base 1024) Default: si.
  • bHidden: (Optional) Use ZZ_YY prefix on table name for attachments that are hidden from the user.

Returns: The number, string or object respecting the type specified in sReturnType

getAttachmentSize

Purpose: This function gets the total attachment size information for a specific record based and a specific query.

Parameters:

  • sQuery: (Optional) The encoded query to be applied on the sys_attachment table.
  • sReturnType: (Optional) The return type if the attachment information: full, compressed or object with both. Default: compressed
  • sNotation: (Optional) The string definining the notation to be used to format the result: number (no notation), si (base 1000) or iec (base 1024) Default: si.

Returns: The number, string or object respecting the type specified in sReturnType

writeAttachment

Purpose: This function writes an attachment to a specific record.

Parameters:

  • grRecord: The glide record to which the file is attached in the sys_attachment table..
  • sFilename: The filename to be set (field file_name).
  • sContent: The content of the attachment.
  • sContentType: (Optional) If undefined the string after the last . (dot) of the sFilename is taken.
  • bBase64: (Optional) Write the content as Base64 encoded string.
  • bHidden: (Optional) Use ZZ_YY prefix on table name for attachments that are hidden from the user.

Returns: The string with the attachment sys_id or undefined if not successful.

writeAttachmentByTableId

Purpose: This function writes an attachment to a specific record.

Parameters:

  • sTable: The glide record table for which the attachment is written.
  • sId: The sys_id of the base record for which the attachment is written.
  • sFilename: The filename to be set (field file_name).
  • sContent: The content of the attachment.
  • sContentType: (Optional) If undefined the string after the last . (dot) of the sFilename is taken.
  • bBase64: (Optional) Write the content as Base64 encoded string.
  • bHidden: (Optional) Use ZZ_YY prefix on table name for attachments that are hidden from the user.

Returns: The string with the attachment sys_id or undefined if not successful.

deleteAttachment

Purpose: This function deletes a specific attachment on a specific record.

Parameters:

    • sTable: The glide record table from which the attachment is deleted.
    • sId: The sys_id of the base record from which the attachment is deleted.
    • sFilename: The filename of the attachment to be deleted (field file_name).
    • bHidden: (Optional) Use ZZ_YY prefix on table name for attachments that are hidden from the user.

 

deleteAttachmentsStartWithFilename

Purpose: This function deletes specific attachments on a specific record.

Parameters:

    • sTable: The glide record table from which the attachments are deleted.
    • sId: The sys_id of the base record from which the attachments are deleted.
    • sFilename: The starting string of the filenames for the attachment to be deleted (field file_name STARTSWITH).
    • bHidden: (Optional) Use ZZ_YY prefix on table name for attachments that are hidden from the user.

 

deleteAttachments

Purpose: This function deletes specific attachments on a specific record.

Parameters:

  • sTable: The glide record table from which the attachments are deleted.
  • sId: The sys_id of the base record from which the attachments are deleted.
  • sQuery: The query string to be applied to search for the attachments to be deleted.
  • bHidden: (Optional) Use ZZ_YY prefix on table name for attachments that are hidden from the user.

 

Script Include: global.GlobalToolsCache

 

setValue

Purpose: This function adds a value to the cache

Parameters:

  • sCachePath: The key to the cache, will convert to object properties using / as delimiter for the transaction cache.
  • sCacheValue: The value to to be stored in the cache.
  • sCacheType: (Optional) The type of cache to be used, valid values are: transaction (default which will use global variable to store the cache, glidecontroller which will use undocumented and thus not recommended GlideController function and session which uses the gs.getSession() cache function.

 

getValue

Purpose: This function retrieves a value from the cache

Parameters:

  • sCachePath: The key to the cache, will convert to object properties using / as delimiter for the transaction cache.
  • sCacheType: (Optional) The type of cache to be used, valid values are: transaction (default which will use global variable to store the cache, glidecontroller which will use undocumented and thus not recommended GlideController function and session which uses the gs.getSession() cache function.

Returns: The sValue from the specific path and cache type

 

checkValue

Purpose: This function checks if a value from the cache exists

Parameters:

  • sCachePath: The key to the cache, will convert to object properties using / as delimiter for the transaction cache.
  • sCacheType: (Optional) The type of cache to be used, valid values are: transaction (default which will use global variable to store the cache, glidecontroller which will use undocumented and thus not recommended GlideController function and session which uses the gs.getSession() cache function.

Returns: The true if the specific path in the cache type exists

 

clearValue

Purpose: This function clears a value from the cache

Parameters:

  • sCachePath: The key to the cache, will convert to object properties using / as delimiter for the transaction cache.
  • sCacheType: (Optional) The type of cache to be used, valid values are: transaction (default which will use global variable to store the cache, glidecontroller which will use undocumented and thus not recommended GlideController function and session which uses the gs.getSession() cache function.

 

resetCache

Purpose: This function empties the transaction cache

 

Script Include: global.GlobalToolsDateTime

A library with various date and time related utility functions.

initialize

Purpose: This initializes the class.

Parameters:

  • sClass: The class is the key used in for the cache (_gtdt_ if empty).
  • gtCache: Can inherit a shared GlobalToolsCache class.


formatMS

Purpose: This function formats a given integer (milliseconds) to a readable time value.

Parameters:

  • iMilliseconds: Number of milliseconds to be formatted.

Returns: The the formatted string (minutes:seconds.milliseconds ms/s/min)

 

startTimer

Purpose: This function starts or resumes a timer for a given sName

Parameters:

  • sName: The key to the timer, will convert to object properties using / as delimiter for nested structures.
  • bInternal: (Optional) Used to resume an already active timer.

Returns: The true if the timer was started successfully.

 

stopTimer

Purpose: This function stops or suspends a timer for a given sName.

Parameters:

  • sName: The key to the timer, will convert to object properties using / as delimiter for nested structures..
  • bInternal: (Optional) Used to suspend an existing timer.

Returns: The true if the timer was stopped successfully

 

getTimer

Purpose: This function returns the result for this timer.

Parameters:

  • sType: (Optional) The return value is: 
    • min: the total execution time without details.
    • default: a string of the object with all the details
    • object: an object with all the details
    • debug: a string with the current cache content for this class
    • cache: an object with the current cache content for this class

Returns: The result depending on the sType variable. 

 

Script Include: global.GlobalToolsSecurity

A library with various role and access related utility functions. 

 

initialize

Purpose: This initializes the class.

Parameters:

  • bCompareGlideRecordSecureCanCRUDClass: boolean (default: false), if true will log output to compare the GlideSecurityManager.hasRightsTo() output the the GlideRecordSecure.canRead etc result for debugging.
  • sDebugAccessAnalyzerOutputForTable: If set to a valid table will output the Access Analyzer result in the JSON.


getUsersRoles

Purpose: This function returns the roles that this particular user has.

Parameters:

  • oUserOrId: Users SysId or GlideRecord for which the roles should be retrieved.
  • sReturnType: "id"  or "name" will return an array with either the SysId or the name of the role, "boolean" will return true if the user has any role.
  • bDirectAssignment: if true will only return directly assigned roles omitting all the inherited roles for this user.
  • bExcludeSNCInternal: if true will not return the "snc_internal" role, else it will be part of the result set if available.

Returns: Depending on the sReturnType parameter will return an Array of role names or ids or true/false if a role exists.

 

getRoleIdFromName

Purpose: This function returns the SysId for the role with this name.

Parameters:

  • sRole: Name of the user role.

Returns: The SysId of the user role.

 

isValidRole

Purpose: This function returns true if the role is valid and false if the role is not valid.

Parameters:

  • ssRoleOrId: Name or SysId of the user role.

Returns: true if the role is valid and false if it's not existing in the instance.

 

generateAccessReport

Purpose: This function returns a detailed report (JSON, CSV or both) on the specific access rights a user with a role would have. Please be aware that this is a very tricky exercise and most probably the output is not 100% correct. This is due to the dynamic and configurable way ACLs and other access control mechanisms behave. But it's a good starting point to get an overview.

Because the output can be pretty big it's best called from a fix script and the result stored in an attachment. To do that create a new fix script, change line one with the SysId of the newly created Fix Script and execute it (in the foreground). The example will generate a report for the "asset" role including all tables where this role (and it's implicitly inherited roles) will give access to.

var sOwnId = '<SysIdOfTheFixScriptItself>';
var _gtAttach = new global.GlobalToolsAttachment();
var _gtSecurity = new global.GlobalToolsSecurity();
var oAccessAnalyzerSimulatorResult, oSimulatorResult;
_gtAttach.deleteAttachmentsStartWithFilename('sys_script_fix', sOwnId, 'Result.json');
_gtAttach.deleteAttachmentsStartWithFilename('sys_script_fix', sOwnId, 'Result.csv');
oSimulatorResult = _gtSecurity.generateAccessReport('asset', '', true, 'both');
if (oSimulatorResult) {
	_gtAttach.writeAttachmentByTableId('sys_script_fix', sOwnId, 'Result.json', JSON.stringify(oSimulatorResult['json']), 'txt/json');
	_gtAttach.writeAttachmentByTableId('sys_script_fix', sOwnId, 'Result.csv', oSimulatorResult['csv'], 'txt/csv');
} // if sim result


Parameters:

  • sRole: The user role that should be tested. The output will include also access that is implicitly given by the inherited roles.
  • sTableQuery: The tables that are queried can be explicitly limited by this parameter.
    Please note that implicitly the following rules apply:
    • The starting table has always to be the absolute base level (e.g. cmdb, not cmdb_ci). 
    • The following tables are excluded:
      sys_metadata
      sys_hop_token
      sys_analytics_data_points*
      v_*
      syslog00*
      ar_*
    • Data base views are excluded.
  • bExtendTables: if true will analyze the tables that extend the given base tables. If they share the same result (CRUD), the tables will be omitted from the result.
  • sOutputType: This can be either "json", "csv" or "both" (this will return a JSON with the properties "json" and "csv" for the respective object.
  • bValidateWithAccessAnalyzer: if true will also run the Access Analyzer scripts and compare the result with the output from this script.
    To use the baseline Access Analyzer functions an additional Script Include needs to be installed on the instance that acts as a scope bridge to the protected Access Analyzer Script Includes. If you want to leverage this function please contact me directly and I will send you the XML.

Returns: Depending on the sOutputType parameter will return either a JSON with the results object, a CSV string or a JSON with both the results object and the CSV string.

1 Comment