<?php
/*
+--------------------------------------------------------------------+
- | CiviCRM version 4.5 |
+ | CiviCRM version 4.6 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2014 |
+--------------------------------------------------------------------+
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
-*/
+ */
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2014
* $Id$
- *
*/
require_once 'HTML/QuickForm/Rule/Email.php';
/**
- * This class contains string functions
+ * This class contains string functions.
*
*/
class CRM_Utils_String {
- CONST COMMA = ",", SEMICOLON = ";", SPACE = " ", TAB = "\t", LINEFEED = "\n", CARRIAGELINE = "\r\n", LINECARRIAGE = "\n\r", CARRIAGERETURN = "\r";
+ const COMMA = ",", SEMICOLON = ";", SPACE = " ", TAB = "\t", LINEFEED = "\n", CARRIAGELINE = "\r\n", LINECARRIAGE = "\n\r", CARRIAGERETURN = "\r";
/**
* List of all letters and numbers
const ALPHANUMERIC = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
/**
- * Convert a display name into a potential variable
- * name that we could use in forms/code
- *
- * @param name Name of the string
- *
- * @return string An equivalent variable name
+ * Convert a display name into a potential variable name.
*
- * @access public
+ * @param $title title of the string
+ * @param int $maxLength
*
- * @return string (or null)
- * @static
+ * @return string
+ * An equivalent variable name.
*/
- static function titleToVar($title, $maxLength = 31) {
+ public static function titleToVar($title, $maxLength = 31) {
$variable = self::munge($title, '_', $maxLength);
if (CRM_Utils_Rule::title($variable, $maxLength)) {
}
/**
- * given a string, replace all non alpha numeric characters and
- * spaces with the replacement character
- *
- * @param string $name the name to be worked on
- * @param string $char the character to use for non-valid chars
- * @param int $len length of valid variables
+ * Replace all non alpha numeric characters and spaces with the replacement character.
*
- * @access public
+ * @param string $name
+ * The name to be worked on.
+ * @param string $char
+ * The character to use for non-valid chars.
+ * @param int $len
+ * Length of valid variables.
*
- * @return string returns the manipulated string
- * @static
+ * @return string
+ * returns the manipulated string
*/
- static function munge($name, $char = '_', $len = 63) {
- // replace all white space and non-alpha numeric with $char
+ public static function munge($name, $char = '_', $len = 63) {
+ // Replace all white space and non-alpha numeric with $char
// we only use the ascii character set since mysql does not create table names / field names otherwise
// CRM-11744
$name = preg_replace('/[^a-zA-Z0-9]+/', $char, trim($name));
}
/**
+ * Convert possibly underscore separated words to camel case with special handling for 'UF'
+ * e.g membership_payment returns MembershipPayment
*
- * Takes a variable name and munges it randomly into another variable name
+ * @param string $string
+ *
+ * @return string
+ */
+ public static function convertStringToCamel($string) {
+ $fragments = explode('_', $string);
+ foreach ($fragments as & $fragment) {
+ $fragment = ucfirst($fragment);
+ }
+ // Special case: UFGroup, UFJoin, UFMatch, UFField
+ if ($fragments[0] === 'Uf') {
+ $fragments[0] = 'UF';
+ }
+ return implode('', $fragments);
+ }
+
+ /**
+ * Takes a variable name and munges it randomly into another variable name.
*
- * @param string $name Initial Variable Name
- * @param int $len length of valid variables
+ * @param string $name
+ * Initial Variable Name.
+ * @param int $len
+ * Length of valid variables.
*
- * @return string Randomized Variable Name
- * @access public
- * @static
+ * @return string
+ * Randomized Variable Name
*/
- static function rename($name, $len = 4) {
+ public static function rename($name, $len = 4) {
$rand = substr(uniqid(), 0, $len);
return substr_replace($name, $rand, -$len, $len);
}
/**
- * takes a string and returns the last tuple of the string.
- * useful while converting file names to class names etc
+ * Takes a string and returns the last tuple of the string.
*
- * @param string $string the input string
- * @param char $char the character used to demarcate the componets
+ * Useful while converting file names to class names etc
*
- * @access public
+ * @param string $string
+ * The input string.
+ * @param string $char
+ * Character used to demarcate the components
*
- * @return string the last component
- * @static
+ * @return string
+ * The last component
*/
- static function getClassName($string, $char = '_') {
+ public static function getClassName($string, $char = '_') {
$names = array();
if (!is_array($string)) {
$names = explode($char, $string);
}
/**
- * appends a name to a string and seperated by delimiter.
- * does the right thing for an empty string
+ * Appends a name to a string and separated by delimiter.
*
- * @param string $str the string to be appended to
- * @param string $delim the delimiter to use
- * @param mixed $name the string (or array of strings) to append
+ * Does the right thing for an empty string
*
- * @return void
- * @access public
- * @static
+ * @param string $str
+ * The string to be appended to.
+ * @param string $delim
+ * The delimiter to use.
+ * @param mixed $name
+ * The string (or array of strings) to append.
*/
- static function append(&$str, $delim, $name) {
+ public static function append(&$str, $delim, $name) {
if (empty($name)) {
return;
}
}
/**
- * determine if the string is composed only of ascii characters
+ * Determine if the string is composed only of ascii characters.
*
- * @param string $str input string
- * @param boolean $utf8 attempt utf8 match on failure (default yes)
+ * @param string $str
+ * Input string.
+ * @param bool $utf8
+ * Attempt utf8 match on failure (default yes).
*
- * @return boolean true if string is ascii
- * @access public
- * @static
+ * @return bool
+ * true if string is ascii
*/
- static function isAscii($str, $utf8 = TRUE) {
+ public static function isAscii($str, $utf8 = TRUE) {
if (!function_exists('mb_detect_encoding')) {
// eliminate all white space from the string
$str = preg_replace('/\s+/', '', $str);
}
/**
- * determine the string replacements for redaction
+ * Determine the string replacements for redaction.
* on the basis of the regular expressions
*
- * @param string $str input string
- * @param array $regexRules regular expression to be matched w/ replacements
+ * @param string $str
+ * Input string.
+ * @param array $regexRules
+ * Regular expression to be matched w/ replacements.
*
- * @return array $match array of strings w/ corresponding redacted outputs
- * @access public
- * @static
+ * @return array
+ * array of strings w/ corresponding redacted outputs
*/
- static function regex($str, $regexRules) {
+ public static function regex($str, $regexRules) {
//redact the regular expressions
if (!empty($regexRules) && isset($str)) {
static $matches, $totalMatches, $match = array();
return CRM_Core_DAO::$_nullArray;
}
- static function redaction($str, $stringRules) {
+ /**
+ * @param $str
+ * @param $stringRules
+ *
+ * @return mixed
+ */
+ public static function redaction($str, $stringRules) {
//redact the strings
if (!empty($stringRules)) {
foreach ($stringRules as $match => $replace) {
/**
* Determine if a string is composed only of utf8 characters
*
- * @param string $str input string
- * @access public
- * @static
+ * @param string $str
+ * Input string.
*
- * @return boolean
+ * @return bool
*/
- static function isUtf8($str) {
+ public static function isUtf8($str) {
if (!function_exists(mb_detect_encoding)) {
// eliminate all white space from the string
$str = preg_replace('/\s+/', '', $str);
/* pattern stolen from the php.net function documentation for
- * utf8decode();
- * comment by JF Sebastian, 30-Mar-2005
- */
+ * utf8decode();
+ * comment by JF Sebastian, 30-Mar-2005
+ */
return preg_match('/^([\x00-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xec][\x80-\xbf]{2}|\xed[\x80-\x9f][\x80-\xbf]|[\xee-\xef][\x80-\xbf]{2}|f0[\x90-\xbf][\x80-\xbf]{2}|[\xf1-\xf3][\x80-\xbf]{3}|\xf4[\x80-\x8f][\x80-\xbf]{2})*$/', $str);
// ||
}
/**
- * determine if two href's are equivalent (fuzzy match)
+ * Determine if two href's are equivalent (fuzzy match)
*
- * @param string $url1 the first url to be matched
- * @param string $url2 the second url to be matched against
+ * @param string $url1
+ * The first url to be matched.
+ * @param string $url2
+ * The second url to be matched against.
*
- * @return boolean true if the urls match, else false
- * @access public
- * @static
+ * @return bool
+ * true if the urls match, else false
*/
- static function match($url1, $url2) {
+ public static function match($url1, $url2) {
$url1 = strtolower($url1);
$url2 = strtolower($url2);
}
/**
- * Function to extract variable values
+ * Extract the civicrm path from the url.
*
- * @param mix $query this is basically url
+ * @param string $query
+ * A url string.
*
- * @return mix $v returns civicrm url (eg: civicrm/contact/search/...)
- * @access public
- * @static
+ * @return string|null
+ * civicrm url (eg: civicrm/contact/search)
*/
- static function extractURLVarValue($query) {
+ public static function extractURLVarValue($query) {
$config = CRM_Core_Config::singleton();
$urlVar = $config->userFrameworkURLVar;
}
/**
- * translate a true/false/yes/no string to a 0 or 1 value
+ * Translate a true/false/yes/no string to a 0 or 1 value
*
- * @param string $str the string to be translated
+ * @param string $str
+ * The string to be translated.
*
- * @return boolean
- * @access public
- * @static
+ * @return bool
*/
- static function strtobool($str) {
+ public static function strtobool($str) {
if (!is_scalar($str)) {
return FALSE;
}
}
/**
- * returns string '1' for a true/yes/1 string, and '0' for no/false/0 else returns false
+ * Returns string '1' for a true/yes/1 string, and '0' for no/false/0 else returns false
*
- * @param string $str the string to be translated
+ * @param string $str
+ * The string to be translated.
*
- * @return boolean
- * @access public
- * @static
+ * @return bool
*/
- static function strtoboolstr($str) {
+ public static function strtoboolstr($str) {
if (!is_scalar($str)) {
return FALSE;
}
/**
* Convert a HTML string into a text one using html2text
*
- * @param string $html the string to be converted
+ * @param string $html
+ * The string to be converted.
*
- * @return string the converted string
- * @access public
- * @static
+ * @return string
+ * the converted string
*/
- static function htmlToText($html) {
+ public static function htmlToText($html) {
require_once 'packages/html2text/rcube_html2text.php';
$token_html = preg_replace('!\{([a-z_.]+)\}!i', 'token:{$1}', $html);
$converter = new rcube_html2text($token_html);
return $text;
}
- static function extractName($string, &$params) {
+ /**
+ * @param $string
+ * @param array $params
+ */
+ public static function extractName($string, &$params) {
$name = trim($string);
if (empty($name)) {
return;
}
}
- static function &makeArray($string) {
+ /**
+ * @param $string
+ *
+ * @return array
+ */
+ public static function &makeArray($string) {
$string = trim($string);
$values = explode("\n", $string);
* Given an ezComponents-parsed representation of
* a text with alternatives return only the first one
*
- * @param string $full all alternatives as a long string (or some other text)
+ * @param string $full
+ * All alternatives as a long string (or some other text).
*
- * @return string only the first alternative found (or the text without alternatives)
+ * @return string
+ * only the first alternative found (or the text without alternatives)
*/
- static function stripAlternatives($full) {
+ public static function stripAlternatives($full) {
$matches = array();
preg_match('/-ALTERNATIVE ITEM 0-(.*?)-ALTERNATIVE ITEM 1-.*-ALTERNATIVE END-/s', $full, $matches);
}
/**
- * strip leading, trailing, double spaces from string
+ * Strip leading, trailing, double spaces from string
* used for postal/greeting/addressee
*
- * @param string $string input string to be cleaned
+ * @param string $string
+ * Input string to be cleaned.
*
- * @return string the cleaned string
- * @access public
- * @static
+ * @return string
+ * the cleaned string
*/
- static function stripSpaces($string) {
+ public static function stripSpaces($string) {
return (empty($string)) ? $string : preg_replace("/\s{2,}/", " ", trim($string));
}
/**
- * This function is used to clean the URL 'path' variable that we use
+ * clean the URL 'path' variable that we use
* to construct CiviCRM urls by removing characters from the path variable
*
- * @param string $string the input string to be sanitized
- * @param array $search the characters to be sanitized
- * @param string $replace the character to replace it with
+ * @param string $string
+ * The input string to be sanitized.
+ * @param array $search
+ * The characters to be sanitized.
+ * @param string $replace
+ * The character to replace it with.
*
- * @return string the sanitized string
- * @access public
- * @static
+ * @return string
+ * the sanitized string
*/
- static function stripPathChars($string,
+ public static function stripPathChars(
+ $string,
$search = NULL,
$replace = NULL
) {
if ($_searchChars == NULL) {
$_searchChars = array(
- '&', ';', ',', '=', '$',
- '"', "'", '\\',
- '<', '>', '(', ')',
- ' ', "\r", "\r\n", "\n", "\t",
+ '&',
+ ';',
+ ',',
+ '=',
+ '$',
+ '"',
+ "'",
+ '\\',
+ '<',
+ '>',
+ '(',
+ ')',
+ ' ',
+ "\r",
+ "\r\n",
+ "\n",
+ "\t",
);
$_replaceChar = '_';
}
-
if ($search == NULL) {
$search = $_searchChars;
}
* xss attacks. This is primarily used in public facing pages which
* accept html as the input string
*
- * @param string $string the input string
+ * @param string $string
+ * The input string.
*
- * @return string the cleaned up string
- * @public
- * @static
+ * @return string
+ * the cleaned up string
*/
- static function purifyHTML($string) {
- static $_filter = null;
+ public static function purifyHTML($string) {
+ static $_filter = NULL;
if (!$_filter) {
$config = HTMLPurifier_Config::createDefault();
$config->set('Core.Encoding', 'UTF-8');
// Disable the cache entirely
- $config->set('Cache.DefinitionImpl', null);
+ $config->set('Cache.DefinitionImpl', NULL);
$_filter = new HTMLPurifier($config);
}
*
* @param string $string
* @param int $maxLen
+ *
+ * @return string
*/
- static function ellipsify($string, $maxLen) {
+ public static function ellipsify($string, $maxLen) {
$len = strlen($string);
if ($len <= $maxLen) {
return $string;
}
else {
- return substr($string, 0, $maxLen-3) . '...';
+ return substr($string, 0, $maxLen - 3) . '...';
}
}
/**
- * Generate a random string
+ * Generate a random string.
*
* @param $len
* @param $alphabet
* "admin foo" => array(NULL,"admin foo")
* "cms:admin foo" => array("cms", "admin foo")
*
- * @param string $string e.g. "view all contacts". Syntax: "[prefix:]name"
- * @return array (0 => string|NULL $prefix, 1 => string $value)
+ * @param $delim
+ * @param string $string
+ * E.g. "view all contacts". Syntax: "[prefix:]name".
+ * @param null $defaultPrefix
+ *
+ * @return array
+ * (0 => string|NULL $prefix, 1 => string $value)
*/
public static function parsePrefix($delim, $string, $defaultPrefix = NULL) {
$pos = strpos($string, $delim);
return array($defaultPrefix, $string);
}
else {
- return array(substr($string, 0, $pos), substr($string, 1+$pos));
+ return array(substr($string, 0, $pos), substr($string, 1 + $pos));
}
}
/**
- * this function will mask part of the the user portion of an Email address (everything before the @)
+ * This function will mask part of the the user portion of an Email address (everything before the @)
*
- * @param string $email the email address to be masked
- * @param string $maskChar the character used for masking
- * @param integer $percent the percentage of the user portion to be masked
+ * @param string $email
+ * The email address to be masked.
+ * @param string $maskChar
+ * The character used for masking.
+ * @param int $percent
+ * The percentage of the user portion to be masked.
*
- * @return string returns the masked Email address
+ * @return string
+ * returns the masked Email address
*/
- public static function maskEmail($email, $maskChar= '*', $percent=50) {
+ public static function maskEmail($email, $maskChar = '*', $percent = 50) {
list($user, $domain) = preg_split("/@/", $email);
$len = strlen($user);
- $maskCount = floor($len * $percent /100);
+ $maskCount = floor($len * $percent / 100);
$offset = floor(($len - $maskCount) / 2);
$masked = substr($user, 0, $offset)
- .str_repeat($maskChar, $maskCount)
- .substr($user, $maskCount + $offset);
+ . str_repeat($maskChar, $maskCount)
+ . substr($user, $maskCount + $offset);
- return($masked.'@'.$domain);
+ return ($masked . '@' . $domain);
}
/**
- * this function compares two strings
+ * This function compares two strings.
*
- * @param string $strOne string one
- * @param string $strTwo string two
- * @param boolean $case boolean indicating whether you want the comparison to be case sensitive or not
+ * @param string $strOne
+ * String one.
+ * @param string $strTwo
+ * String two.
+ * @param bool $case
+ * Boolean indicating whether you want the comparison to be case sensitive or not.
*
- * @return boolean TRUE (string are identical); FALSE (strings are not identical)
+ * @return bool
+ * TRUE (string are identical); FALSE (strings are not identical)
*/
public static function compareStr($strOne, $strTwo, $case) {
if ($case == TRUE) {
}
}
-}
+ /**
+ * Many parts of the codebase have a convention of internally passing around
+ * HTML-encoded URLs. This effectively means that "&" is replaced by "&"
+ * (because most other odd characters are %-escaped in URLs; and %-escaped
+ * strings don't need any extra escaping in HTML).
+ *
+ * @param string $htmlUrl
+ * URL with HTML entities.
+ * @return string
+ * URL without HTML entities
+ */
+ public static function unstupifyUrl($htmlUrl) {
+ return str_replace('&', '&', $htmlUrl);
+ }
+
+ /**
+ * Formats a string of attributes for insertion in an html tag.
+ *
+ * @param array $attributes
+ *
+ * @return string
+ */
+ public static function htmlAttributes($attributes) {
+ $output = '';
+ foreach ($attributes as $name => $vals) {
+ $output .= " $name=\"" . htmlspecialchars(implode(' ', (array) $vals)) . '"';
+ }
+ return ltrim($output);
+ }
+}