1.2 ScriptHelper functions
Below is a description of all available ScriptHelper functions.
1.2.1 Assign a voucher code (voucher codes)
The recipient with the ID customerID from the Company companyID is assigned a coupon code that is taken from the specified table. The table name follows the structure ref_{tableBaseName}_{companyID}_tbl, e.g. ref_subscribevoucher_123_tbl.
If a coupon code has already been assigned to the recipient from the table, it will not be overwritten and no other coupon code will be used.
If the recipient has a voucher code (either because it was assigned by the call or because a voucher code has already been assigned to the recipient), the method returns true. If an error occurs (e.g. invalid Company ID, no free coupon code), the method returns false. The exact error message can be found in the log file.
$ScriptHelper.assignVoucherCodeOnce($customerID, $companyID,
$tableBaseName)
#set($voucherCode=$ScriptHelper.getReferenceValue($referenceTabl eAliasName, "customer_id", "$customerID", "voucher_code"))
1.2.2 Link web push login to a possibly existing recipient
Associates a push logon with an existing receiver.
$ScriptHelper.associatePushSubscriptionWithCustomerID(@VelocityC heck final int companyID,
final int customerID, final String endpoint)
companyID and customerID are the information about the newsletter recipient, endpoint is the endpoint URL of the push registration.
1.2.3 E-mail address change by recipient
E-mail address changes are initially triggered by calling the following function:
$ScriptHelper.updateRecipientWithEmailChangeConfirmation(recipie nt, mailingID, profileFieldForConfirmationCode)
An action-based e-mail must then be sent to the new recipient address that uses the confirmation code from the specified profile field in a link as a parameter.
In the database table "pending_email_change_tbl", e-mail address changes of the recipients are stored temporarily as long as they have not yet been confirmed (corresponds to double opt-in to avoid misuse of the change function). The confirmation is then saved by the following function:
1.2.4 Change recipient data
If the data of the recipient (based on the contained CustomerID) is not yet available in the database, a new recipient is created, otherwise the existing recipient (based on the CustomerID) is updated.
#set($recipient = new RecipientImpl())
$recipient.setCustParameters("email", "new.email@example.com")
$ScriptHelper.storeRecipient($recipient)
1.2.5 Creating an AgnUID for an existing recepient
This method is used to generate an AgnUID string, which can then be used in form links to secure the recipient data (CustomerID) by encryption.
#set($agnUID=$ScriptHelper.createUidForCustomer($companyId,
$customerKeyColumnNameString,
$customerKeyColumnValueString)
Example:
1.2.6 decodeUID (String)
These functions decode the encrypted contents of an agnUID.
The following values (names are case-sensitive) are contained in the returned map:
-
companyID: CompanyID of the client
-
mailingID: MailingID of the mailing in which the link was contained
-
urlID: LinkID of the link that was clicked
-
customerID: CustomerID of the recipient
-
prefix: Prefix
1.2.7 URL encoding SessionIDs and other values
To get a URL encoding of a string value (e.g. „abc&def“ ⇒ „abc%26def“):
1.2.8 Determining the last newsletter sent out
Using the CustomerID, the CompanyID and the MailinglistID, the last newsletter can be sent to a recipient after registration.
The target groups used for the mailings are compared with the recipient profile.
#set($mail=$MailingDao.getMailing($ScriptHelper.findLastNewslett er($customerID, $companyID, $mailinglistID), $companyID)) #if($mail) $ScriptHelper.sendEventMailing($mail,
$customerID.intValue(),
0, "1", null)
#end
1.2.9 Query the name of a mailing
This call returns a string or NULL. Only mailings from the current client can be queried.
1.2.10 Query the subject of a mailing
This call returns a string or NULL. Only mailings from the current client can be queried.
1.2.11 Querying the dispatch date of a mailing
This call returns a date object or NULL. This can then be used for further purposes, for example, to format and display the dispatch date.
1.2.12 Formatting the date
The format characters are those from JAVA:
-
yyyy:Year 4 digits
-
MM: Month 2 digits
-
dd: Day 2 digits
-
hh: 24 hours, 2 digits
-
mm: Minutes 2 digits
-
ss: Seconds 2 digits
Attention: DD = Day of the year
#set ($nowDate1 = $ScriptHelper.newDate())
#set ($nowFormatted1 = $ScriptHelper.formatDate($nowDate1,
"yyyy-MM-dd", "de", "de")) ## Date informat "YYYY-MM-DD"
#set ($nowDate2 = $ScriptHelper.newCalendar().getTime())
#set ($nowFormatted2 = $ScriptHelper.formatDate($nowDate2,
"yyyy-MM-dd", "de", "de")) ## Date informat "YYYY-MM-DD"
1.2.13 Using the current date
The following expression generates the current date:
#set ($now = $ScriptHelper.newCalendar())
##1 = Year, 2 = Month, starting with 0, 5 = Day of Month
#set ($year4 = $now.get(1).toString())
#set ($month = $now.get(2) + 1)
#set ($month = $month.toString())
#set ($dayOfMonth = $now.get(5).toString())
## keep leading zeros
#if ($month.length() < 2)
#set ($month = "0$month")
#end
## keep leading zeros
#if ($dayOfMonth.length() < 2)
#set ($dayOfMonth = "0$dayOfMonth")
#end
#set ($nowFormatted = "$year4$month$dayOfMonth") ## Date informat "YYYYMMDD"
1.2.14 Formatting numbers
To convert numbers from unwanted formats (e.g. "4.5") to readable formats (e.g. "4,50"):
#set($format='###,##0.00')
#set($productPrice = $ScriptHelper.formatNumber("8.00",
$format,"de")) ## Standard decimal separator is "." ##or:
#set($productPrice = $ScriptHelper.formatNumber('8.00', '.',
'###,##0.00', 'de')) ##or:
#set($productPrice = $ScriptHelper.formatNumber('8,00', ',',
'###,##0.00', 'de'))## Use decimal separator comma
1.2.15 Convert numbers to strings
(Long) numerical values are sometimes required in string format:
1.2.16 Convert string to number
String Numerical values are sometimes needed as real numbers again
1.2.17 Convert int-number to integer-number
Very rarely, simple numerical values (int) are required as integer numbers (Java class integer).
1.2.18 Requesting the last mailing sent to a recipient
This call returns a mailing ID. This ID can then be used for further purposes, e.g. to resend the mailing or to log the ID somewhere.
1.2.19 Creating a "double quotation mark"
Since it is difficult to create the character "double quotation mark" in velocity scripts, there is the help method getDoubleQuote().
#set($doubleQuote=$ScriptHelper.getDoubleQuote()
#set($textWithDoubleQuotes="${doubleQuote}My text with double quotation marks$doubleQuote")
1.2.20 List of numbers from 1 to x
Create a list of numbers from 1 to x as string values. These can then be traversed as in a foreach loop.
1.2.21 Query of the last mailing sent by a client
This call returns a mailing ID.
This can then be used for further purposes, e.g. to resend the mailing or to log the ID somewhere.
#set($lastSentMailingID=$ScriptHelper.getLastSentWorldMailingIDB yCompanyAndMailinglist(companyID, mailingListID))
1.2.22 Creating a line break
Since it is difficult to create a line break in velocity scripts, there is the help method getNewline().
#set($linebreak=$ScriptHelper.getNewline()
#set($textWithLinebreak="My text${linebreak}with line break")
1.2.23 Reading a reference table value
To read a reference table value from a reference table (EMM-Menu → Administration → Manage tables)
#set($myValue=$ScriptHelper.getReferenceValue($referenceTableAli asName, $keyColumnName, $keyValueAsString, $entryColumnName))
1.2.24 Log output to the error log file on the Rdir server
The following expression is used to display the error text:
1.2.25 Write log file
Write a log file named "<companyID_4digit>_<randomvalue>_<fnameValue>" in the VelocityLogDir directory on the EMM/Rdir server.
1.2.26 Calculating the residual value of a division
The following function returns the remainder of a division. So the result of „a mod b“ or „a % b“.
Examples:
„16 mod 5 = 1“
„10 mod 4 = 2“
1.2.27 (Obsolete) Map functions
The functions newHashMap and newHashtable will be removed soon and should not be used anymore.
Instead, use:
1.2.28 Filling or delimiting a text
With the following functions, a text can be limited to a certain length or, if the text is too short, it can be brought to the desired length using spaces.
Example:
#set($shortText="aBc")
#set($longText="abcdefghi")
#set($leftFilledText=$ScriptHelper.padLOrTrim($shortText, 5))
#set($rightFilledText=$ScriptHelper.padROrTrim($longText, 5))
#set($shortenedText=$ScriptHelper.padLOrTrim($longText, 5))
$leftFilledText: " aBc"
$rightFilledText: "aBc "
$shortenedText: "abcde"
1.2.29 Processing a text as a date
With the following function a text can be used as GregorianCalendar.
All Java date format characters are allowed as characters in the DatePattern (dMyHms, see also https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html).
#set($date=$ScriptHelper.parseDate($dateString, "dd.MM.yyyy")) #set($dateTime=$ScriptHelper.parseDate($dateTimeString,
"dd.MM.yyyy HH:mm:ss"))
1.2.30 Validating a Google reCaptcha token
With the following function the token result of a reCaptcha call can be validated before further actions follow (see also https://developers.google.com/recaptcha/docs/verify) ATTENTION: Each reCaptcha token can only be checked once.
Every subsequent check (browser reload, double call in the velocity script, etc.) will result in an error.
Documentation and example available separately from Support.
#set($isValid=$ScriptHelper.validateReCaptcha($apiKey,
$captchaResponseToken))
#if($isValid) ...
#end
1.2.31 Parsing XML data and sending event based mailings
This script action parses an XML construct and then sends an event-based mailing to a mailing list.
Example Code:
## use the mailinglist-id here
#set($ml=6995)
#set($messageList=$ScriptHelper.parseTransactionMailXml($reque stParameters.xml)) #if($messageList)
$Customer.loadCustDBStructure()
#foreach( $message in $messageList )
#set($recipient=$message.recipient)
$Customer.resetCustParameters()
$Customer.setCustomerID(0)
#set($customerID=$Customer.findByKeyColumn("CLIENTNO",
$recipient.get("CLIENTNO").toLowerCase()))
#if($customerID!=0)
#set($bind=$Customer.loadAllListBindings())
#if($bind)
#set($mt=$bind.get($ml))
#if($mt)
#if($mt.get(0).getUserStatus()==1)
#set($params=$ScriptHelper.newHashtable())
$params.put("REVENUE", $recipient.get("REVENUE"))
#set($text="")
#set($link="")
#set($link1="")
#set($content="") #set($loop=$ScriptHelper.getForLoop(99))
#foreach($index in $loop)
#set($line="")
#set($link_part="")
#set($link_part2="")
#set($link_part3="")
#if($recipient.get("DESCRIPTION$index"))
#set($art=$ScriptHelper.padROrTrim($recipient. get("DESCRIPTION$index"),50))
#set($line = "$art
<br>$ScriptHelper.getNewline()")
#set($text="$line")
#set($art_no="")
#set($art_ma="")
#set($art_no=$recipient.get("ARTICLE$index"))
#set($art_ma=$recipient.get("SIZE$index"))
#set($link_part2="&size=$art_ma")
#set($link_part3="&format=cus_formatQ")
#set($link="$link_part$link_part2")
#set($link1="$link_part$link_part3")
#set($content="$content<table width='610' border='0' align='center' cellpadding='2' cellspacing='0' style='border: 1px solid;'><tr><td width='130' class='smalltext'>$art_no</td><td width='*' style='fontfamily:Arial,sans-serif; font-size:10.0pt; color:black;'> $text</td><td width='133'><a
href='http://www.bewerten.de'> Rate </a></td></tr></table>")
#end
#end
$params.put("SURVEY", $content)
$Mailing.setMailingID(106715)
#set($mail=$MailingDao.getMailing(106715, 468))
#if($mail)
$ScriptHelper.sendEventMailing($mail,
$customerID, 0, "1", $params)
#end
#end
#end
#end
#end
#end
#set($scriptResult="1")
#end
1.2.32 Sending email (without existing EMM mailing) within a script
To send a single e-mail, you do not have to create a mailing beforehand. However, this does not create any statistics.
his can be sent within a script action to a specific recipient who does not have to be created as an E-Marketing Manager recipient and therefore does NOT receive a CustomerID or statistics.
The variable "$mailtypeIntLegacy" is for backward compatibility only and has no effect, but must still be specified.
Historically available methods:
## With CC address
$ScriptHelper.sendEmail($from_address, $to_address, $cc_address,
$subject, $body_text, $body_html, $mailtypeIntLegacy, $charset)
## or without CC address
$ScriptHelper.sendEmail($from_address, $to_address, $subject,
$body_text, $body_html, $mailtypeIntLegacy, $charset)
In future, only the following method should be used:
$ScriptHelper.sendEmail($from_address, $to_address, $cc_address,
$subject, $body_text, $body_html, $charset)
1.2.33 Sending of an eventbased mailing within a script
In order to send a single event-based mailing, it must first be created. MailingID (and CompanyID) must be known.
This can then be sent to a specific recipient (CustomerID) within a script action.
The variable "overwrite" can contain a map of values that overwrites the current profile fields of the recipient only for sending the e-mail.
However, these values are not permanently stored in the receiver profile.
#set($mailing=$MailingDao.getMailing($mailingID, $companyID))
#if($mailing)
#set($overwriteParams={})
$overwriteParams.put("firstname",
$recipient.get("firstname")) ## Use the first name of the recipient as the default.
$overwriteParams.put("firstname",
$!requestParameters.firstname) ## Only if another first name is passed as request parameter, use this one
## With UserStatus as list of integer values (without BCC)
$ScriptHelper.sendEventMailing($mailing, $customerID,
$delayMinutes, $userStatusList, $overwriteParams)
## or with UserStatus as a single value in a string
(without BCC)
$ScriptHelper.sendEventMailing($mailing, $customerID,
$delayMinutes, $userStatus, $overwriteParams)
## or with UserStatus as list of integer values and with
BCC address
$ScriptHelper.sendEventMailing($mailing, $customerID,
$delayMinutes, $bccEmails, $userStatusList, $overwriteParams)
## or with UserStatus as single value in a string and with
BCC address
$ScriptHelper.sendEventMailing($mailing, $customerID,
$delayMinutes, $bccEmails, $userStatus, $overwriteParams)
#end
The following receiver status values are possible:
-
1 = Active
-
2 = Bounce
-
3 = AdminOut
-
4 = UserOut
-
5 = WaitForConfirm
-
6 = Blacklisted
-
7 = Suspend / Pending
1.2.34 Creating a SHA-512 hash to a text
Sometimes you need a SHA-512 hash for texts, this can be created as follows:
With default encoding UTF-8:
#set($hashValue=$ScriptHelper.sha512($text))
With special encoding e.g. ISO-8859-1:
#set($hashValue=$ScriptHelper.sha512WithEncoding($text, "ISO-
8859-1"))
1.2.35 Measuring the past time within a velocity script action (debugging)
Up to 10 stop times can be started ($uniqueId from 0 to 9) To start a stopwatch:
To read out the past time in milliseconds on this stopwatch:
1.2.36 Setting a new DatasourceID at the recipient
This can be useful to select a recipient for target groups or to document a processing of the recipient data using a script. $ScriptHelper.updateDatasourceID($recipient)
If there is already an existing DatasourceID greater than 0, the new DatasourceID is written to the profile field "latest_datasource_id".
Attention: Writing to the profile field "latest_datasource_id" can be prevented by the EMarketing Manager configuration value "DontWriteLatestDatasourceId" (technically:
"system.DontWriteLatestDatasourceId").
1.2.37 URL-encoding of text for links
Parameter values for links must not contain some characters, e.g. "=".
These can be replaced by the method urlEncode.
Example:
#set($clearText = "My§=Text")
#set($encodedText = urlEncode($clearText))
Result: encodedText = "My%C2%A7%3DText"
1.2.38 Check / validate e-mail address
Check for correct e-mail address syntax; NO check whether the address really exists.
#if($ScriptHelper.validateEmail($!requestParameters.EMAIL))
## Email address is valid
#else
## Email address is invalid
#end
1.2.39 Create a random value
With ScriptHelper.random(int startvalueInclusive, int startvalueExclusive) you can output a random value. The values in brackets indicate the value range within which the random value must move. The start value is contained in the value range, the end value is outside.
Example: Creating a 4-digit code from "1000" to "9999"
1.2.40 Query value from reference table
With the method ScriptHelper.getReferenceTableValue data from a reference table can be displayed. The following parameters are required for the query:
-
companyId = Company_ID of the client
-
referenceTableName = Name of the reference table (overview, column table)
-
referenceKeyValue = the value that is searched for in the key column
-
referenceColumnName = Column to be output
The complete printout is structured as follows:
ScriptHelper.getReferenceTableValue(int companyId, String referenceTableName, String referenceKeyValue, String referenceColumnName)
Example: Query the phone number of Charles Darwin