HSL core functions

From Halon Security
(Redirected from HSL Core Functions)
Jump to: navigation, search

These functions are always accessible when writing HSL code, since they are built-in. Additional functions are only available when executed in a specific context. A function is invoked, possibly with arguments, doing what it is supposed to do, and possibly returning a value. Although many function names and constructions are the same as in Perl, PHP, C and other languages, keep in mind that HSL is not related to any of those, and therefore rely on this documentation for their usage.

Contents

Example

The code below demonstrates the execution of a function (uuid, returning a unique id) in multiple ways.

$variable uuid();
echo 
uuid();
echo (
uuid() == "test"); 

In the example above;

List of core functions

The functions listed below can be referred to in any context, since they are built into HSL. The arguments of the functions are listed as variables ($variable), but can be expressions as well.

Network Functions

Functions returning or operating on IP-addresses and Hostnames or making various network requests.

http($url, $timeout = 15, array($get_params...), array($post_params...) or $post_data)

→ String

Returns the content of the response from the HTTP request (headers not included), upon failure an empty string is returned. The $url parameter should contain a the URL, this URL will not be escaped before the request, therefore it's possible to pass more parameters that will be escaped before they are included in the URL, they are referred to using $1, $2... (for each parameter). The concept should be that all values of a query string should be specified as a included parameter.

With this functions it's possible to build external applications which may interact with the SPG; for example a black and white list.

switch(http("http://test.example.org/check_bwlist.cgi?mail=$1&ip=$2"10, array($sender$senderip)))
{
 case 
"blacklist"Delete(); break;
 case 
"whitelist"Deliver(); break;

smtp_lookup_rcpt($mailtransport or $settings, $sender, $recipient, $options)

→ Number

Lookup if sender is allowed to send to recipient using the mailtransport profile specified. It will basically try to send the message but abort after the recipient is checked, if the session were successful, it will return 1, if the recipient was rejected it will return 0, and for any other (unexpected) error -1 will be returned.

Result Description
1 SMTP Recipient OK
0 SMTP Recipient Failed
-1 SMTP failure

If you instead of a mailtransport profile specified a array. The following parameters may be specified.

Name Default Parameter
host no default Host
port 25 Port
sourceip auto Source IP (advanced)
sasl_user empty SASL Username
sasl_pass empty SASL Password
tls disabled TLS settings (disabled, optional, optional_verify, require, require_verify)

If you specified a option array. The following parameters may be defined.

Name Default Parameter
error_code false Return a array instead of integer (error_message, error_code)
switch(smtp_lookup_rcpt("mailtransport:1"$sender$recipient))
{
 case 
1:
  echo 
"smtp_lookup_rcpt OK";
 break;
 case 
0:
  echo 
"smtp_lookup_rcpt FAILED";
 break;
 case -
1:
  echo 
"RCPT Unexpected Error";
 break;
}

echo 
smtp_lookup_rcpt(
                      array(
                            
"host"=>"mx1.example.com",
                            
"port"=>25,
                            
"helo"=>"mail.example.org"
                      
),
                      
$sender,
                      
$recipient,
                      array(
"error_code"=>true)
          ); 

smtp_lookup_auth($mailtransport or $settings, $username, $password)

→ Number

Lookup if sender is allowed to send to authenticate using the mailtransport profile specified. It will basically try to authenticate, if the session were successful, it will return 1, if the recipient was rejected it will return 0, and for any other (unexpected) error -1 will be returned.

Result Description
1 SMTP authentication was successful
0 SMTP authentication failed
-1 SMTP failure

If you instead of a mailtransport profile specified a array. The following parameters may be specified.

Name Default Parameter
host no default Host
port 25 Port
sourceip auto Source IP (advanced)
sasl_user empty SASL Username
sasl_pass empty SASL Password
tls disabled TLS settings (disabled, optional, optional_verify, require, require_verify)
switch(smtp_lookup_auth("mailtransport:1"$saslusername$saslpassword))
{
 case 
1:
  echo 
"smtp_lookup_auth OK";
 break;
 case 
0:
  echo 
"smtp_lookup_auth FAILED";
 break;
 case -
1:
  echo 
"SMTP AUTH Unexpected Error";
 break;

ldap_search($ldapprofile, $lookup, $override)

→ Array

Searches for $lookup (eg. $recipient) in $ldapprofile (eg. "ldap:1") and returnes all LDAP Entires found. You may override some parameters from the configured LDAP profile by passing an array().

Result Description
Array() of result Entries found in LDAP
-1 LDAP failure
Name Parameter
host Host
username Username (DN)
password Password
base Search Base (DN)
query Search Query


switch($result=ldap_search("ldap:1"$recipient, array("username"=>"test""password"=>"test"))
{
 case -
1:
  echo 
"LDAP Failure";
 break;
 default:
  if (
count($result))
  {
   echo 
count($result)+" results found";
  } else {
   echo 
"no results found";
  }
 break;

ldap_bind($ldapprofile, $username, $password, $override)

→ Array

Tries to bind ot a LDAP profile using username and password. This should be used for LDAP authentication.

Result Description
1 Successfull Bind
0 Bind Failed
-1 LDAP failure
Name Parameter
host Host
username Username (DN)
password Password
base Search Base (DN)
query Search Query


switch(ldap_bind("ldap:1""username""password"))
{
 case 
1:
  echo 
"Authentication OK";
 break;
 case 
0:
  echo 
"Authentication Failed";
 break;
 case -
1:
  echo 
"LDAP Failure";
 break;

in_network($ip, $network)

→ Boolean

Returns true if $ip is in the $network. The network parameter may be specified in the following formats; IP, IP/BITMASK or as an IP-IP range. This function supports both IPv4 and IPv6. If you try to match against wrong IP-family it will just return false.

$ip "192.168.1.23";

// will print (true) 1
echo in_network($ip"192.168.1.23");

// will print (true) 1
echo in_network($ip"192.168.1.0/24");

// will print (true) 1
echo in_network($ip"192.168.1.20-192.168.1.50"); 

dns($hostname, $dns_servers, $timeout = 5)

dns4($hostname, $dns_servers, $timeout = 5)

dns6($hostname, $dns_servers, $timeout = 5)

→ Array of String

Return an array of IP numbers that the $hostname resolved to. $dns_servers is optional and should an array of DNS servers to query, this is just in case if you don't want to use system defaults. Default timeout is 5 seconds.

// will print the ("ip-address", "ip-address", ..)
echo dns("example.com");
// Will query, using default dns_servers with a 5 second timeout.
echo dns("example.com", array(), 15); 

dnsmx($hostname, $dns_servers, $timeout = 5)

→ Array of String

Return an array of addresses that the $hostname announced as MX for it's domain. $dns_servers is optional and should an array of DNS servers to query, this is just in case if you don't want to use system defaults. Default timeout is 5 seconds.

// will print the ("mx.example.org", ..)
echo dnsmx("example.com");

// Will query, using default dns_servers with a 5 second timeout.
echo dnsmx("example.com", array(), 5); 

dnsptr($ip, $dns_servers, $timeout = 5)

→ Array of String

Return an array of Hostnames that the $ip resolved to. $dns_servers is optional and should an array of DNS servers to query, this is just in case if you don't want to use system defaults. Default timeout is 5 seconds.

echo dns("212.37.18.222");

// Will query, using default dns_servers with a 5 second timeout.
echo dns("212.37.18.222", array(), 5); 

dnstxt($hostname, $dns_servers, $timeout = 5)

→ Array of String

Return an array of the TXT fields for a domain name that the $hostname resolved to. $dns_servers is optional and should an array of DNS servers to query, this is just in case if you don't want to use system defaults. Default timeout is 5 seconds.

echo dnstxt("example.com"); 

dnsbl($ip, $zone, $dns_servers, $timeout = 5)

→ Array of String

Return an array of IP numbers returned by the DNSBL lookup, $dns_servers is optional and should an array of DNS servers to query, this is just in case if you don't want to use system defaults. Default timeout is 5 seconds.

if (count(dnsbl($senderip,"zen.spamhaus.org")) > 0) echo "Listed in Spamhaus"

spf($senderip, $senderhelo, $sender)

→ Number

SPF lookup; check if the combination of senderip, senderhelo and sender is valid according to the SPF record specified for the sending domain.

Result Description
0 Genuine (Pass)
20 Softfail (Suspected)
50 Unknown (Neutral)
100 Fail (Spam)

This module affects the $result variable.

switch(spf($senderip$senderhelo$sender))
{
 case 
100:
  
Delete();
 break;
 case 
0:
  
Deliver();
 break;

globalview($ip)

→ String

Return the result of the GlobalView module. The GlobalView modules returns different action which can be "accept", "tempfail" or "permfail".

switch(globalview($senderip)) {
  case 
"accept":
   
Allow();
  break;
  case 
"tempfail":
   echo 
"Connection from $senderip allowed by GlobalView (tempfail)";
   
Allow();
  break;
  case 
"permfail":
   echo 
"Connection from $senderip blocked by GlobalView (permfail)";
   
Block();
  break;

If license is missing it returns "accept". This section only defines how the interface against GlobalView work, not the GlobalView module itself. If you want to use tempfail also include a case for "tempfail".

Mail Functions

mail($sender, $recipient, $subject, $body, $options)

→ String

Send an mail from within HSL; the message will be put in the outgoing queue. This function will return the message ID on success regardless of the delivery status.

mail("postmaster@example.org""support@halon.se""Lunch""How about lunch on Friday?"); 

You may also specify an associative array of options.

Name Default Parameter
serverid no default Helps the decision making of where we should send this email.
sender_name empty Friendly name of the sender (Postmaster)
recipient_name empty Friendly name of the recipient (Support Crew)
template internal/en_EN Language of the template files
plaintext false Send message as text/plain

BATV

Bounce Address Tag Validation can be used to prevent backscatter from servers not verifying your SPF record (or DKIM enforcement) for forged messages.

batv_sign($sender, $key, $options)

→ String

Signs the $sender address parameter with the specified $key. As options the following parameters can be specified.

Name Default Parameter
keyid 0 Key id (0-9)
days 7 Days the tag should be valid
SetSender(batv_sign($sender"my secret key", array("keyid" => 1)); 

batv_verify($sender, $keys, $options)

→ String

Verifies the $sender address parameter with any of the available $keys. As options the following parameters can be specified.

Name Default Parameter
days 7 Days the tag should is valid

The following return values may be returned

Value Type Reason
"pass" Good The BATV tag is valid! Message should be batv_stripped and delivered.
"missing" Neutral No BATV tag
"invalid" Bad BATV tag is invalid
"checksum" Bad BATV tag is bad (invalid key)
"expired" Bad BATV tag has expired
// Verify BATV signature in Recipient Flow
if ($sender == "" and batv_verify($recipient, array(=> "my secret key")) != "pass")
{
 
Reject("Invalid Bounce");

batv_strip($sender)

→ String

Removes the BATV tag from the e-mail address. If not tagged, $sender will be returned.

echo batv_strip("prvs=1212af4dsa=test@example.org"); // echo test@example.org
echo batv_strip("test@example.org"); // echo test@example.org

SetRecipient(batv_strip($recipient)); // Strip BATV signature in Content Flow before delivery 

minger_lookup($host, $address, $options)

→ Number

Minger is a recipient lookup protocol (specified in a [draft-hathcock-minger-06]), very much like RCPT TO/VRFY and LDAP, but it aims to be simple and fast by using UDP. Alt-N's MDaemon (draft author) and others has adopted this draft. Advantages over smtp_lookup_rcpt could be that you do not populate your SMTP logs with recipient lookups from mail filters and that it's faster, advantages over LDAP could be that it's simpler to implement both server and client side with less parameters.

Since the protocol is only defined as a draft with some disputed weaknesses like bad choice of password protection method (should use HMAC SHA1 instead of SHA1) and bad error codes ("5" equals success, instead of proposed "0") you must specify "draft" => 6 as a option. This requirement will be removed when and if it becomes an RFC and the protocol is stable.

The following options are available.

Option Default Description
"draft" no default This value must be "6" to represent draft-hathcock-minger-06
"secret" "" No secret is used by default.
"port" 4069 UDP Port
"timeout" 10 Default query timeout

The following return values are available.

Value Type Description
-1 Bad Protocol error (eg. timeout)
0 Bad Invalid request (for example, malformed query string)
1 Bad Access denied (for example, query from unauthorized IP)
2 Bad Bad or missing credentials (returned when anonymous mode is disabled and no credentials were provided in the query string or when the credentials themselves are invalid)
3 Bad Email address does not exist
4 Bad Email address exists but can not receive mail (for example, the account associated with the email address has exceeded local storage constraints or it is otherwise disabled due to local policy)
5 Good Email address exists and is active (able to receive mail)
switch (cache ["ttl" => 86400"ttl_override" => array(-=> 60), "size"=> 16384]
 
minger_lookup("10.1.0.20"$recipient, array("draft" => 6)))
{
 case 
5:
  
Accept();
 break;
 case -
1:
  
Defer(); // Query error (eg timeout)
 
break;
 default:
  
Reject();
 break;

String (Text) Functions

These functions are operating on strings (text), having strings as input arguments. Information about how to combine strings can be found on the operators page.

substr($text, $start, $stop)

→ String

Returns a part of a string, starting from $start and stopping at the optional argument $stop.

// will print "est"
echo substr("test"1); 

strlen($text)

→ Number

Returns the number of characters in the string $text.

// will print 4
echo strlen("test"); 

strpos($text, $find, $startat)

→ Number

Returns the index number of the first occurrence of the string $find in the string $text, possibly restricting the search to begin the examination at the optional index number $startat. If $find was not found in $text, -1 is returned.

// will print 0
echo strpos("test test""te");
// will print 5
echo strpos("test test""te"1); 

strrpos($text, $find, $startat)

→ Number

Returns the index number of the last occurrence of the string $find in the string $text, possibly restricting the search to end the examination at the optional index number $startat. If $find was not found in $text, -1 is returned.

// will print 0
echo strpos("test test""te");
// will print 5
echo strpos("test test""te"1);

// will print halonsecurity.com
$mail "support@halonsecurity.com";
echo 
substr($mail,strpos($mail,"@")+1); 

strtolower($text)

→ String

Return the lower-case representation of $text.

// will print "test"
echo strtolower("Test"); 

strtoupper($text)

→ String

Return the upper-case representation of $text.

// will print "TEST"
echo strtoupper("Test"); 

str_replace($replace, $with, $intext)

→ String

Returns the string $intext after all occurrences of the string $replace has been replaced with $with.

// will print "this is an ice cream"
echo str_replace("apple""ice cream""this is an apple"); 

str_repeat($text, $repeat)

→ String

Returns the string $text, repeated $repeat times.

// will print "test test "
echo str_repeat("test "2); 

chr($asciinum)

→ String

Returns the ascii-character as a string, use an ascii table to look up possible values.

echo "Hello"+chr(32)+"World"

pcre_match($pattern, $input)

→ Array of Strings

Perl compatible regular expression data matching and extraction, requires capture groups. Empty results return an empty array(). For pure matching use =~ (which is implemented much faster). All modifiers supported by =~ are available.

echo pcre_match("/(.*?)/""foo");
// greedy by default
// [0=>"f",1=>"f"]

echo pcre_match("/(.*?)/U""foo");
// ungreedy by modifier U
// [0=>"foo",1=>"foo"]

echo pcre_match_all(
    
"/(<([\\w]+)[^>]*>)(.*?)(<\\/\\2>)/",
    
"This <b>text</b> contains <a href=howdy.html>tags</a>.");
/*
[0=>
 [
  0=>"<b>text</b>",
  1=>"<a href=howdy.html>links</a>"
 ],
 1=>
 [
  0=>"<b>",
  1=>"<a href=howdy.html>"
 ],
 2=>
 [
  0=>"b",
  1=>"a"
 ],
 3=>
 [
  0=>"text",
  1=>"tags"
 ],
 4=>[
  0=>"</b>",
  1=>"</a>"
 ]
]
*/ 

pcre_match_all($pattern, $input)

→ Array of Array of Strings

Returns multiple results grouped by capture groups, and matched result. Otherwise similar to pcre_match().

Array Functions

These functions operate on, or return, arrays. Information about how to add items to an array can be found on the operators page.

array($variable1, $variable2, ...)

→ Array

Returns an array containing the variables (or expressions) requested in the arguments. This function is a "special" function, in the sense that it has an alternative way of specifying named parameters. Note that the syntax of square brackets are accepted as well.

$var = array("fruit"=>array("apple","banana","orange"),"hello","world"=>"!"); 
$var = ["fruit"=>["apple","banana","orange"],"hello","world"=>"!"]; 

Result

["fruit"=>[0=>"apple",1=>"banana",2=>"orange"],0=>"hello","world"=>"!"]

in_array($lookfor, $inarray)

→ Boolean

Returns true (1) if $lookfor was found at any position in $inarray.

$array = array("a""b");
// will print 0
echo in_array("c"$array); 

is_array($array)

→ Boolean

Returns true (1) if $array is an array.

$array = array("a""b");
// will print 1
echo in_array($array); 

array_keys($array)

→ Array of Values

Return the keys of an array.

$array = array("a""b""c" => "d");
// will return and array of array(0,1,"c");
echo array_keys($array); 

array_reverse($array)

→ Array of Values

Return the array reversed (numberic indexes are reindexed).

$array array_reverse(array(123"c" => "d"));
// will return and array of array("c"=>"d", 0=>3, 1=>2, 2=>3);
echo $array

count($array)

→ Number

Returns the number of items in $array.

$array = array("a""b");
// will print 2
echo count($array); 

range($start, $stop, $step)

→ Array of Number

Returns an array with number between $start and $stop, possibly with the stepping defined by the optional parameter $step.

// will contain 10, 12, 14, 16, 18 and 20
$array range(10202); 

explode($delimiter, $string)

→ Array of String

Splits up a string on a delimiter (string)

// will contain "a", "b" and "cd"
$array explode("-""a-b-cd"); 

implode($glue, $string)

→ Array of String

Concatenates a string using the $glue

// Prints "I...like...pancakes"
echo implode("...",explode(" ","I like pancakes")); 

Arithmetic (Math) Functions

Functions returning or operating on numbers.

round($number, $precision)

→ Number

Rounds the $number with $precision decimals.

$number 3.14159265;
// will print 3.142
echo round($number3); 

floor($number, $precision)

→ Number

Returns the $number rounded down with $precision decimal. If no precision is specified it will round down to the next integer.

$number 3.9
// will print 3
echo floor($number); 

ceil($number, $precision)

→ Number

Returns the $number rounded up with $precision decimal. If no precision is specified it will round up to the next integer.

$number 3.14159265;
// will print 4
echo ceil($number); 

rand($low, $high)

→ Number

Return a random integer number, between the integer values $low and $high

// will print a number between 10 and 20
echo rand(1020); 

sqrt($number)

→ Number

Return the square root of $number

// will print 3.16
echo sqrt(10); 

Time and Date Functions

Functions used to work with time and date in HSL.

strftime($format)

→ String

This functions converts the current time into a String using the format pattern. The length of the returned string is truncated to 100 characters. For a complete reference manual of strftime read the strftime manual.

// Show Time
echo strftime("%H:%M:%S"); // prints current time eg "13:58:38"

// Execute code between 08:00 and 16:59
$time number(strftime("%H"));
if (
$time >= and $time <= 16)
{   
    echo 
"Working time";

Cryptographic Functions

Functions that may be used in a cryptographic context.

md5($text)

→ String

Returns the MD5 Hash of $text.

sha1($text)

→ String

Returns the SHA1 Hash of $text.

hmac_md5($text, $key)

→ String

Returns the HMACMD5 Hash of $text and $key.

hmac_sha1($text, $key)

→ String

Returns the HMACSHA1 Hash of $text and $key.

base64_encode($text)

→ String

Return the $text Base64 encoded.

base64_decode($text)

→ String

Return the $text Base64 decoded.

Authentication Functions

Functions that may be used in a authentication/authorisation context.

tacplus_authen($options, $username, $password)

→ Number

Authenticating $username / $password against a TACACS+ server (eg. Cisco Secure ACS).

Result Description
1 Authentication Successful
0 Authentication Failed
-1 Authentication Error

The following options are available

Name Default Parameter
host no default Host
secret no default Shared secret
clientip empty Client IP to report
port 49 Port
timeout 5 Timeout in seconds

More examples are available in the System Authentication documentation.

$hostopt = [
   
"host"=>"10.0.0.31",
   
"secret"=>"mysharedsecret",
   
"clientip" => $clientip
  
];
if (
tacplus_authen($hostopt$username$password) == true)
{
 
$ret tacplus_author($hostopt$username, ["service=admin"]);
 if (
is_array($ret) and in_array("halon=test"$ret))
 {
  
Authenticate(["fullname"=>"TACACS+ User"]);
 }

tacplus_author($options, $username, $avparis)

→ Number or Array of strings

Return the authorisation result for $username as a string of pairs from a TACACS+ server (eg. Cisco Secure ACS).

Result Description
Array Authentication Successful
0 Authentication Failed
-1 Authentication Error

The following options are available

Name Default Parameter
host no default Host
secret no default Shared secret
clientip empty Client IP to report
port 49 Port
timeout 5 Timeout in seconds

More examples are available in the System Authentication documentation.

$hostopt = [
   
"host"=>"10.0.0.31",
   
"secret"=>"mysharedsecret",
   
"clientip" => $clientip
  
];
if (
tacplus_authen($hostopt$username$password) == true)
{
 
$ret tacplus_author($hostopt$username, ["service=admin"]);
 if (
is_array($ret) and in_array("halon=test"$ret))
 {
  
Authenticate(["fullname"=>"TACACS+ User"]);
 }

radius_authen($options, $username, $password, $vendorstrings)

→ Number or Array of strings

Return the authentication/authorization result for $username / $password as an array of vendor strings (an empty array should be considered a successful authentication) from a RADIUS server (eg. Cisco Secure ACS). Vendor strings must be strings and must be registered as ID 33234 (Halon Security's Enterprise Number).

Result Description
Array Authentication Successful
0 Authentication Failed
-1 Authentication Error

The following options are available

Name Default Parameter
host no default Host
secret no default Shared secret
clientip empty Client IP to report
port 1812 Port
timeout 5 Timeout in seconds
retry 3 Number of retries

More examples are available in the System Authentication documentation.

$ret radius_authen(
  [
   
"host"=>"10.0.0.33",
   
"secret"=>"mysharedsecret",
   
"clientip" => $clientip
  
], $username$password);
if (
is_array($ret))
{
 
Authenticate(["fullname"=>"Radius User"]);

or with vendor strings

$ret radius_authen(
  [
   
"host"=>"10.0.0.33",
   
"secret"=>"mysharedsecret",
   
"clientip" => $clientip
  
], $username$password, [1=>"knock"]);
if (
is_array($ret) and $ret[1] == "admin")
{
 
Authenticate(["fullname"=>"Radius User"]);

System Functions

Functions that use system parameters as basis of their results.

uuid()

→ String

Return a unique ID, based, on time and other system parameters.

// will print something like 247c7e61-0a06-11dd-85d8-000c29beac
echo uuid() 
if (uuid() == uuid())
{
 echo 
"This statement cannot be true";

executiontime()

→ Number

Returns the total number of seconds the code has been executing. In many contexts "code" can be interpreted as single message/recipient processing.

sleep(5);
echo 
executiontime(); // 5.01 (some minor overhead is expected)
sleep(3);
echo 
executiontime(); // 8.01 (some minor overhead is expected) 

In a Mail Content Flow, it may be used as this (not very useful example)

if (ScanSA() > 5)
{
 echo 
"I found a spam and it took " executiontime() + " seconds";

sleep($seconds, $microseconds)

→ Number

Delays the script execution for the given number of seconds. Returns the number of seconds the code has been executing. In a mail context this function can be used to implement [SMTP tarpitting] as in this tarpitting example.

echo strftime("%H:%M:%S"); // 10:50:31
sleep(5);
echo 
strftime("%H:%M:%S"); // 10:50:36 

serial()

→ Number

Return the unit assigned serial number ("System Serial"). This can be useful to choose different code paths depending on which unit in a "shared" configuration. It's not recommended to be used as an raw identifier which is visible to the user in any way, the less he know about your system - the better.

$unit = array(20001234=>"unit 1"20001235=>"unit2");

echo 
$unit[serial()]); 

rate($namespace, $entry, $count, $interval)

→ Boolean or Number

This functions count the number of executions for the unique relation with $namespace and $entry. If $count is exceeded for the specified $interval (in seconds), it will return 0 (false) else return (true).

If $count is 0 (false) it will not increase the internal counter, instead return the current value of the internal counter.

if (rate("outbound"$saslusername360) == false)
{
 
Reject("User is only allowed to send 3 messages per minute");

isset($variable)

→ Boolean

Returns 1 (true) or 0 (false) whether or not a variable is defined or not. This function is not a pure-function and behaves more like a language construct.

if (!isset($var))
 
$var "Hej";
echo 
$var

get_defined_functions()

→ Multidimensional Array of String

Returns two sets of arrays "internal" and "user", containing all defined functions.

echo get_defined_functions(); // array("internal"=>array(...), "user"=>...) 

File Functions

Functions returning or operating on files in the HSL. A file can either reside on the FTP storage, and is addressed as file://path_to_file.txt or in the File Store (file:id) where id (numeric) is visible in the web administration or configuration.

in_file($needle, $file, $delimiter or $options = array())

→ Array of String

Searches for $needle as the first word on each line in $file, if found all words on that line will be returned as an array of strings. If not found, an empty array will be returned. The $file parameter should point to a file.

Parameter Default Default for "text/csv" Description
type "text/plain" "text/csv" If you specify type "text/csv", some default values changes. Warning: if text/csv, the first row is used as column names.
delimiter " " "," Word-delimiter to use.
assoc n/a true If type is text/csv, return the result as an associative array based on column name.
index 0 0 Word-index to search for (needle). The word counter starts at 0.

Example #1

This example is for a "rewrite table", this table will let you change the recipient by looking it up in a file.

File located on the ftp://192.168.0.1/rewrite_table.txt

current_recipient new_recipient optional_new_transport
test@example.org user@example.org
demo@example.org user@example.org mailtransport:2

Script using the rewrite_table.

switch(count($data=in_file($recipient"file://rewrite_table.txt")))
{
    case 
2:
        echo 
"BCC to user " $data[1];
        
CopyMail($data[1], "mailtransport:1");
        
Delete();
    break;
    case 
3:
        echo 
"BCC to user " $data[1] + " using transport " $data[2];
        
CopyMail($data[1], $data[2]);
        
Delete();
    break;

Example #2

This example is for a "white list" using a file on the FTP.

File located on the ftp://192.168.0.1/whitelist.txt

domain or e-mail address
example.org
test@example.com

Script using the white list.

if (in_file($senderdomain"file://whitelist.txt") or in_file($sender"file://whitelist.txt")) {
 
Deliver();

Example #3

This example is for a mail "distribution list" using a file on the FTP. One might argue if this is something that should be implemented in a Spam Gateway :)

File located on the ftp://192.168.0.1/distribution.txt

trigger-address user1 user2 user3...
trigger-mail@example.org user1@example.org user2@example.com user3@example.net

Script using the distribution list.

if (count($multiply in_file($recipientdomain"file://distribution.txt")) > 0)
 foreach(
$multiply as $user)
 {
  
CopyMail($user"mailtransport:1");
 }
 
Delete();

file($file)

→ Array of String

Reads a file an returns the files rows as an array of strings. The $file parameter should point to a file.

Example

foreach(file("file://list.txt") as $row)
{
 echo 
$row;

file_get_contents($file)

→ String

Reads a entire file into a string. The $file parameter should point to a file.

Example

echo file_get_contents("file://list.txt"); 
Personal tools
Namespaces
Variants
Actions
Navigation
Products
Toolbox