Global Functions

While creating a website with Barebones CMS, it may eventually be required to introduce new functionality. Most of the key functionality of Barebones CMS is encapsulated inside a set of common functions. This documentation covers how to develop software that uses these functions and some guidelines on how to create function names that will not conflict with other components. As many developers mix and mingle together, there is increased risk of creating conflicts.

All Barebones CMS functions start with the prefix 'BB_'. This prefix is reserved exclusively for the main Barebones CMS product. Community members will give you an online beating if you violate this rule.

Widgets and Shortcodes usually don't require external functions outside of the main class. However, Plugins are function-oriented. The easiest way to avoid a conflict is to prefix your function names with the directory/file/class name. Whatever name makes the new functionality unique and very unlikely to conflict with anything else.

This documentation is presented in Execution Path order.

Core Functions: 'main.php'

These functions are introduced when the caching system runs. They are of limited use to most Widgets, Shortcodes, and Plugins but are used by both 'main.php' and 'proc.php'.

BB_GetInitClientLangMap($lang)

Parameters:

Returns: A string containing language mapping in $bb_page. Returns false if a suitable mapping can't be found for the requested language.

Typically called by BB_GetInitClientLang(), which selects the default language mapping if nothing else matches.

BB_GetInitClientLang()

Parameters: None

Returns: A string containing the language to load.

This is used to select the value for $bb_pref_lang. The selection come from either $_REQUEST["lang"] or the HTTP Accept-Language header (sent by the browser). Calls BB_GetInitClientLangMap() to determine if an appropriate language mapping exists. If no mapping can be found, the default language for the page is returned.

Core Functions: 'proc.php'

These functions are introduced when the main page processor script is loaded.

BB_CreatePHPStorageData($data)

Parameters:

Returns: A string that is ready to be stored in a .php file assigned to a variable.

This function prepares variables to save them to a file. It uses the USE_LESS_SAFE_STORAGE configuration item to determine how to generate the data. When less safe storage is disabled, data is serialized and then base64 encoded. When less safe storage is enabled, data is var_export()'ed. Both methods perform about the same but the latter is slightly less secure but readability is vastly improved.

BB_SavePage()

Parameters: None

Returns: A boolean value of true if successful, false otherwise.

Saves $bb_page to its language-independent file. To save the language-dependent variable $bb_langpage, where widget configurations are stored, use BB_SaveLangPage(). This function is used mostly to update last-cached information.

BB_InitWidget()

Parameters: None

Returns: Nothing.

An internal function used to initialize a widget instance. Do not call this function.

BB_ProcessMasterWidget($name, $displaymwm = true)

Parameters:

Returns: Nothing.

Processes an active master widget. Used mostly by BB_ProcessPage() and the Layout widget.

When inside the editor, this function also calls BB_MasterWidgetPreWidget() and BB_MasterWidgetManager().

If $displaymwm is false, then BB_MasterWidgetManager() is not called for the master widget and widgets inside the master widget can't be detached or deleted. This is used by the Layout widget for master widgets that will contain one specific widget.

BB_ProcessPage($retcache, $dumpcache, $easyedit)

Parameters:

Returns: An empty string if $retcache is 'false', otherwise returns a string containing the generated page data.

This is the main workhorse of the CMS. It sets $bb_mode to one of 'prehtml', 'head', 'body', or 'foot' and calls BB_ProcessMasterWidget("root"). Widgets generally call this function if they want to display the page after processing a form in their ProcessAction() function.

If $retcache is 'false', then $dumpcache is ignored.

Easy Edit is the nifty 'Edit' link in the upper-right corner of the page. The only place that this should ever be set to 'false' is inside the main editor preview frame. That is, if you call this function, use 'true'. If Easy Edit is disabled in the configuration for the page, it won't show.

When $bb_mode is 'head', the global variables $bb_css, $bb_js, and $bb_premainjs are initialized. During the processing of the root master widget, these variables can be modified to output relevant content into the HTML 'head' tag.

Core Functions: 'edit.php'

These functions are introduced when the main editor loads.

BB_AddPluginAction($name, $callback, $priority = 10)

Parameters:

Returns: A boolean value of 'true' if the hook was added, 'false' otherwise.

This is used to register a hook within the Barebones CMS editor. Hooks are only valid within the editor and are designed mostly for Plugins to extend the core functionality of the Barebones CMS.

A plugin can also register for all hooks globally by specifying "global_action" to receive callbacks for BB_RunPluginAction() calls and "global_action_info" to receive callbacks for BB_RunPluginActionInfo().

BB_RunPluginAction($name)

Parameters:

Returns: Nothing.

This is used for notification-only hooks that lets registered callbacks know that a specific state during page processing has been reached. The $name parameter is the same as the parameter used in a BB_AddPluginAction() call.

Global hooks with "global_action" are also called.

BB_RunPluginActionInfo($name, &$info)

Parameters:

Returns: Nothing.

This is used for data processing hooks that lets registered callbacks know that a specific state during page processing has been reached and usually lets the callback modify some information. The $name parameter is the same as the parameter used in a BB_AddPluginAction() call. The $info parameter varies depending on the hook.

Global hooks with "global_action_info" are also called.

BB_CreateSecurityToken($bbaction, $wid = "", $extra = "")

Parameters:

Returns: A string containing a security token.

This function is used extensively throughout the main editor to generate security tokens to defend against CSRF attacks (the correct phrase is 'security nonce' but the word 'nonce' has inappropriate connotations). Every action, except 'bb_main_edit', requires a valid security token or an "Invalid security token." message will be displayed.

A security token is based on a mixture of random data plus some regular data and is on a per-session, per-language-specific page, per-hyperlink/form basis. A would-be hacker will find this defense to be very difficult to get around. It would be simpler to attempt to find the login screen or brute-force a login session.

The $extra parameter is used for creating an even more secure token based on parameters the target routine is expecting to exist. Basically, this feature is overkill. If used, the $extra parameter should be an array of values that gets passed in to include in the security token. When $extra is used, the string 'bb_sec_extra' must also be sent to the server that contains the names of the parameters that were included in $extra. Use BB_IsSecExtraOpt() to determine if a specific option is in 'bb_sec_extra'.

There are several support functions that generate correct URLs and Javascript objects along with the correct security tokens. In general, those functions should be used since using this function is error-prone.

BB_IsSecExtraOpt($opt)

Parameters:

Returns: A boolean value of true if the option is found, otherwise false.

This simplifies checking the comma-separated string $_REQUEST["bb_sec_extra"] for a specific option. See the description of $extra and 'bb_sec_extra' in the function BB_CreateSecurityToken().

BB_CreatePropertiesLink($title, $bbaction, $extra = array(), ...)

Parameters:

Returns: A string containing a valid hyperlink including surrounding 'a' tags.

This function wraps up the error-prone BB_CreateSecurityToken() function and creates a valid link that loads a property form (dialog) via AJAX.

BB_CreatePropertiesJS($bbaction, $extra = array(), ...)

Parameters:

Returns: A string containing a Javascript object.

This function wraps up the error-prone BB_CreateSecurityToken() function and creates a Javascript object suitable for LoadProperties() calls. Can also be used to generate load/save callback objects for the reusable components (Code Editor, Content Editor, etc.), which are typically generated using $full set to true.

BB_CreateWidgetPropertiesLink($title, $bbaction, $extra = array(), ...)

Parameters:

Returns: A string containing a valid hyperlink targeting a Widget 'bb_action' handler. Includes surrounding 'a' tags.

This function is nearly identical to BB_CreatePropertiesLink() but adds the active Widget identifier. Creates a valid link that loads a property form (dialog) via AJAX.

BB_CreateWidgetPropertiesJS($bbaction, $extra = array(), ...)

Parameters:

Returns: A string containing a Javascript object.

This function is nearly identical to BB_CreatePropertiesJS() but adds the active Widget identifier. Creates a Javascript object suitable for LoadProperties() calls. Can also be used to generate load/save callback objects for the reusable components (Code Editor, Content Editor, etc.), which are typically generated using $full set to true.

BB_MasterWidgetManager($name)

Parameters:

Returns: Nothing.

Generates the master widget menu. This menu contains standard links such as "Add Widget", "Reorder Widgets", and detection of and support for attaching and deleting orphaned widgets and master widgets. This function is called by BB_ProcessMasterWidget() when the editor is active (i.e. only used for the preview frame).

BB_MasterWidgetPreWidget($displaymwm)

Parameters:

Returns: Nothing.

Generates the widget menu for the active widget. This menu appears before the actual widget content and contains standard links such as "Detach" and "Delete" if the user has permission and $displaymwm is true. Additional links may appear based on the widget's PreWidget() member function. This function is called by BB_ProcessMasterWidget() when the editor is active (i.e. only used for the preview frame).

BB_PropertyForm($options)

Parameters:

Returns: Nothing.

This function is used extensively to create the standard property form/dialog used everywhere within the editor. In almost all cases, it simplifies the process of creating a dialog that integrates well with the AJAX system and creates a consistent look-and-feel.

This function is covered in detail in the Creating Property Forms documentation.

BB_PropertyFormError($message)

Parameters:

Returns: Nothing.

This function displays an error message within a property form created with BB_PropertyForm() and then stops executing code via a PHP exit() call.

This function is covered in detail in the Creating Property Forms documentation.

BB_PropertyFormLoadError($message, $alt = false)

Parameters:

Returns: Nothing.

This function is used for error messages that need to be generated because the property form/dialog can't be created (typically used for insufficient privileges). The message appears and then the Javascript function CloseProperties() is called. The function stops executing code via a PHP exit() call.

When LoadProperties2() is used and an error message needs to be displayed, set $alt to true.

This function is covered in detail in the Creating Property Forms documentation.

BB_FileExplorer_ReplaceStr($find, $replace, $str)

Parameters:

Returns: The modified string.

This function is called by BB_FileExplorer_GetActionStr() and should not be called directly. It is designed for File Explorer string replacements to make strings safe for both HTML inclusion and Javascript objects.

BB_FileExplorer_GetActionStr($dir, $file, $wid = "")

Parameters:

Returns: If a suitable extension map is found in $extmap, a mapped string is modified and returned. Otherwise an empty string is returned.

This function requires two globals to be loaded prior to calling it - $editmap and $extmap. The file extension of $file is extracted and looked up in $extmap to determine which editor in $editmap to use to generate HTML/Javascript code that can be returned and output.

This function is used by File Explorer and the Layout widget. It is designed to load files on the local file system in embedded editors (e.g. the Code Editor).

Supporting Functions: 'support/functions.php'

These support functions are included by default in the editor but widgets that use them will need to have:

<?php
	require_once ROOT_PATH . "/" . SUPPORT_PATH . "/functions.php";
?>

Most of the main editor routines are encapsulated within these functions and are self-contained. This makes it easier to make mass changes across an entire website using a single script.

These functions typically assume that user-submitted content has already been filtered.

BB_Translate()

Parameters:

Returns: A translated string containing output from sprintf().

This function provides multilingual translation of an input formatting string into a single output string based on the information in $bb_langmap, $bb_admin_lang, and $bb_admin_def_lang.

BB_PostTranslate($str)

Parameters:

Returns: A translated version of the string.

This function runs specialized partial or complete translations of the input string based on the information in $bb_langmap, $bb_admin_lang, and $bb_admin_def_lang.

BB_FormatTimestamp($ts)

Parameters:

Returns: A translated string containing the timestamp in a human-readable format.

This function runs the output of the PHP date() function through BB_Translate() and BB_PostTranslate(). The format is fixed as 'M j, Y, g:i A' so dates within the admin interface are consistent everywhere.

BB_SetLanguage($path, $lang)

Parameters:

Returns: An array that indicates success and contains an error string on failure.

Loads in the specified language pack (if not already loaded) and sets the $bb_admin_lang global variable to the language.

BB_InitLangMap($path, $default = "")

Parameters:

Returns: Nothing.

Initializes $bb_langmap, $bb_admin_lang, and $bb_admin_def_lang based on the browser's preferences and available language packs. Failures are ignored.

BB_CreateUser($type, $username, $password, $group = "")

Parameters:

Returns: A boolean of true if the account was created successfully, false otherwise.

This function creates a new user account. When $type is 'content', the $group option needs to be specified.

BB_SetUserPassword($username, $password)

Parameters:

Returns: A boolean of true if the password was changed successfully, false otherwise.

This function sets the password and resets all sessions of the specified user.

BB_SetUserLanguage($username, $lang)

Parameters:

Returns: A boolean of true if the language was changed successfully, false otherwise.

This function sets the preferred language pack to load for the specified user.

BB_NewUserSession($username, $oldid)

Parameters:

Returns: A string containing a new session ID or a boolean of false if an error occurs.

This function creates a new login session ID for the specified user. It does not set a browser cookie. See the SetCookieFixDomain() function. User sessions expire based on the time stored in the configuration file for each account type.

BB_LogoutUserSession($username, $oldid)

Parameters:

Returns: A boolean of true if the session was successfully removed, false otherwise.

This function logs out a specific session for a specific user.

BB_DeleteExpiredUserSessions()

Parameters: None.

Returns: A boolean of true if successful, false otherwise.

This function deletes expired user sessions. User sessions expire based on the time stored in the configuration file for each account type.

BB_DeleteAllUserSessions()

Parameters: None.

Returns: A boolean of true if successful, false otherwise.

Wipes out all sessions that are logged in regardless of expiration date or time. This function is intended for scripting purposes.

BB_DeleteUser($username)

Parameters:

Returns: A boolean of true if the user was successfully removed, false otherwise.

This function deletes all active sessions for the specified user and then deletes the user.

BB_SaveUserAccounts()

Parameters: None.

Returns: A boolean of true if the $bb_accounts array was successfully saved, false otherwise.

This function saves changes made to the $bb_accounts array, which stores user accounts and active logins.

BB_GetAccountGroups()

Parameters: None.

Returns: A sorted array of group names.

This function scans the user accounts in $bb_accounts looking for accounts with type 'content' (Content Editors) and extracts the group each user belongs to.

BB_ExtractClientLanguages()

Parameters: None.

Returns: An array of language codes that the browser sent to the server.

This function is used to determine what the preferred language of the browser is (the Accept-Language header) when creating a new page.

BB_MakePageDirs(&$bb_dir)

Parameters:

Returns: A string containing a relative path to ROOT_PATH from $bb_dir. May modify $bb_dir with a cleaned up path.

This function creates a directory if it does not exist and calculates two paths. This function is used by BB_CreatePage() to define the $bb_dir and $bb_relroot variables for the new page.

BB_CreatePage($bb_dir, $bb_file)

Parameters:

Returns: A boolean of true if the page was successfully created, false otherwise.

This function creates a new page in Barebones CMS. Each page consists of a minimum of three files: A language independent file (e.g. 'index.php'), a language-dependent file (e.g. 'index_en_us_page.php'), and a language-dependent revision system (e.g. 'index_en_us_rev.php').

The $bb_dir and $bb_file parameters are what the resulting page's identical global variables will be ($bb_dir might be modified slightly).

BB_SaveLangPage($revnum)

Parameters:

Returns: A boolean of true if $bb_langpage was successfully saved, false otherwise.

This function saves $bb_langpage to the correct location. Most calls to this function are done within the Barebones CMS editor and pass in the global variable $bb_revision_num, which contains the active revision (the live page is '-1', revisions in the revision system start with '0').

If a revision is not writeable, then this function will fail.

BB_IsRevisionWriteable($revnum)

Parameters:

Returns: A boolean of true if the revision exists and is writeable, false otherwise.

This function determines if a specific revision number is writeable. A revision is writeable if $revnum is '-1' (the live page), the revision is the most recent 'root' revision, or the revision is the most recent revision of a branch.

BB_CreateRevision($reason, $name = false)

Parameters:

Returns: A boolean of true if the revision was successfully created, false otherwise.

This function creates a new revision in the revision system for the current $bb_langpage. It is recommended that $name be a string. The 'root' branch can be referenced via an empty string ("").

BB_CreateRevisionBranch($name)

Parameters:

Returns: A boolean of true if the branch was successfully created, false otherwise.

This function creates a new branch in the revision system. The branch name must not already be active. That is, the system allows a branch to be closed and then created again later.

BB_CloseRevisionBranch($name)

Parameters:

Returns: A boolean of true if the branch was successfully closed, false otherwise.

This function closes an open branch in the revision system. The only branch that can't be closed is the 'root' branch.

BB_SaveRevisions()

Parameters: None.

Returns: A boolean of true if the revisions were successfully saved, false otherwise.

This function saves changes made to the revision system.

BB_AddTranslationNotification($lang, $reason)

Parameters:

Returns: A boolean of true if the notification was successfully added, false otherwise.

This function adds a notification to the $bb_translate_notify array (translate.php) for the current $bb_langpage.

BB_DeleteTranslationNotification($num)

Parameters:

Returns: A boolean of true if the notification was successfully deleted, false otherwise.

This function deletes a notification from the $bb_translate_notify array (translate.php) based on the index.

BB_SaveTranslationNotifications()

Parameters: None.

Returns: A boolean of true if the notifications were successfully saved, false otherwise.

This function saves changes made to the translation notification system.

BB_GetCleanLang($lang)

Parameters:

Returns: A string that has been cleaned up intended for IANA language lookups.

This function cleans up a language input string (e.g. 'en_us' to 'en-us').

BB_CreateLangPage($lang, $langmap = "")

Parameters:

Returns: A boolean of true if the language-dependent page or mapping was successfully created, false otherwise.

This function creates a new language-dependent page and revision system OR creates a new language mapping. For example, a language-dependent page could be created as 'en-us' and then a language mapping could be 'en' to 'en-us'. This would allow browsers to request 'en' and get the 'en-us' version of the page.

BB_DeleteLangPage($lang)

Parameters:

Returns: A boolean of true if the language-dependent page or mapping was successfully deleted, false otherwise.

This function deletes a language-dependent page and revision system OR deletes a language mapping. It won't delete the default language-dependent page.

BB_SetDefaultLangPage($lang)

Parameters:

Returns: A boolean of true if the language-dependent page was successfully set as the default, false otherwise.

This function set the default language-dependent page to be used as the fallback position when there isn't a match to the browser's preferred language list or another selection made via the URL.

BB_UpdateSitemaps()

Parameters: None.

Returns: A boolean of true if the sitemaps were updated successfully, false otherwise.

Updates the XML sitemaps for the website. Typically called after changing the page's properties. A sitemap allows search engines to crawl a site more easily by finding recently changed content in a centralized location (a single sitemap file).

BB_DeletePageCache()

Parameters: None.

Returns: Nothing.

This deletes all files in the language-dependent page cache. Files are generated again on the next page load. This approach allows a change to be made to a page and be guaranteed that the information isn't cached on the front-end.

BB_GetPageGroupPermissions($perm)

Parameters:

Returns: An array containing the groups that have the permission.

This retrieves the set of group names (Content Editors only) that have a specific permission ($perm). The most common request is for "_p" to retrieve the list of groups that can edit content on the page. This information is stored in the language-independent $bb_page global variable.

BB_IsMemberOfPageGroup($perm, $account = "")

Parameters:

Returns: A boolean of true if the account has the specified permission, false otherwise.

This checks a user account to see if it has a specific permission ($perm). The most common request is for "_p" to see if the user can edit content on the page.

The $account parameter is optional. When it is not specified, the currently logged in user account is used ($bb_account).

BB_CreateWidget($sname, $name)

Parameters:

Returns: A boolean of true if the widget was successfully created, false otherwise.

This function creates a new widget.

BB_GetWidgetList()

Parameters: None.

Returns: An array containing information about the installed widgets in the system.

Retrieves a complete list of installed widgets. Special values of '_dir' and '_file' are included beyond the usual $bb_widget variables.

BB_CreateWidgetID($base)

Parameters:

Returns: A string containing a unique widget identifier.

This is a supporting function of BB_AddWidget() to create a unique widget identifier for the page. Each widget has to have a unique identifier from all other widgets (including master widgets).

BB_AddWidget($widgetdir, $name, $parent, $init = false)

Parameters:

Returns: A boolean of true if the widget was successfully added to the page, false otherwise.

This function adds a widget to a master widget on the current language-dependent page.

The $init parameter is used to determine whether or not to initialize the widget for later processing in the same request. This is used by the Layout widget when a specific widget is added to a newly created master widget automatically via the one widget only master widget feature.

BB_AttachWidget($name, $parent)

Parameters:

Returns: A boolean of true if the widget was successfully attached to the master widget, false otherwise.

This function attaches a detached (orphaned) widget to a master widget.

BB_DetachWidget($name)

Parameters:

Returns: A boolean of true if the widget or master widget was successfully detached, false otherwise.

This function detaches a widget or master widget from its parent.

BB_DetachAllWidgets($name)

Parameters:

Returns: A boolean of true if all widgets were successfully detached from the master widget, false otherwise.

This function detaches (orphans) all widgets from the specified master widget.

BB_DeleteWidget($name)

Parameters:

Returns: A boolean of true if the widget or master widget was successfully deleted, false otherwise.

This function detaches a widget or master widget from its parent, detaches any children, and then deletes it.

BB_IsMasterWidgetConnected($parent, $name)

Parameters:

Returns: A boolean of true if a master widget of $parent . "_" . $name is connected to $parent, false otherwise.

This is a function used by the Layout widget to manage master widget connections. Typically used to determine if an expected master widget exists. If it does not, then BB_AddMasterWidget() is called to create and attach it.

BB_AddMasterWidget($parent, $name)

Parameters:

Returns: A boolean of true if the master widget was successfully created/found and attached, false otherwise.

This function adds a master widget with an identifier of $parent . "_" . $name and attaches it to the $parent widget. If the master widget already exists, the existing master widget will be attached. An example of this behavior is deactivating a Layout widget layout with a @mw_left@ and then activating a different layout with another @mw_left@ will attach the existing master widget to the correct location.

This function is typically used in conjunction with BB_IsMasterWidgetConnected().

BB_GetPluginList()

Parameters: None.

Returns: An array containing the directory names of installed plugins.

This function retrieves the list of installed plugins. Plugins are stored in their own subdirectories and must have an 'index.php' file to be recognized.

BB_ProcessRelativePath($path)

Parameters:

Returns: A string with a resolved absolute path.

This function is a support function for BB_GetRealPath() that converts a relative path into an absolute path (e.g. "somedir/../index.php" to "index.php").

BB_GetRealPath($path, $relroot = true)

Parameters:

Returns: A string with a resolved absolute path from root.

This function calculates a real, absolute path from root. This function is used extensively to calculate absolute paths and avoid security vulnerabilities involving the file system. When $relroot is false, the path is relative to ROOT_PATH.

Do not use $relroot set to false unless you know what you are doing. The typical approach to this function is to calculate using $relroot set to true (the default) and then prefix ROOT_PATH. For example, ROOT_PATH . "/" . BB_GetRealPath("somedir/../index.php"); would produce a valid, complete path from the web root to the desired location.

BB_GetDirectoryList($path)

Parameters:

Returns: An array of two arrays of subdirectories ("dirs") and files ("files") within the directory specified by $path.

This function retrieves a list of subdirectories and files within the specified directory and sorts them with natcasesort(). Subdirectories go into one array of the array that is returned and is called "dirs". Files go into another array and is called "files".

BB_RemoveDirectory($path, $recursive = true)

Parameters:

Returns: A boolean of true if the directory was successfully removed, false otherwise.

This function removes/deletes a directory and optionally all subdirectories.

BB_DeleteWidgetFiles($dir)

Parameters:

Returns: A boolean of true if the widget was successfully deleted, false otherwise.

This function deletes a widget's files and forces a site-wide update of all pages using BB_WidgetStatusUpdate().

BB_WidgetStatusUpdate()

Parameters: None.

Returns: A boolean of true if the 'lastupdated.php' file was successfully updated, false otherwise.

This function updates the global cache file 'lastupdated.php'. It is designed for signaling that code in a widget has been changed and all pages need to update to include the changes.

BB_IsSSLRequest()

Parameters: None.

Returns: A boolean of true if the browser is loading the page via SSL, false otherwise.

This function attempts to detect a SSL connection. Few web servers accurately provide the status of SSL to scripting languages. As a result of the broad-based attempt at detection of SSL, this can be spoofed. The purpose of this function is to detect SSL so as to switch the user to and from SSL on the login page and inside the editor to keep login credentials and tokens secure.

BB_GetRequestHost($protocol = "")

Parameters:

Returns: A string containing the host in URL format.

This function retrieves the host in URL format and looks like 'http[s]://www.something.com[:port]' based on the current page request. The result of this function is cached. The $protocol parameter defaults to whatever type the connection is - detected with BB_IsSSLRequest() - but can be overridden by specifying 'http' or 'https'.

BB_GetRequestURLBase()

Parameters: None.

Returns: A string containing the path part of the request URL (excludes query string).

This function retrieves the path of request URL. When inside the Barebones CMS environment, it is calculated. Otherwise, $_REQUEST["REQUEST_URI"] is parsed and the protocol, host, and query string parts are removed if they exist. This function is used for the Barebones CMS editor preview pane and a few other key areas.

BB_GetFullRequestURLBase($protocol = "")

Parameters:

Returns: A string containing the full request URL.

This function combines BB_GetRequestHost() and BB_GetRequestURLBase() to obtain the full request URL.

BB_GetFullRootURLBase($protocol = "")

Parameters:

Returns: A string containing the full root URL of the Barebones CMS installation.

This function combines BB_GetRequestHost() and ROOT_URL (config.php) to obtain the full Barebones CMS root URL.

BB_GetIANAInfo($lang, $usecache = true)

Parameters:

Returns: An array containing a description path and a mapping path.

This function attempts to take an IANA language code and look up human-readable mappings for it (e.g. "en_us" should be mapped to "English, United States (en-us)").

This function can be CPU and RAM intensive. It performs a lookup in the common IANA language map (stored in 'support/php/common_lang.php') or the massive IANA language map (stored in 'support/php/iana_lang.php'). These are preprocessed lookup tables that are sourced from iana.org.

The preferred method of calling this function is to use BB_GetIANADesc() instead of calling this function directly.

BB_AddIANACache($src, $dest, $usecache = true)

Parameters:

Returns: $dest

This is a supporting function for BB_GetIANAInfo() that handles caching (if it needs caching) and returning the result passed in via $dest.

BB_GetIANADesc($lang, $usecache = true, $simple = false)

Parameters:

Returns: A string containing a human-readable language mapping in English.

This function is used to generate human-readable language mapping strings. For example, "en_us" gets mapped to "English, United States (en-us)".

BB_ValidateSWFUpload()

Parameters: None.

Returns: A string containing any error message if the file was not uploaded successfully to the server. An empty string ("") otherwise.

This function is used to perform basic validation of an upload made with SWFUpload.

BB_HTMLPurify($data, $options = array())

Parameters:

Returns: A string containing purified HTML (UTF-8 encoded).

This function is designed to purify user-submitted HTML for display (eliminates XSS attempts). Uses HTML Purifier and some custom UTF-8 filtering functions. See BB_HTMLPurifyForWYMEditor() which purifies HTML so it is compatible with WYMEditor.

BB_CSSPurify($data, $cleanall = true)

Parameters:

Returns: A string containing purified CSS.

This function is not in use in the Barebones CMS core due to rearranging of element classes and other weird oddities. It is left in just in case it comes in handy somewhere along the line.

BB_HTMLClassExplode($classes)

Parameters:

Returns: An array of key => value pairs of each class name extracted.

This function takes a string of classes from a HTML tag 'class' attribute and converts it into a fast lookup table. Each key and value pair of the resulting array are identical. This function makes it easy to manipulate the classes of a 'class' attribute.

A little bit of cleanup of unnecessary whitespace and duplicate class names are also performed.

BB_HTMLHasClass($classes, $class)

Parameters:

Returns: A boolean of true if the $class is in $classes.

This function checks for the existence of a class in a HTML tag 'class' attribute. The main tag parser does not call this function.

BB_HTMLAddClass($classes, $class)

Parameters:

Returns: A string containing all the classes plus $class if it doesn't already exist.

This function takes a list of classes, adds a new class if it doesn't already exist, and returns the result. The main tag parser does not call this function.

BB_HTMLRemoveClass($classes, $class)

Parameters:

Returns: A string containing all the classes except $class.

This function takes a list of classes, removes a class, and returns the result.

BB_HTMLParseTag($tag)

Parameters:

Returns: An array of information containing the parsed HTML tag.

This function is a very lightweight HTML parser that assumes that the tag has already been preprocessed by BB_HTMLPurify() and is valid XHTML.

BB_HTMLMakeTag($data)

Parameters:

Returns: A string containing a single HTML tag.

This function takes an array of information, usually returned from BB_HTMLParseTag(), and converts it into a HTML tag. The typical use is to extract information about the HTML tag, modify the attributes, and then recreate the tag with the modified attributes.

This function does not perform input checking.

BB_IsLocalURL($url)

Parameters:

Returns: A boolean of true if the URL is deemed to be a local URL - that is, within the confines of the Barebones CMS. False otherwise.

This function attempts to determine if the URL passed in is a local URL. The intended use is for determining if a shortcode can display the URL in the preview pane to the user and is only suitable for HTTP and HTTPS URLs.

BB_IsValidURL($url, $options = array())

Parameters:

Returns: An array of information about the URL and whether or not the request succeeded.

This function attempts to download the content at the specified URL into memory. If it succeeds, the "success" boolean in the returned array is true, otherwise false. On failure, a "error" string in the returned array contains the error message. On success, "data" contains the content of the URL, "headers" contains the HTTP headers returned by the server, and "url" contains a possibly modified $url.

The $options array parameter can include a "protocol" of "http" or "https". This is used to modify relative URLs (to the Barebones CMS root) into absolute URLs.

This function is used by the main Barebones CMS editor and Content widget Shortcodes for transferring files via URL to the server.

BB_GetImageType(&$data)

Parameters:

Returns: A string containing the detected image type or an empty string ("").

This function uses official magic numbers, typically located at the start of the image, to detect the real content type. Detects "gif", "jpg", and "png" types.

BB_IsValidHTMLImage($url, $options = array())

Parameters:

Returns: An array of information about the URL and whether or not the request succeeded.

This function attempts to download an image at the specified URL into memory. If it succeeds, the "success" boolean in the returned array is true, otherwise false. On failure, a "error" string in the returned array contains the error message. On success, "data" contains the image content of the URL, "type" contains the type of image as determined by BB_GetImageType(), and "url" contains a possibly modified $url.

The $options array parameter can include a "protocol" of "http" or "https". This is used to modify relative URLs (to the Barebones CMS root) into absolute URLs. It may also contain booleans of "allow_gif", "allow_jpg", and "allow_png" set to false (Default is true) to limit what images are allowed.

This function is used by Content widget Shortcodes for transferring images via URL to the server.

BB_MakeFilenameFromURL($url, $forceext = "", ...)

Parameters:

Returns: A string containing a possibly safe local filename based on the specified URL.

This function is built specifically to be used in conjunction with transferring files from another server via URL. It is your responsibility to make sure that the resulting filename is truly safe. Usually this means analyzing the content of the URL and then forcing a file extension with $forceext if the content is deemed both valid and safe to store on the server.

This function is used by the main Barebones CMS editor and Content widget Shortcodes for transferring files via URL to the server.

BB_HTMLPurifyForWYMEditor($data, $options)

Parameters:

Returns: A string containing purified and filtered XHTML content that is compatible with WYMEditor.

This function one portion of a two part parser. It is the slowest part of the entire Barebones CMS and processes input data at a rate of around 6KB per second. The output of this function is XHTML that is WYMEditor- and transformation-ready and free of XSS attempts. The output content is NOT web-ready. See BB_HTMLTransformForWYMEditor() for transforming content output from this function into web-ready content.

This approach allows the output of this function to be stored internally for fast retrieval for conversion to the web-ready state OR quickly loading the content into WYMEditor later.

The $options array can contain a number of options (the defaults are usually good enough):

BB_HTMLTransformForWYMEditor_BacktrackStack(...)

Parameters:

Returns: A boolean of true if $type is found, false otherwise.

This function is a supporting function of BB_HTMLTransformForWYMEditor() that performs backtracking of open HTML tags on the stack. This is possible because special classes (e.g. 'table-row') transform paragraph 'p' tags to create new open HTML tags that need to be closed.

BB_HTMLTransformForWYMEditor($data, $options)

Parameters:

Returns: A string containing web-safe XHTML content.

This function is designed to generate output to a web browser and is the second part of the two-part parser (the first part being BB_HTMLPurifyForWYMEditor()). This function is very fast (approximately 10 milliseconds per 6KB), implements a lightweight tag parser, and performs the final transformations of the content complete with configurable callback routines.

The $options array can contain a number of options (the defaults are usually good enough):

BB_JSSafe($data)

Parameters:

Returns: A string containing data that is safe for use in Javascript.

This function is used extensively to create error-free Javascript strings. Note that only single-quotes are escaped.

BB_HTMLToJS($data)

Parameters:

Returns: A string containing document.write() statements for use inside of Javascript.

This function is used to create inline script tags so that pages can be cached except for the section that has per-client dynamic output. For example, the Installation documentation outputs the IP address of the client to their web browser using this approach.

BB_PHPShorthandToBytes($val)

Parameters:

Returns: An integer containing the shorthand size in bytes.

This function is used primarily to determine how many bytes can be uploaded to the server.

BB_PreMainJS()

Parameters: None.

Returns: Nothing.

This function generates a series of Javascript statements designed to setup before loading the main Barebones CMS editor. This function can also be called on the front-end by setting $bb_use_premainjs to true.

Supporting Functions: 'support/str_basics.php'

The 'support/str_basics.php' file contains older functions that predate Barebones CMS and were among the first functions of the Barebones CMS before various naming conventions were put in place. These functions provide rudimentary support for older library calls for processing strings.

These functions may be rewritten in the future to better fit in with the Barebones CMS naming conventions.

ProcPOSTStr($data)

Parameters:

Returns: A string that is trim()'ed and magic quote free.

This function is called by ProcessSingleInput() to clean up strings so there is no surrounding whitespace and no magic quotes (if enabled).

ProcessSingleInput($data)

Parameters:

Returns: Nothing.

This function is called by ProcessAllInput() to clean up a PHP superglobal and overwrite existing values in $_REQUEST.

ProcessAllInput()

Parameters: None.

Returns: Nothing.

This function processes and filters $_COOKIE, $_GET, and $_POST into the $_REQUEST superglobal. This function allows $_GET and $_POST to override any $_COOKIE variables that were set of the same name (useful for SWFUpload), trim()'s user input, and removes magic quotes.

Use the $_REQUEST superglobal for everything in the Barebones CMS. It offers significant benefits and convenience.

ExtractPathname($dirfile)

Parameters:

Returns: A string containing the path.

This function extracts the path from a path and filename combination. For example, '/test/index.php' becomes '/test/'.

ExtractFilename($dirfile)

Parameters:

Returns: A string containing the filename.

This function extracts the filename from a path and filename combination. For example, '/test/index.php' becomes 'index.php'.

ExtractFileExtension($dirfile)

Parameters:

Returns: A string containing the file extension.

This function extracts the file extension from a path and filename combination. For example, '/test/index.php' becomes 'php'.

ExtractFilenameNoExtension($dirfile)

Parameters:

Returns: A string containing the filename without the file extension.

This function extracts the filename without the file extension from a path and filename combination. For example, '/test/index.php' becomes 'index'.

FilenameSafe($filename)

Parameters:

Returns: A string containing a safe filename prefix.

This function allows the characters A-Z, a-z, 0-9, '_' (underscore), '.' (period), and '-' (hyphen) through. All other characters are converted to underscores. Multiple underscores in a row are converted to one underscore. So a filename like 'index@$%*&^$+hacked?12.php' becomes 'index_hacked_12.php'. Note that this function still allows file extensions through - you should always add your own file extension when calling this function.

ReplaceNewlines($replacewith, $data)

Parameters:

Returns: A string with newlines replaced.

This function cleverly replaces any newline combination with the desired target. Usually this function is used for replacing one (unknown) type of newline in some data with another, specific newline type. Windows newlines are '\r\n', Mac newlines are '\r', and *NIX newlines are '\n'. This function deals with all three and even correctly handles most mixed cases too.

LineInput($data, &$pos)

Parameters:

Returns: A string containing the next line of data minus the newline.

This function is very old and designed to mimic an internal C++ library I've written. Do not use. This function reads in the next line of buffered data and moves $pos to the start of the next line. Used mostly by the older PHP libraries that are included with Barebones CMS.

Supporting Functions: 'support/utf8.php'

Like 'support/str_basics.php' above, the 'support/utf8.php' file contains older functions that predate Barebones CMS and were among the first functions of the Barebones CMS before various naming conventions were put in place. These functions provide rudimentary support for older library calls for processing unicode strings in PHP.

These functions may be rewritten in the future to better fit in with the Barebones CMS naming conventions.

NOTE: Since writing these functions, I've learned a ton about Unicode. I've also learned that you should never, ever want to attempt to write your own Unicode library in any programming language. Take strtolower(), for example. Functions like that are ONLY valid for the English language. To do the same thing in Unicode requires enormous effort because the concept of 'lowercase' in any other language is generally rather complex or simply non-existent.

MakeValidUTF8($Data)

Parameters:

Returns: A valid UTF-8 string.

This function analyzes an input string for invalid UTF-8 code points, removes them, and returns the cleaned up string. Most built-in PHP functions for Unicode will return an error or stop processing the moment an invalid byte is encountered. One of the benefits of UTF-8 is its ability to recover from errors. It is easy to identify where a new code point starts and recover most of a string starting at the next valid byte.

IsValidUTF8($Data)

Parameters:

Returns: A boolean of true if the string is valid UTF-8, false otherwise.

This function checks a string to see if it is 100% valid UTF-8.

UTF8NextChrPos(&$Data, $DataLength, &$Pos, &$Size)

Parameters:

Returns: A boolean of true if there is a code point and the next UTF-8 code point is valid, false otherwise. $Size is set to the length of the code point.

This function is intended to be used in a loop to get the next code point in the string and leave the loop when the function returns false. Set $Pos and $Size to 0 before calling. $DataLength should be set to the value of strlen($Data). See the source code to UTF8IsASCII() for an example.

UTF8IsASCII($Data)

Parameters:

Returns: A boolean of true if the string is valid ASCII, false otherwise.

This function determines if the UTF-8 string is 100% ASCII. Useful for some ancient technologies (e.g. SMTP).

ConvertUTF8ToASCII($Data)

Parameters:

Returns: A string containing only ASCII characters.

This function drops bad UTF-8 code points and non-ASCII characters and then returns the result.

ConvertUTF8ToHTML($data)

Parameters:

Returns: A string with Unicode code points converted into HTML entities.

This function makes it possible to display Unicode characters even on pages with a different encoding other than UTF-8. Unicode code points are converted to HTML entities. The resulting output takes up a lot more space but should work under a wide variety of encodings.

Barebones CMS always emits UTF-8 to the user. This function is used for getting content into WYMEditor, which does not like UTF-8 characters.

ConvertUTF8ToHTML__Callback($data)

Parameters:

Returns: A string with the Unicode code point converted into a HTML entity.

This is a regular expression callback for ConvertUTF8ToHTML(). Do not call directly.

ConvertCharset($Data, $InCharset, $OutCharset)

Parameters:

Returns: A converted string on success, a boolean of false otherwise.

This function uses the built-in PHP functions iconv(), mb_convert_encoding(), and utf8_encode()/utf8_decode() if available to convert between character sets and returns the result. Mostly designed to convert between UTF-8, ISO-8859-1, and ASCII. Other character sets may work too.

Core Functions: 'support/js/mainedit.js'

These functions are part of the main Barebones CMS editor and provide all the basic AJAX support that the editor requires. Widgets and Shortcodes should leverage these functions to accomplish their tasks within the editor.

Some of the functionality is technically reusable but would be a bit odd to reuse. Specifically, the delayed Javascript and CSS loaders. Maybe such features will be cleanly broken out into an external reusable component in a future version.

ResizeIFrame()

Parameters: None.

Returns: Nothing.

This internal function is called every second to automatically resize the height of the iframe of the preview pane.

BeginResizeIFrame()

Parameters: None.

Returns: Nothing.

This internal function is called to start the one-second interval timer for the iframe preview pane.

EndResizeIFrame()

Parameters: None.

Returns: Nothing.

This internal function is called to stop the one-second interval timer for the iframe preview pane.

ReloadMenu()

Parameters: None.

Returns: Nothing.

This function reloads the left navigation menu.

ReloadMainViewInfo()

Parameters: None.

Returns: Nothing.

This function reloads the language string that appears just above the iframe preview pane.

UpdateSessionInfo()

Parameters: None.

Returns: Nothing.

This internal function is supposed to keep the time left in the current login session info fresh (5 second interval). It does not always work perfectly.

ReloadIFrame()

Parameters: None.

Returns: Nothing.

This function reloads the iframe preview pane.

ReloadPage()

Parameters: None.

Returns: Nothing.

This function reloads the entire page. This function should generally be avoided since the sections of the page that need reloading can usually be reloaded with other functions.

FindPagePosition(elem)

Parameters:

Returns: A Javascript array of two elements containing x and y coordinates, in pixels, of the upper-left corner of the specified 'elem'.

This function locates an element on a page in pixel coordinates. For example, this function is called by the Content Editor to determine where on the page the right column starts so it knows how many pixels to push down the tools so it travels with the user.

AddPropertyChange(callback, params)

Parameters:

Returns: Nothing.

This function adds a callback function with parameters to call when the property form changes - that is, LoadProperties() or CloseProperties() is called. This allows custom Javascript to perform cleanup so there are no Javascript errors on the page. Even one Javascript error can break the editor.

ProcessPropertyChangeQueue()

Parameters: None.

Returns: Nothing.

This internal function is used to process callbacks registered with AddPropertyChange().

LoadProperties(params, callback)

Parameters:

Returns: A boolean of false.

This function loads the first property form with a property form/dialog. This dialog is usually built with a BB_PropertyForm() call. The function returns false to make it easy to use in hyperlinks. Upon calling this function, the browser attempts to scroll to the top of the page.

Note that there are a few PHP support functions that call LoadProperties() directly (BB_CreatePropertiesLink(), etc.) and several PHP support functions that will generate the params object (BB_CreatePropertiesJS(), etc). Prefer to call those functions because they also generate the required security token.

The callback parameter is never used in Barebones CMS.

CloseProperties(restorescroll)

Parameters:

Returns: A boolean of false.

This function closes a property form opened with a LoadProperties() call. By default, this function will attempt to jump back to where the user was on the page.

SendProperties()

Parameters: None.

Returns: A boolean of false.

This function sends the form created by BB_PropertyForm() and loaded with LoadProperties() to the server. This is done with a GET request but may eventually be changed to be a POST request. It is recommended to prefer using $_REQUEST to access variables sent to the server.

LoadProperties2(params, callback)

Parameters:

Returns: A boolean of false.

This function loads the second property form. This is designed to be a lighter-weight loader for no-form functionality. That is, something else gets loaded instead such as an editor or some action needs to take place where a dialog is not necessary. Part of the action phase typically makes a Javascript call to CloseProperties2().

CloseProperties2()

Parameters: None.

Returns: A boolean of false.

This function closes a property form opened with a LoadProperties2() call.

AddOnBeforeUnload(callback)

Parameters:

Returns: A boolean of true.

The default 'onbeforeunload' Javascript event only takes one callback. This function allows multiple functions to be registered with the callback. Each registered callback should take no parameters and return a string to display to the user.

Typical use of this function is to register a reusable component (e.g. Content Editor) with the browser to notify the user when they attempt to leave the page or close the browser without saving their changes.

ProcessOnBeforeUnload()

Parameters: None.

Returns: A string containing the message to display to the user.

This internal function calls each callback that was added using AddOnBeforeUnload(). Each callback is called and responses stored. Empty strings ("") are ignored. Non-empty strings are concatenated together into a single message and returned. The browser is responsible for displaying the message to the user.

DisplayConditionalScripts()

Parameters: None.

Returns: Nothing.

This internal function displays the active conditional scripts to the user so they know something is going on. Typically used for loading the larger reusable components.

InternalProcessConditionalScripts()

Parameters: None.

Returns: Nothing.

This internal function handles changes to the conditional script loading process. As each script is loaded, callbacks are executed and processed.

IsConditionalScriptLoading()

Parameters: None.

Returns: A boolean of true if there is at least one conditional script loading, false otherwise.

This function determines if there are any conditional scripts loading.

LoadConditionalScript(url, cachescript, cond, callback, params)

Parameters:

Returns: Nothing.

Example of loading SWFUpload in File Explorer:

<?php
	// SWFUpload is delay-loaded and loaded exactly one time.
?>
<script type="text/javascript">
LoadConditionalScript(Gx__RootURL + '/' + Gx__SupportPath + '/upload.js?_=20090725', true, function(loaded) {
		return ((!loaded && typeof(window.CreateSWFUploadInterface) == 'function') || (loaded && !IsConditionalScriptLoading()));
	}, function() {
		AddPropertyChange(ManageFileUploadDestroy, CreateSWFUploadInterface('swfupload_inject', <?php echo BB_CreatePropertiesJS("bb_main_edit_site_opt_file_explorer_swfupload", array("dir" => $_REQUEST["dir"]), true, true); ?>, ManageFileUploadResults, <?php echo BB_CreatePropertiesJS("bb_main_edit_site_opt_file_explorer", array("dir" => $_REQUEST["dir"])); ?>));
});
</script>

This function conditionally loads a Javascript file. This is primarily used for delay-loading Javascript files exactly one time per page. The 'cond' callback function is called by this function with a boolean of false (cond(false)) to determine if the script needs to be loaded in the first place. If it does, the information is added to a queue and the URL is loaded. As each script finishes loading, InternalProcessConditionalScripts() is called and cond(true) is executed to determine if it is okay to remove the script from the queue. This approach allows multiple scripts that have dependencies on other scripts to be chained together and guarantee a specific loading order.

As can be seen from the example, this function can be rather messy/difficult to work with.

InjectScriptTag(url)

Parameters:

Returns: Nothing.

This function is used to work around third-party components that look for their 'script' tag declaration in the header to operate properly. Under most circumstances, this is a non-issue. However, the main Barebones CMS editor delay-loads everything, including Javascript. This means that some third-party components could break. This helps alleviate that issue.

Note that the script itself is NOT loaded. This is designed to be used in conjunction with LoadConditionalScript() calls.

LoadCSS(url, cssmedia)

Parameters:

Returns: Nothing.

This function delay-loads a CSS file. The CSS file is injected into the 'head' element.

Note: Some browsers have limitations on the number of CSS files that can be loaded on a page. Beyond that number, they are ignored.

InitPropertiesTableDragAndDrop(tableid)

Parameters:

Returns: A boolean of false.

This internal function is designed specifically for BB_PropertyForm() drag-and-drop reordering of table items.

ManageFileUploadResults(params)

Parameters:

Returns: Nothing.

This function handles file upload results from SWFUpload for property forms. If there were errors, processing stops so the user can see the errors. If successful, LoadProperties() is called with 'params'.

ManageFileUploadDestroy(swfu)

Parameters:

Returns: Nothing.

This function cleanly removes a SWFUpload instance from a page. This is used primarily within property forms when they go away and is registered with the AddPropertyChange() function. Failure to remove the object cleanly results in a Javascript error.

EditFile(dir, file, syntaxopt, loadtoken, savetoken)

Parameters:

Returns: A boolean of false.

This function creates an ACE or EditArea instance for a specific directory and filename. Designed for File Explorer operations. Therefore, File Explorer restrictions with EditFile() apply. If the file is already open, it will attempt to reload the file.

ClosedAllFiles(eid)

Parameters:

Returns: Nothing.

This internal function is called when the last EditArea is closed. It hides the EditArea cleanly. Failure to hide the object cleanly results in a Javascript error.

© CubicleSoft