Extra Components

There are a number of extra components that ship with the core Barebones CMS product that are not documented anywhere else in the documentation. Many of the components are not even used by Barebones CMS itself.

These components are designed to make certain common tasks on websites easier. Connecting to a MySQL database, running queries, and gathering results, for example, is encapsulated in 'support/mysql.php'. Other common tasks are encapsulated as well - sending and receiving e-mail, setting browser cookies, and web scraping.

Bit Stream Class: 'support/bits.php'

The StreamBitStream class allows a string to be treated as a stream of bits for easy bit-level manipulation. There is currently just 'read' functionality in this class. It is used by the official Barebones CMS Flash Shortcode to analyze Flash objects (SWF files) to determine the optimal width and height of the Flash object.

Example from the Flash Shortcode:

<?php
	...
	require_once ROOT_PATH . "/" . SUPPORT_PATH . "/bits.php";

	$sbs = new StringBitStream;
	$sbs->Init($data);
	$numbits = $sbs->ReadBits(5);
	$x = $sbs->ReadBits($numbits);
	$x2 = $sbs->ReadBits($numbits);
	$y = $sbs->ReadBits($numbits);
	$y2 = $sbs->ReadBits($numbits);

	$info["width"] = (int)(($x2 - $x) / 20);
	$info["height"] = (int)(($y2 - $y) / 20);
	...
?>

StringBitStream::Init($data = "")

Parameters:

Returns: Nothing.

This function initializes a StringBitStream instance with the data that will be used and resets all internal variables.

StringBitStream::ReadBits($numbits, $toint = true, ...)

Parameters:

Returns: An integer if $toint is true, an array otherwise on success. If there are insufficient bits for the request, a boolean of false is returned.

This function reads in the specified number of bits and returns an integer or an array containing those bits.

The array form is an array of arrays where the first element of each subarray is the number of bits and the second element are the extracted bits in integer form. Each subarray contains up to one byte of the stream. The $toint option is a shortcut to calling ConvertBitsToInt() after each ReadBits() call.

StringBitStream::ConvertBitsToInt($data, ...)

Parameters:

Returns: An integer containing the converted array.

This function is intended to be used after a call to ReadBits(). The ReadBits() function uses this function when the $toint option of that function is set to true.

StringBitStream::GetBytePos()

Parameters: None.

Returns: An integer containing the current byte being processed.

This function can be useful to know where in the data stream the byte pointer is at. Usually used in conjunction with the AlignBytes() function. If processing hasn't begun, it will return -1.

StringBitStream::AlignBytes($base, $size)

Parameters:

Returns: Nothing.

This function aligns the byte pointer and resets the bit pointer. For instance, if binary data in a row is DWORD-aligned (4 bytes), then $base could be 0 and $size would be 4 to move the internal byte pointer to the start of the next row once the end of the current row was reached with ReadBits(). Basically, this offers a flushing mechanism.

Browser Cookie Functions: 'support/cookie.php'

This file contains one function for setting browser cookies. The main Barebones CMS login system and editor both use the function to set the login cookie. The built-in PHP setcookie() function is okay, but this offers a couple features over that function.

SetCookieFixDomain($name, $value = "", ...)

Parameters:

Returns: Nothing.

This functions sends a cookie to the browser. To expire a cookie, call the function with $expires set to a low value (e.g. 1). This function corrects $domain issues that are frequently encountered when using cookies.

Cookies are a security issue. Make sure that cookies containing session information use $httponly set to true so that Javascript can't send the session information to a remote server. How Barebones CMS detects a login (so Easy Edit works) is to set a second cookie containing useless information that has $httponly set to false. Javascript detects the second cookie and, by inference, the first cookie is assumed to exist and therefore the 'Edit' link appears in the browser.

HTTP Class: 'support/http.php'

This class is designed to perform the first half of a process known as "web scraping". Web scraping is essentially retrieving content from the web, parsing the content, and extracting whatever data is needed for whatever nefarious purposes the user has in mind. However, I'm not responsible with what you choose to do with this class. The class contains incredibly powerful PHP routines that go far beyond what PHP cURL or file_get_contents() calls typically do is therefore quite easy to create web requests that look exactly like they came from a web browser.

This section of the documentation has moved to the Ultimate Web Scraper Toolkit HTTP class documentation.

Web Browser State Class: 'support/web_browser.php'

The HTTP functions are fine for most purposes. However, they fall short when emulating web browser states such as session cookies, redirects, forms, and other commonly desired features. That is where the Web Browser State class comes in. This class handles cookies, redirects (including relative URL redirects), HTTP 'referer's, and supports enhanced browser emulation for the most common browsers in use.

This section of the documentation has moved to the Ultimate Web Scraper Toolkit WebBrowser classes documentation.

Web Browser Form Class: 'support/web_browser.php'

The web browser form class is specifically designed to manage HTML forms for later submission with the WebBrowser class. $form->info and $form->fields are public arrays that can be read and manipulated but use of the convenient helper functions is highly recommended.

This section of the documentation has moved to the Ultimate Web Scraper Toolkit WebBrowser classes documentation.

WebSocket Class: 'support/websocket.php'

This class provides routines to communicate with a WebSocket server. It has dependencies on the WebBrowser and HTTP classes.

This section of the documentation has moved to the Ultimate Web Scraper Toolkit WebSocket class documentation.

WebSocketServer Class: 'websocket_server.php'

This class provides routines to initialize and run a WebSocket server. It has dependencies on the WebSocket and HTTP classes.

This section of the documentation has moved to the Ultimate Web Scraper Toolkit WebSocketServer class documentation.

POP3 Mail Class: 'support/pop3.php'

This class provides routines to communicate with a POP3 server. There are several uses for these functions - some servers require "POP before SMTP" to send e-mail and these functions meet that requirement. They also for setting an automated script that watches a mailbox for incoming messages and then processes the incoming e-mail as it arrives.

For a working example of how to use the POP3 class, see the Ultimate E-mail Toolkit documentation.

POP3::ProcessSSLOptions(&$options, $key, $host)

Parameters:

Returns: Nothing.

This internal static function processes the "auto_cainfo", "auto_cn_match", and "auto_sni" options for "sslopts" and "proxysslopts" for SSL/TLS context purposes.

POP3::Connect($username, $password, $options = array())

Parameters:

Returns: An array containing the results of the call.

This function connects to a POP3 server using the specified username and password.

The $options array can contain:

While the $options array is optional, the best approach is to be as specific as possible.

POP3::GetMessageList()

Parameters: None.

Returns: An array containing the results of the call.

This function retrieves the list of message IDs and message sizes on the server. This information is returned in key-value ID and size pairs.

POP3::GetMessage($id)

Parameters:

Returns: An array containing the results of the call.

Retrieves a single message from the POP3 server that matches the specified message ID. Message IDs are retrieved with POP3::GetMessageList().

The message is typically processed with the MIMEParser::Parse() function and then text and HTML components are further extracted with the MIMEExtractContent() function.

POP3::DeleteMessage($id)

Parameters:

Returns: An array containing the results of the call.

This function deletes a single message from a POP3 server based on the message ID. Message IDs are retrieved with POP3::GetMessageList().

POP3::Disconnect()

Parameters: None.

Returns: A boolean of true if the instance was successfully disconnected from the POP3 server, false otherwise.

This function disconnects from a POP3 server and performs cleanup for a potential future connection with the same instance.

POP3::POP3Request($command, &$rawsend, &$rawrecv, $multiline = false)

Parameters:

Returns: An array containing the results of the call.

This internal function sends a command to the POP3 server and retrieves the response. Drastically simplifies and improves maintainability of the class.

POP3::GetPOP3Response($multiline)

Parameters:

Returns: An array containing the results of the call.

This internal function retrieves a response from a POP3 server.

MIME Parser Class: 'support/mime_parser.php'

This class supports the POP3 class above by extracting content from retrieved e-mails.

MIMEParser::ConvertFromRFC1341($data)

Parameters:

Returns: A string containing the converted data.

This static function converts RFC 1341 encoded data (also known as "Quoted Printable") into 8-bit clean data. 8-bit data (e.g. UTF-8) has to be converted into 7-bit clean ASCII for transport across the Internet. This reverses the process.

MIMEParser::ConvertFromRFC1342($data)

Parameters:

Returns: A string containing the converted data.

This static function converts RFC 1342 encoded header data into UTF-8 data. 8-bit headers have to be converted into 7-bit clean ASCII for transport across the Internet. This reverses the process.

MIMEParser::ConvertCharset($data, $incharset, $outcharset)

Parameters:

Returns: A string containing the converted data if successful, a boolean of false on failure.

This static function converts a string from one character set to another. Translation is done in the following order of preference: iconv(), mb_convert_encoding(), and then utf8_encode()/utf8_decode().

MIMEParser::ExplodeHeader($data)

Parameters:

Returns: An array containing the parsed MIME header.

This function parses a single MIME header into its component pieces. The first piece's key is an empty string "". The rest are split up by key => value pairs. This function is called by MIMEParse() and MIMEExtractContent().

MIMEParser::Parse($data)

Parameters:

Returns: An array containing the parsed MIME data.

This function parses MIME data into headers, body, and sub-MIME components. It recursively calls itself up to a depth of 10 to parse most MIME content. Do not use the $depth parameter when calling this function (second parameter).

This function is typically used to parse an e-mail message retrieved from a POP3 server. This code also handles non-MIME e-mail content.

MIMEParser::ExtractContent($message)

Parameters:

This function takes the output from MIMEParser::Parse() and extracts "text/plain" and "text/html" components from the message. It recursively calls itself up to a depth of 10 to parse the content. Do not use the $depth parameter when calling this function (second parameter).

This function is typically used to extract just the text and HTML components of a MIME message that have been parsed by MIMEParser::Parse().

SMTP Mail Class: 'support/smtp.php'

This class provides SMTP mail sending functionality and e-mail address correction routines. The mail sending functions directly connect to a SMTP/ESMTP server to send an e-mail and offer more functionality and flexibility than the built-in PHP mail() function.

I'm not responsible with what you choose to do with these functions. These are incredibly powerful PHP routines that go far beyond what PHP mail() calls typically do. It is easy to create e-mails that look exactly like they came from a real e-mail client and will get through spam filters.

Due to spam proliferation across the Internet and the fact that each mail server is set up uniquely makes it nearly impossible to diagnose problems with these functions and YOUR mail server. Note that the included test suite in the Ultimate E-mail Toolkit may help with diagnosing mail sending issues. Other than that, you are on your own and, in the event of problems, you should contact your web/e-mail hosting provider. These functions are a good place to start though and offer significantly more functionality than anything you'll likely need.

Full MIME, Quoted Printable, and binary transfer support.

SMTP::ConvertToRFC1341($data, $restrictmore = false)

Parameters:

Returns: A string containing the converted data.

This static function takes an input string of data and converts it into a RFC1341-compliant string. RFC1341 is a hacky workaround to allow 8-bit data to be transmitted cleanly over 7-bit transports (SMTP is a 7-bit transport) in the body of a message. Also known as Quoted Printable. Typically used for e-mail in Latin-based languages (e.g. U.S. English).

SMTP::ConvertEmailMessageToRFC1341($data, $restrictmore = false)

Parameters:

Returns: A string containing the converted data.

This static function takes an input string of data, converts newlines, and then converts the data into a RFC1341-compliant string. See ConvertToRFC1341() for details.

SMTP::ConvertToRFC1342($data, $lang = "UTF-8", $encodeb64 = true)

Parameters:

Returns: A string containing the converted data.

This static function takes an input string and converts it into a RFC1342-compliant string. RFC1342 is a hacky workaround to allow 8-bit data to be transmitted cleanly over 7-bit transports in an e-mail header. Used primarily to encode the name portion of an e-mail address.

By default Base64 encoding is used but Quoted Printable can be used - $encodeb64 can be set to false - when $lang is "ISO-8859-1" or "US-ASCII".

SMTP::MakeValidEmailAddress($email, $options = array())

Parameters:

Returns: An array containing whether or not conversion was successful, the cleaned up e-mail address, and whether or not the domain passes DNS checks.

This static function takes an input e-mail address of the form 'local@domain', parses it one character at a time using a state engine, cleans it up of common mistakes, and validates that the resulting domain is valid. For example, "someone@hotmail,com" would become "someone@hotmail.com". This function allows all non-obsolete address formats.

This function is not a validation routine but it can be used as such. If it successfully completes, just check the resulting e-mail address ('email') for a match with the original. If they match exactly, then the original is valid. This function, however, is much more desirable for its repairing capabilities. It becomes possible to use AJAX to send a query to the server to determine if the address is valid. Instead of saying, "Invalid e-mail address" to the user, it could say, "Did you mean ...?" with the corrected e-mail address.

The $options array can contain the following options:

Checking for the existence of a SMTP mail server via DNS is a great way to avoid bounced e-mail. DNS checking is done with a slightly modified PEAR::Net_DNS library, which is more versatile than the built-in PHP functions that aren't always available for all platforms.

E-mail validation/clean up is hard. As of this writing, Dominic Sayers has a decent test suite. This function passes most tests with flying colors - everything except obsolete address formats - and even passes most of the tests that are supposed to "fail" because of the repairing capabilities, which only a state engine could accomplish.

SMTP::UpdateDNSTTLCache()

Parameters: None.

Returns: Nothing.

This static function updates the static DNS cache that this class uses for resolving identical domains by removing outdated cache entries (Time-To-Live has expired).

SMTP::GetDNSRecord($domain, $types, $nameservers, $cache = true)

Parameters:

Returns: An array containing the results of the call.

This static function retrieves DNS record information for a specific domain and then optionally caches the results to avoid future DNS requests.

SMTP::EmailAddressesToNamesAndEmail(&$destnames, &$destaddrs, ...)

Parameters:

Returns: A boolean of true if at least one valid e-mail address was successfully processed, false otherwise.

This static function takes a string of '"name" <emailaddr>', 'name <emailaddr>', or 'emailaddr' and extracts each component. Multiple e-mail addresses can be separated with commas (',') [preferred] or semi-colons (';').

This function attempts to deal with malformed strings as best as possible but there are limits as to what it can do. MakeValidEmailAddress() is called for each e-mail address to check its validity.

SMTP::EmailAddressesToEmailHeaders($emailaddrs, $headername, ...)

Parameters:

Returns: A string containing an e-mail header if the e-mail addresses were successfully processed, an empty string otherwise.

This static function generates a valid mail header from one or more e-mail addresses. If $headername is an empty string, e-mail addresses will be returned without a header name.

SMTP::GetUserAgent($type)

Parameters:

Returns: A string containing a valid user agent for the specified e-mail client.

This static function returns a popular user agent string. These aren't always up-to-date but are usually good enough to get the job done on servers that require a user agent and helps to get past most spam filters. If you feel a string is too out of date, post a message to the forums.

SMTP::ProcessSMTPRequest($command, &$code, &$data, &$rawsend, &$rawrecv, $fp, $debug)

Parameters:

Returns: A boolean of true if the $fp socket handle is still successfully connected at the end of the function, false otherwise.

An internal static function to send a command to a SMTP server and extract the response code and data. Correctly handles responses with multiple lines.

SMTP::SMTP_RandomHexString($length)

Parameters:

Returns: A randomly generated string containing hexadecimal letters and numbers (0-9, A-F).

An internal static function to generate a unique string for the 'Message-ID' portion of an e-mail.

SMTP::ProcessSSLOptions(&$options, $key, $host)

Parameters:

Returns: Nothing.

This internal static function processes the "auto_cainfo", "auto_cn_match", and "auto_sni" options for "sslopts" and "proxysslopts" for SSL/TLS context purposes.

SMTP::SendSMTPEmail($toaddr, $fromaddr, $message, $options = array())

Parameters:

Returns: An array containing the results of the call.

This static function sends an e-mail message by directly connecting to a SMTP server. The returned array has a 'success' boolean that can be used to determine success or failure of the call. On failure, 'error' and 'info' are also defined with the technical error message and additional information respectively.

The $options array can contain all the $options for MakeValidEmailAddress() plus:

Some SMTP servers may use the HELO/EHLO 'hostname' option for blocking incoming messages via SPF records.

While it might seem to make sense to connect to the target SMTP server (the "To" address), that isn't how e-mail works. The source SMTP server (the "From" address) is the correct server to connect to. On many web hosts, the mail server is "localhost" but not always.

Some popular web hosts will block SMTP requests made with this function. PHP mail() also tends to not work on such hosts. The host isn't usually specifically blocking sending e-mail via the web server but rather generally blocking until a POP3 login occurs for the same "From" address. This is known as POP before SMTP. To successfully send e-mail in this situation, you should attempt to send an e-mail and, if it fails, then use the POP3 functions to connect to the mail server. Once the POP3 login is successful, attempt to send the same message again over SMTP. If the message is still blocked, then something else is the problem.

SMTP::ConvertHTMLToText_FixWhitespace($data, &$depth)

Parameters:

Returns: A string with whitespace modified/removed.

An internal static function to modify whitespace for a given chunk of data. Used by SMTP::ConvertHTMLToText().

SMTP::ConvertHTMLToText($data)

Parameters:

Returns: A string containing the formatted text version of the HTML.

This static function is intended to be used to generate a text version of a HTML document for sending via e-mail but is versatile enough for most other purposes. The output attempts to create a visually appealing version of the text found within the HTML.

The downside to this particular function is that it is rather slow. As the number of HTML tags increases, the slower this function runs. A complex template can take up to five seconds to parse. On the upside, the output is generally very good.

SMTP::MIME_RandomString($length)

Parameters:

Returns: A string containing alphanumeric characters suitable for MIME encoding.

An internal static function to generate MIME headers for e-mails. Note that the output of this function is not actually random.

SMTP::SendEmail($fromaddr, $toaddr, $subject, $options = array())

Parameters:

Returns: An array of processed information, the result of the mail() command, or the result of SendSMTPEmail() depending on the various $options. The default is to return the result of SendSMTPEmail().

This static function sends an e-mail message or returns processed data intended to be sent via e-mail. In terms of capabilities, this function does it all: E-mail address validation and cleanup, DNS checking, direct SMTP server communication, plain-text and HTML e-mails, MIME, attachments, etc. It does its best to look and smell like an actual e-mail client.

The $options array can contain all the $options for SendSMTPEmail() plus:

The optional 'attachments' array can contain a number of different options:

When specifying an attachment that someone can open, only use 'name'. For inline attachments, such as embedded images, do not use 'name' but use either 'location' or 'cid' instead (avoid using both). Inline images are generally not blocked by e-mail clients. For most web developers who want to use inline images, 'location' is probably the easiest to use but 'cid' is more likely to get through spam filters since that is what most e-mail clients use.

CSPRNG Class: 'support/random.php'

This class provide a CSPRNG to generate user session tokens. These also make up a product with the uncreative name of CSPRNG. See the product's documentation for instructions on use.

CSPRNG::__construct($cryptosafe = false)

Parameters:

Returns: Nothing.

This function selects the best available source available to PHP on the host. If a relevant source is not available, an exception is raised.

CSPRNG::GetBytes($length)

Parameters:

Returns: A string containing the exact number of bytes requested or a boolean of false on failure.

This function retrieves the number of requested bytes from the source selected in the constructor.

CSPRNG::GenerateToken()

Parameters: None.

Returns: A string containing a token (hex encoded) on success or a boolean of false on failure.

This function retrieves a token suitable for a wide variety of uses such as a session token.

CSPRNG::GetInt($min, $max)

Parameters:

Returns: Returns a random integer from $min to $max (inclusive) on success, a boolean of false on failure.

This function returns a random integer. Random integer selection is performed by throwing out integers outside the desired range (the right way) instead of modulus arithmetic (the wrong way).

CSPRNG::GenerateString($size = 32)

Parameters:

Returns: A string containing randomly selected alphanumeric characters.

This function uses CSPRNG::GetInt() to generate a random string with only alphanumeric characters (0-9, A-Z, and a-z). Useful for generating shorter random strings.

CSPRNG::GetMode()

Parameters: None.

Returns: A string containing the current internal mode being used.

This function returns the mode that was selected by the constructor. There are several modes available: "openssl", "mcrypt", and "file".

IP Address Class: 'support/ipaddr.php'

The IPAddr class transforms and matches IP addresses. This class works primarily with IPv6 addresses but will automatically detect IPv4 addresses and patterns and act appropriately. Every IPv4 address has an IPv6 equivalent and all new applications should be built to support IPv6 because it is "the future".

This class also slices, dices, chops, minces, and deals with security vulnerabilities involving IP addresses like you've never seen before! Yes, Virginia, there is a class of security vulnerabilities involving IP addresses.

IPAddr::NormalizeIP($ipaddr)

Parameters:

Retruns: An array containing an IPv6 address, a short version of the IPv6 address, an IPv4 address (or an empty string).

This static function takes an input IP address string and normalizes it to a full IPv6 address. Then it takes that and creates the short IPv6 and IPv4 addresses from that. The result is normalized output that an application can rely upon.

IPAddr::GetRemoteIP($proxies = array())

Parameters:

Returns: A normalized remote IP address.

This static function takes the usual $_SERVER["REMOTE_ADDR"] IP address and normalizes it. If any trusted proxies are specified, any relevant "HTTP_X_FORWARDED_FOR" and "HTTP_CLIENT_IP" headers are analyzed looking for the real remote IP address, stopping at the first untrusted proxy. Valid HTTP header types for $proxies are "xforward" and "clientip".

IPAddr::IsMatch($pattern, $ipaddr)

Parameters:

Returns: A boolean of true if the IP address matches the pattern, false otherwise.

This static function normalizes the IP address if it isn't already normalized and then attempts to match the input pattern against the address. The pattern must contain the correct number of ':' (colon) or '.' (dot) characters corresponding to an IPv6 or IPv4 address respectively. Special characters may be used within each segment of the pattern:

IPv6 segments can also contain IPv4-style notation, but it looks a little weird (e.g. '*:*:*:*:*:*:127.0:0.1' notice the colon).

© CubicleSoft