6 * Copyright (c) 1999-2005 The SquirrelMail Project Team
7 * Licensed under the GNU GPL. For full terms see the file COPYING.
9 * This code provides various string manipulation functions that are
10 * used by the rest of the SquirrelMail code.
13 * @package squirrelmail
17 if (!defined('SM_PATH')) define('SM_PATH','../');
20 * SquirrelMail version number -- DO NOT CHANGE
23 $version = '1.5.1 [CVS]';
26 * SquirrelMail internal version number -- DO NOT CHANGE
27 * $sm_internal_version = array (release, major, minor)
29 global $SQM_INTERNAL_VERSION;
30 $SQM_INTERNAL_VERSION = array(1,5,1);
33 * There can be a circular issue with includes, where the $version string is
34 * referenced by the include of global.php, etc. before it's defined.
35 * For that reason, bring in global.php AFTER we define the version strings.
37 include_once(SM_PATH
. 'functions/global.php');
40 * Appends citation markers to the string.
41 * Also appends a trailing space.
43 * @author Justus Pendleton
44 * @param string $str The string to append to
45 * @param int $citeLevel the number of markers to append
49 function sqMakeCite (&$str, $citeLevel) {
50 for ($i = 0; $i < $citeLevel; $i++
) {
53 if ($citeLevel != 0) {
59 * Create a newline in the string, adding citation
60 * markers to the newline as necessary.
62 * @author Justus Pendleton
63 * @param string $str the string to make a newline in
64 * @param int $citeLevel the citation level the newline is at
65 * @param int $column starting column of the newline
69 function sqMakeNewLine (&$str, $citeLevel, &$column) {
73 sqMakeCite ($str, $citeLevel);
74 $column = $citeLevel +
1;
81 * Checks for spaces in strings - only used if PHP doesn't have native ctype support
83 * You might be able to rewrite the function by adding short evaluation form.
86 * - iso-2022-xx charsets - hex 20 might be part of other symbol. I might
87 * be wrong. 0x20 is not used in iso-2022-jp. I haven't checked iso-2022-kr
88 * and iso-2022-cn mappings.
90 * - no-break space ( ) - it is 8bit symbol, that depends on charset.
91 * there are at least three different charset groups that have nbsp in
94 * I don't see any charset/nbsp options in php ctype either.
96 * @param string $string tested string
97 * @return bool true when only whitespace symbols are present in test string
100 function sm_ctype_space($string) {
101 if ( preg_match('/^[\x09-\x0D]|^\x20/', $string) ||
$string=='') {
109 * Wraps text at $wrap characters. While sqWordWrap takes
110 * a single line of text and wraps it, this function works
111 * on the entire corpus at once, this allows it to be a little
112 * bit smarter and when and how to wrap.
114 * @author Justus Pendleton
115 * @param string $body the entire body of text
116 * @param int $wrap the maximum line length
117 * @return string the wrapped text
120 function &sqBodyWrap (&$body, $wrap) {
121 //check for ctype support, and fake it if it doesn't exist
122 if (!function_exists('ctype_space')) {
123 function ctype_space ($string) {
124 return sm_ctype_space($string);
128 // the newly wrapped text
130 // current column since the last newline in the outstring
132 $length = sq_strlen($body);
133 // where we are in the original string
135 // the number of >>> citation markers we are currently at
138 // the main loop, whenever we start a newline of input text
139 // we start from here
140 while ($pos < $length) {
141 // we're at the beginning of a line, get the new cite level
144 while (($pos < $length) && (sq_substr($body,$pos,1) == '>')) {
148 // skip over any spaces interleaved among the cite markers
149 while (($pos < $length) && (sq_substr($body,$pos,1) == ' ')) {
154 if ($pos >= $length) {
159 // special case: if this is a blank line then maintain it
160 // (i.e. try to preserve original paragraph breaks)
161 // unless they occur at the very beginning of the text
162 if ((sq_substr($body,$pos,1) == "\n" ) && (sq_strlen($outString) != 0)) {
163 $outStringLast = $outString{sq_strlen($outString) - 1};
164 if ($outStringLast != "\n") {
167 sqMakeCite ($outString, $newCiteLevel);
174 // if the cite level has changed, then start a new line
175 // with the new cite level.
176 if (($citeLevel != $newCiteLevel) && ($pos > ($newCiteLevel +
1)) && ($outStringCol != 0)) {
177 sqMakeNewLine ($outString, 0, $outStringCol);
180 $citeLevel = $newCiteLevel;
182 // prepend the quote level if necessary
183 if ($outStringCol == 0) {
184 sqMakeCite ($outString, $citeLevel);
185 // if we added a citation then move the column
186 // out by citelevel + 1 (the cite markers + the space)
187 $outStringCol = $citeLevel +
($citeLevel ?
1 : 0);
188 } else if ($outStringCol > $citeLevel) {
189 // not a cite and we're not at the beginning of a line
190 // in the output. add a space to separate the new text
191 // from previous text.
196 // find the next newline -- we don't want to go further than that
197 $nextNewline = sq_strpos ($body, "\n", $pos);
198 if ($nextNewline === FALSE) {
199 $nextNewline = $length;
202 // Don't wrap unquoted lines at all. For now the textarea
203 // will work fine for this. Maybe revisit this later though
204 // (for completeness more than anything else, I think)
205 if ($citeLevel == 0) {
206 $outString .= sq_substr ($body, $pos, ($nextNewline - $pos));
207 $outStringCol = $nextNewline - $pos;
208 if ($nextNewline != $length) {
209 sqMakeNewLine ($outString, 0, $outStringCol);
211 $pos = $nextNewline +
1;
215 * Set this to false to stop appending short strings to previous lines
218 // inner loop, (obviously) handles wrapping up to
220 while ($pos < $nextNewline) {
221 // skip over initial spaces
222 while (($pos < $nextNewline) && (ctype_space (sq_substr($body,$pos,1)))) {
225 // if this is a short line then just append it and continue outer loop
226 if (($outStringCol +
$nextNewline - $pos) <= ($wrap - $citeLevel - 1) ) {
227 // if this is the final line in the input string then include
228 // any trailing newlines
229 // echo substr($body,$pos,$wrap). "<br />";
230 if (($nextNewline +
1 == $length) && (sq_substr($body,$nextNewline,1) == "\n")) {
234 // trim trailing spaces
235 $lastRealChar = $nextNewline;
236 while (($lastRealChar > $pos && $lastRealChar < $length) && (ctype_space (sq_substr($body,$lastRealChar,1)))) {
239 // decide if appending the short string is what we want
240 if (($nextNewline < $length && sq_substr($body,$nextNewline,1) == "\n") &&
241 isset($lastRealChar)) {
243 //check the first word:
244 while (($mypos < $length) && (sq_substr($body,$mypos,1) == '>')) {
246 // skip over any spaces interleaved among the cite markers
247 while (($mypos < $length) && (sq_substr($body,$mypos,1) == ' ')) {
253 if ($mypos == $nextNewline+1) {
254 while (($mypos < $length) && ($body{$mypos} == ' ')) {
260 $firstword = sq_substr($body,$mypos,sq_strpos($body,' ',$mypos) - $mypos);
261 //if ($dowrap || $ldnspacecnt > 1 || ($firstword && (
262 if (!$smartwrap ||
$firstword && (
263 $firstword{0} == '-' ||
264 $firstword{0} == '+' ||
265 $firstword{0} == '*' ||
266 sq_substr($firstword,0,1) == sq_strtoupper(sq_substr($firstword,0,1)) ||
267 strpos($firstword,':'))) {
268 $outString .= sq_substr($body,$pos,($lastRealChar - $pos+
1));
269 $outStringCol +
= ($lastRealChar - $pos);
270 sqMakeNewLine($outString,$citeLevel,$outStringCol);
279 $outString .= sq_substr ($body, $pos, ($lastRealChar - $pos +
1));
280 $outStringCol +
= ($lastRealChar - $pos);
281 $pos = $nextNewline +
1;
285 $eol = $pos +
$wrap - $citeLevel - $outStringCol;
286 // eol is the tentative end of line.
287 // look backwards for there for a whitespace to break at.
288 // if it's already less than our current position then
289 // our current line is already too long, break immediately
290 // and restart outer loop
292 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
296 // start looking backwards for whitespace to break at.
298 while (($breakPoint > $pos) && (! ctype_space (sq_substr($body,$breakPoint,1)))) {
302 // if we didn't find a breakpoint by looking backward then we
303 // need to figure out what to do about that
304 if ($breakPoint == $pos) {
305 // if we are not at the beginning then end this line
306 // and start a new loop
307 if ($outStringCol > ($citeLevel +
1)) {
308 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
311 // just hard break here. most likely we are breaking
312 // a really long URL. could also try searching
313 // forward for a break point, which is what Mozilla
314 // does. don't bother for now.
319 // special case: maybe we should have wrapped last
320 // time. if the first breakpoint here makes the
321 // current line too long and there is already text on
322 // the current line, break and loop again if at
323 // beginning of current line, don't force break
325 if ((($outStringCol +
($breakPoint - $pos)) > ($wrap +
$SLOP)) && ($outStringCol > ($citeLevel +
1))) {
326 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
330 // skip newlines or whitespace at the beginning of the string
331 $substring = sq_substr ($body, $pos, ($breakPoint - $pos));
332 $substring = rtrim ($substring); // do rtrim and ctype_space have the same ideas about whitespace?
333 $outString .= $substring;
334 $outStringCol +
= sq_strlen ($substring);
335 // advance past the whitespace which caused the wrap
337 while (($pos < $length) && (ctype_space (sq_substr($body,$pos,1)))) {
340 if ($pos < $length) {
341 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
350 * Wraps text at $wrap characters
352 * Has a problem with special HTML characters, so call this before
353 * you do character translation.
355 * Specifically, &#039; comes up as 5 characters instead of 1.
356 * This should not add newlines to the end of lines.
358 * @param string $line the line of text to wrap, by ref
359 * @param int $wrap the maximum line lenth
360 * @param string $charset name of charset used in $line string. Available since v.1.5.1.
364 function sqWordWrap(&$line, $wrap, $charset='') {
365 global $languages, $squirrelmail_language;
367 // Use custom wrapping function, if translation provides it
368 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
369 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap')) {
370 if (mb_detect_encoding($line) != 'ASCII') {
371 $line = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap', $line, $wrap);
376 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
377 $beginning_spaces = $regs[1];
378 if (isset($regs[2])) {
379 $words = explode(' ', $regs[2]);
385 $line = $beginning_spaces;
387 while ($i < count($words)) {
388 /* Force one word to be on a line (minimum) */
390 $line_len = strlen($beginning_spaces) +
sq_strlen($words[$i],$charset) +
2;
391 if (isset($words[$i +
1]))
392 $line_len +
= sq_strlen($words[$i +
1],$charset);
395 /* Add more words (as long as they fit) */
396 while ($line_len < $wrap && $i < count($words)) {
397 $line .= ' ' . $words[$i];
399 if (isset($words[$i]))
400 $line_len +
= sq_strlen($words[$i],$charset) +
1;
405 /* Skip spaces if they are the first thing on a continued line */
406 while (!isset($words[$i]) && $i < count($words)) {
410 /* Go to the next line if we have more to process */
411 if ($i < count($words)) {
418 * Does the opposite of sqWordWrap()
419 * @param string $body the text to un-wordwrap
423 function sqUnWordWrap(&$body) {
424 global $squirrelmail_language;
426 if ($squirrelmail_language == 'ja_JP') {
430 $lines = explode("\n", $body);
432 $PreviousSpaces = '';
433 $cnt = count($lines);
434 for ($i = 0; $i < $cnt; $i ++
) {
435 preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
436 $CurrentSpaces = $regs[1];
437 if (isset($regs[2])) {
438 $CurrentRest = $regs[2];
444 $PreviousSpaces = $CurrentSpaces;
446 } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
447 && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
448 && strlen($CurrentRest)) { /* and there's a line to continue with */
449 $body .= ' ' . $CurrentRest;
451 $body .= "\n" . $lines[$i];
452 $PreviousSpaces = $CurrentSpaces;
459 * If $haystack is a full mailbox name and $needle is the mailbox
460 * separator character, returns the last part of the mailbox name.
462 * @param string haystack full mailbox name to search
463 * @param string needle the mailbox separator character
464 * @return string the last part of the mailbox name
467 function readShortMailboxName($haystack, $needle) {
472 $parts = explode($needle, $haystack);
473 $elem = array_pop($parts);
474 while ($elem == '' && count($parts)) {
475 $elem = array_pop($parts);
484 * Creates an URL for the page calling this function, using either the PHP global
485 * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added.
487 * @return string the complete url for this page
490 function php_self () {
491 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER
) && !empty($req_uri) ) {
495 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER
) && !empty($php_self) ) {
497 // need to add query string to end of PHP_SELF to match REQUEST_URI
499 if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER
) && !empty($query_string) ) {
500 $php_self .= '?' . $query_string;
513 * Determines the location to forward to, relative to your server.
514 * This is used in HTTP Location: redirects.
515 * If this doesnt work correctly for you (although it should), you can
516 * remove all this code except the last two lines, and have it return
517 * the right URL for your site, something like:
519 * http://www.example.com/squirrelmail/
521 * @return string the base url for this SquirrelMail installation
524 function get_location () {
526 global $imap_server_type;
528 /* Get the path, handle virtual directories */
529 if(strpos(php_self(), '?')) {
530 $path = substr(php_self(), 0, strpos(php_self(), '?'));
534 $path = substr($path, 0, strrpos($path, '/'));
535 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION
) ) {
536 return $full_url . $path;
539 /* Check if this is a HTTPS or regular HTTP request. */
543 * If you have 'SSLOptions +StdEnvVars' in your apache config
544 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
545 * OR if you are on port 443
547 $getEnvVar = getenv('HTTPS');
548 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
549 (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER
) && !strcasecmp($https_on, 'on')) ||
550 (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER
) && $server_port == 443)) {
554 /* Get the hostname from the Host header or server config. */
555 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER
) ||
empty($host) ) {
556 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER
) ||
empty($host) ) {
562 if (! strstr($host, ':')) {
563 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER
)) {
564 if (($server_port != 80 && $proto == 'http://') ||
565 ($server_port != 443 && $proto == 'https://')) {
566 $port = sprintf(':%d', $server_port);
571 /* this is a workaround for the weird macosx caching that
572 causes Apache to return 16080 as the port number, which causes
575 if ($imap_server_type == 'macosx' && $port == ':16080') {
579 /* Fallback is to omit the server name and use a relative */
580 /* URI, although this is not RFC 2616 compliant. */
581 $full_url = ($host ?
$proto . $host . $port : '');
582 sqsession_register($full_url, 'sq_base_url');
583 return $full_url . $path;
590 * These functions are used to encrypt the password before it is
591 * stored in a cookie. The encryption key is generated by
592 * OneTimePadCreate();
594 * @param string $string the (password)string to encrypt
595 * @param string $epad the encryption key
596 * @return string the base64-encoded encrypted password
599 function OneTimePadEncrypt ($string, $epad) {
600 $pad = base64_decode($epad);
602 if (strlen($pad)>0) {
603 // make sure that pad is longer than string
604 while (strlen($string)>strlen($pad)) {
608 // FIXME: what should we do when $epad is not base64 encoded or empty.
612 for ($i = 0; $i < strlen ($string); $i++
) {
613 $encrypted .= chr (ord($string[$i]) ^
ord($pad[$i]));
616 return base64_encode($encrypted);
620 * Decrypts a password from the cookie
622 * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
623 * This uses the encryption key that is stored in the session.
625 * @param string $string the string to decrypt
626 * @param string $epad the encryption key from the session
627 * @return string the decrypted password
630 function OneTimePadDecrypt ($string, $epad) {
631 $pad = base64_decode($epad);
633 if (strlen($pad)>0) {
634 // make sure that pad is longer than string
635 while (strlen($string)>strlen($pad)) {
639 // FIXME: what should we do when $epad is not base64 encoded or empty.
642 $encrypted = base64_decode ($string);
644 for ($i = 0; $i < strlen ($encrypted); $i++
) {
645 $decrypted .= chr (ord($encrypted[$i]) ^
ord($pad[$i]));
653 * Randomizes the mt_rand() function.
655 * Toss this in strings or integers and it will seed the generator
656 * appropriately. With strings, it is better to get them long.
657 * Use md5() to lengthen smaller strings.
659 * @param mixed $val a value to seed the random number generator. mixed = integer or string.
663 function sq_mt_seed($Val) {
664 /* if mt_getrandmax() does not return a 2^n - 1 number,
665 this might not work well. This uses $Max as a bitmask. */
666 $Max = mt_getrandmax();
668 if (! is_int($Val)) {
680 mt_srand(($Val ^
mt_rand(0, $Max)) & $Max);
685 * Init random number generator
687 * This function initializes the random number generator fairly well.
688 * It also only initializes it once, so you don't accidentally get
689 * the same 'random' numbers twice in one session.
694 function sq_mt_randomize() {
702 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER
);
703 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER
);
704 sq_mt_seed((int)((double) microtime() * 1000000));
705 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
708 if (function_exists('getrusage')) {
709 /* Avoid warnings with Win32 */
711 if (isset($dat) && is_array($dat)) {
713 foreach ($dat as $k => $v)
717 sq_mt_seed(md5($Str));
721 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER
)) {
722 sq_mt_seed(md5($unique_id));
729 * Creates encryption key
731 * Creates an encryption key for encrypting the password stored in the cookie.
732 * The encryption key itself is stored in the session.
734 * Pad must be longer or equal to encoded string length in 1.4.4/1.5.0 and older.
735 * @param int $length optional, length of the string to generate
736 * @return string the encryption key
739 function OneTimePadCreate ($length=100) {
743 for ($i = 0; $i < $length; $i++
) {
744 $pad .= chr(mt_rand(0,255));
747 return base64_encode($pad);
751 * Returns a string showing the size of the message/attachment.
753 * @param int $bytes the filesize in bytes
754 * @return string the filesize in human readable format
757 function show_readable_size($bytes) {
761 if ($bytes / 1024 > 1) {
768 settype($bytes, 'integer');
771 settype($bytes, 'integer');
774 return $bytes . ' ' . $type;
778 * Generates a random string from the character set you pass in
780 * @param int $size the length of the string to generate
781 * @param string $chars a string containing the characters to use
782 * @param int $flags a flag to add a specific set to the characters to use:
784 * 1 = add lowercase a-z to $chars
785 * 2 = add uppercase A-Z to $chars
786 * 4 = add numbers 0-9 to $chars
787 * @return string the random string
790 function GenerateRandomString($size, $chars, $flags = 0) {
792 $chars .= 'abcdefghijklmnopqrstuvwxyz';
795 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
798 $chars .= '0123456789';
801 if (($size < 1) ||
(strlen($chars) < 1)) {
805 sq_mt_randomize(); /* Initialize the random number generator */
808 $j = strlen( $chars ) - 1;
809 while (strlen($String) < $size) {
810 $String .= $chars{mt_rand(0, $j)};
817 * Escapes special characters for use in IMAP commands.
819 * @param string $str the string to escape
820 * @return string the escaped string
823 function quoteimap($str) {
824 return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
830 * Trims every element in the array, ie. remove the first char of each element
831 * @param array $array the array to trim
834 function TrimArray(&$array) {
835 foreach ($array as $k => $v) {
838 foreach ($
$k as $k2 => $v2) {
839 $
$k[$k2] = substr($v2, 1);
845 /* Re-assign back to array. */
851 * Create compose link
853 * Returns a link to the compose-page, taking in consideration
854 * the compose_in_new and javascript settings.
855 * @param string $url the URL to the compose page
856 * @param string $text the link text, default "Compose"
857 * @param string $target (since 1.4.3) url target
858 * @return string a link to the compose page
861 function makeComposeLink($url, $text = null, $target='') {
862 global $compose_new_win,$javascript_on, $compose_width, $compose_height;
865 $text = _("Compose");
868 // if not using "compose in new window", make
869 // regular link and be done with it
870 if($compose_new_win != '1') {
871 return makeInternalLink($url, $text, $target);
874 // build the compose in new window link...
877 // if javascript is on, use onclick event to handle it
879 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION
);
880 $compuri = $base_uri.$url;
881 return "<a href=\"javascript:void(0)\" onclick=\"comp_in_new('$compuri','$compose_width','$compose_height')\">$text</a>";
884 // otherwise, just open new window using regular HTML
885 return makeInternalLink($url, $text, '_blank');
891 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
893 * Debugging function - does the same as print_r, but makes sure special
894 * characters are converted to htmlentities first. This will allow
895 * values like <some@email.address> to be displayed.
896 * The output is wrapped in <<pre>> and <</pre>> tags.
897 * Since 1.4.2 accepts unlimited number of arguments.
901 function sm_print_r() {
902 ob_start(); // Buffer output
903 foreach(func_get_args() as $var) {
906 // php has get_class_methods function that can print class methods
907 if (is_object($var)) {
908 // get class methods if $var is object
909 $aMethods=get_class_methods(get_class($var));
910 // make sure that $aMethods is array and array is not empty
911 if (is_array($aMethods) && $aMethods!=array()) {
912 echo "Object methods:\n";
913 foreach($aMethods as $method) {
914 echo '* ' . $method . "\n";
920 $buffer = ob_get_contents(); // Grab the print_r output
921 ob_end_clean(); // Silently discard the output & stop buffering
922 print '<div align="left"><pre>';
923 print htmlentities($buffer);
924 print '</pre></div>';
928 * version of fwrite which checks for failure
929 * @param resource $fp
930 * @param string $string
931 * @return number of written bytes. false on failure
934 function sq_fwrite($fp, $string) {
936 $count = @fwrite
($fp,$string);
937 // the number of bytes written should be the length of the string
938 if($count != strlen($string)) {
946 * sq_get_html_translation_table
948 * Returns the translation table used by sq_htmlentities()
950 * @param integer $table html translation table. Possible values (without quotes):
952 * <li>HTML_ENTITIES - full html entities table defined by charset</li>
953 * <li>HTML_SPECIALCHARS - html special characters table</li>
955 * @param integer $quote_style quote encoding style. Possible values (without quotes):
957 * <li>ENT_COMPAT - (default) encode double quotes</li>
958 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
959 * <li>ENT_QUOTES - encode double and single quotes</li>
961 * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
962 * @return array html translation array
965 function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT
,$charset='us-ascii') {
966 global $default_charset;
968 if ($table == HTML_SPECIALCHARS
) $charset='us-ascii';
970 // Start array with ampersand
971 $sq_html_ent_table = array( "&" => '&' );
974 $sq_html_ent_table = array_merge($sq_html_ent_table,
979 if ($quote_style == ENT_COMPAT
)
980 $sq_html_ent_table = array_merge($sq_html_ent_table,
981 array("\"" => '"')
984 // double and single quotes
985 if ($quote_style == ENT_QUOTES
)
986 $sq_html_ent_table = array_merge($sq_html_ent_table,
987 array("\"" => '"',
991 if ($charset=='auto') $charset=$default_charset;
993 // add entities that depend on charset
996 include_once(SM_PATH
. 'functions/htmlentities/iso-8859-1.php');
999 include_once(SM_PATH
. 'functions/htmlentities/utf-8.php');
1006 return $sq_html_ent_table;
1012 * Convert all applicable characters to HTML entities.
1013 * Minimal php requirement - v.4.0.5.
1015 * Function is designed for people that want to use full power of htmlentities() in
1018 * @param string $string string that has to be sanitized
1019 * @param integer $quote_style quote encoding style. Possible values (without quotes):
1021 * <li>ENT_COMPAT - (default) encode double quotes</li>
1022 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
1023 * <li>ENT_QUOTES - encode double and single quotes</li>
1025 * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
1026 * @return string sanitized string
1029 function sq_htmlentities($string,$quote_style=ENT_COMPAT
,$charset='us-ascii') {
1030 // get translation table
1031 $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES
,$quote_style,$charset);
1032 // convert characters
1033 return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
1037 * Tests if string contains 8bit symbols.
1039 * If charset is not set, function defaults to default_charset.
1040 * $default_charset global must be set correctly if $charset is
1042 * @param string $string tested string
1043 * @param string $charset charset used in a string
1044 * @return bool true if 8bit symbols are detected
1045 * @since 1.5.1 and 1.4.4
1047 function sq_is8bit($string,$charset='') {
1048 global $default_charset;
1050 if ($charset=='') $charset=$default_charset;
1053 * Don't use \240 in ranges. Sometimes RH 7.2 doesn't like it.
1054 * Don't use \200-\237 for iso-8859-x charsets. This range
1055 * stores control symbols in those charsets.
1056 * Use preg_match instead of ereg in order to avoid problems
1057 * with mbstring overloading
1059 if (preg_match("/^iso-8859/i",$charset)) {
1060 $needle='/\240|[\241-\377]/';
1062 $needle='/[\200-\237]|\240|[\241-\377]/';
1064 return preg_match("$needle",$string);
1068 * Replacement of mb_list_encodings function
1070 * This function provides replacement for function that is available only
1071 * in php 5.x. Function does not test all mbstring encodings. Only the ones
1072 * that might be used in SM translations.
1074 * Supported strings are stored in session in order to reduce number of
1075 * mb_internal_encoding function calls.
1077 * If you want to test all mbstring encodings - fill $list_of_encodings
1079 * @return array list of encodings supported by php mbstring extension
1082 function sq_mb_list_encodings() {
1083 if (! function_exists('mb_internal_encoding'))
1087 if (function_exists('mb_list_encodings')) {
1088 $ret = mb_list_encodings();
1089 array_walk($ret,'sq_lowercase_array_vals');
1093 // don't try to test encodings, if they are already stored in session
1094 if (sqgetGlobalVar('mb_supported_encodings',$mb_supported_encodings,SQ_SESSION
))
1095 return $mb_supported_encodings;
1097 // save original encoding
1098 $orig_encoding=mb_internal_encoding();
1100 $list_of_encoding=array(
1126 $supported_encodings=array();
1128 foreach ($list_of_encoding as $encoding) {
1129 // try setting encodings. suppress warning messages
1130 if (@mb_internal_encoding
($encoding))
1131 $supported_encodings[]=$encoding;
1134 // restore original encoding
1135 mb_internal_encoding($orig_encoding);
1137 // register list in session
1138 sqsession_register($supported_encodings,'mb_supported_encodings');
1140 return $supported_encodings;
1144 * Callback function used to lowercase array values.
1145 * @param string $val array value
1146 * @param mixed $key array key
1149 function sq_lowercase_array_vals(&$val,$key) {
1150 $val = strtolower($val);
1155 * Function returns number of characters in string.
1157 * Returned number might be different from number of bytes in string,
1158 * if $charset is multibyte charset. Detection depends on mbstring
1159 * functions. If mbstring does not support tested multibyte charset,
1160 * vanilla string length function is used.
1161 * @param string $str string
1162 * @param string $charset charset
1164 * @return integer number of characters in string
1166 function sq_strlen($str, $charset=null){
1168 if (is_null($charset)) return strlen($str);
1170 // lowercase charset name
1171 $charset=strtolower($charset);
1173 // use automatic charset detection, if function call asks for it
1174 if ($charset=='auto') {
1175 global $default_charset;
1177 $charset=$default_charset;
1180 // Use mbstring only with listed charsets
1181 $aList_of_mb_charsets=array('utf-8','big5','gb2312','gb18030','euc-jp','euc-cn','euc-tw','euc-kr');
1183 // calculate string length according to charset
1184 if (in_array($charset,$aList_of_mb_charsets) && in_array($charset,sq_mb_list_encodings())) {
1185 $real_length = mb_strlen($str,$charset);
1187 // own strlen detection code is removed because missing strpos,
1188 // strtoupper and substr implementations break string wrapping.
1189 $real_length=strlen($str);
1191 return $real_length;
1195 * string padding with multibyte support
1197 * @link http://www.php.net/str_pad
1198 * @param string $string original string
1199 * @param integer $width padded string width
1200 * @param string $pad padding symbols
1201 * @param integer $padtype padding type
1202 * (internal php defines, see str_pad() description)
1203 * @param string $charset charset used in original string
1204 * @return string padded string
1206 function sq_str_pad($string, $width, $pad, $padtype, $charset='') {
1208 $charset = strtolower($charset);
1209 $padded_string = '';
1217 * all multibyte charsets try to increase width value by
1218 * adding difference between number of bytes and real length
1220 $width = $width - sq_strlen($string,$charset) +
strlen($string);
1222 $padded_string=str_pad($string,$width,$pad,$padtype);
1224 return $padded_string;
1228 * Wrapper that is used to switch between vanilla and multibyte substr
1230 * @param string $string
1231 * @param integer $start
1232 * @param integer $length
1233 * @param string $charset
1236 * @link http://www.php.net/substr
1237 * @link http://www.php.net/mb_substr
1239 function sq_substr($string,$start,$length,$charset='auto') {
1240 // use automatic charset detection, if function call asks for it
1241 if ($charset=='auto') {
1242 global $default_charset;
1244 $charset=$default_charset;
1246 $charset = strtolower($charset);
1247 if (function_exists('mb_internal_encoding') &&
1248 in_array($charset,sq_mb_list_encodings())) {
1249 return mb_substr($string,$start,$length,$charset);
1251 // TODO: add mbstring independent code
1253 // use vanilla string functions as last option
1254 return substr($string,$start,$length);
1258 * Wrapper that is used to switch between vanilla and multibyte strpos
1260 * @param string $haystack
1261 * @param mixed $needle
1262 * @param integer $offset
1263 * @param string $charset
1266 * @link http://www.php.net/strpos
1267 * @link http://www.php.net/mb_strpos
1269 function sq_strpos($haystack,$needle,$offset,$charset='auto') {
1270 // use automatic charset detection, if function call asks for it
1271 if ($charset=='auto') {
1272 global $default_charset;
1274 $charset=$default_charset;
1276 $charset = strtolower($charset);
1277 if (function_exists('mb_internal_encoding') &&
1278 in_array($charset,sq_mb_list_encodings())) {
1279 return mb_strpos($haystack,$needle,$offset,$charset);
1281 // TODO: add mbstring independent code
1283 // use vanilla string functions as last option
1284 return strpos($haystack,$needle,$offset);
1288 * Wrapper that is used to switch between vanilla and multibyte strtoupper
1290 * @param string $string
1291 * @param string $charset
1294 * @link http://www.php.net/strtoupper
1295 * @link http://www.php.net/mb_strtoupper
1297 function sq_strtoupper($string,$charset='auto') {
1298 // use automatic charset detection, if function call asks for it
1299 if ($charset=='auto') {
1300 global $default_charset;
1302 $charset=$default_charset;
1304 $charset = strtolower($charset);
1305 if (function_exists('mb_strtoupper') &&
1306 in_array($charset,sq_mb_list_encodings())) {
1307 return mb_strtoupper($string,$charset);
1309 // TODO: add mbstring independent code
1311 // use vanilla string functions as last option
1312 return strtoupper($string);
1314 $PHP_SELF = php_self();