6 * This code provides various string manipulation functions that are
7 * used by the rest of the SquirrelMail code.
9 * @copyright © 1999-2006 The SquirrelMail Project Team
10 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
12 * @package squirrelmail
16 * Appends citation markers to the string.
17 * Also appends a trailing space.
19 * @author Justus Pendleton
20 * @param string $str The string to append to
21 * @param int $citeLevel the number of markers to append
25 function sqMakeCite (&$str, $citeLevel) {
26 for ($i = 0; $i < $citeLevel; $i++
) {
29 if ($citeLevel != 0) {
35 * Create a newline in the string, adding citation
36 * markers to the newline as necessary.
38 * @author Justus Pendleton
39 * @param string $str the string to make a newline in
40 * @param int $citeLevel the citation level the newline is at
41 * @param int $column starting column of the newline
45 function sqMakeNewLine (&$str, $citeLevel, &$column) {
49 sqMakeCite ($str, $citeLevel);
50 $column = $citeLevel +
1;
57 * Checks for spaces in strings - only used if PHP doesn't have native ctype support
59 * You might be able to rewrite the function by adding short evaluation form.
62 * - iso-2022-xx charsets - hex 20 might be part of other symbol. I might
63 * be wrong. 0x20 is not used in iso-2022-jp. I haven't checked iso-2022-kr
64 * and iso-2022-cn mappings.
66 * - no-break space ( ) - it is 8bit symbol, that depends on charset.
67 * there are at least three different charset groups that have nbsp in
70 * I don't see any charset/nbsp options in php ctype either.
72 * @param string $string tested string
73 * @return bool true when only whitespace symbols are present in test string
76 function sm_ctype_space($string) {
77 if ( preg_match('/^[\x09-\x0D]|^\x20/', $string) ||
$string=='') {
85 * Wraps text at $wrap characters. While sqWordWrap takes
86 * a single line of text and wraps it, this function works
87 * on the entire corpus at once, this allows it to be a little
88 * bit smarter and when and how to wrap.
90 * @author Justus Pendleton
91 * @param string $body the entire body of text
92 * @param int $wrap the maximum line length
93 * @return string the wrapped text
96 function &sqBodyWrap (&$body, $wrap) {
97 //check for ctype support, and fake it if it doesn't exist
98 if (!function_exists('ctype_space')) {
99 function ctype_space ($string) {
100 return sm_ctype_space($string);
104 // the newly wrapped text
106 // current column since the last newline in the outstring
108 $length = sq_strlen($body);
109 // where we are in the original string
111 // the number of >>> citation markers we are currently at
114 // the main loop, whenever we start a newline of input text
115 // we start from here
116 while ($pos < $length) {
117 // we're at the beginning of a line, get the new cite level
120 while (($pos < $length) && (sq_substr($body,$pos,1) == '>')) {
124 // skip over any spaces interleaved among the cite markers
125 while (($pos < $length) && (sq_substr($body,$pos,1) == ' ')) {
130 if ($pos >= $length) {
135 // special case: if this is a blank line then maintain it
136 // (i.e. try to preserve original paragraph breaks)
137 // unless they occur at the very beginning of the text
138 if ((sq_substr($body,$pos,1) == "\n" ) && (sq_strlen($outString) != 0)) {
139 $outStringLast = $outString{sq_strlen($outString) - 1};
140 if ($outStringLast != "\n") {
143 sqMakeCite ($outString, $newCiteLevel);
150 // if the cite level has changed, then start a new line
151 // with the new cite level.
152 if (($citeLevel != $newCiteLevel) && ($pos > ($newCiteLevel +
1)) && ($outStringCol != 0)) {
153 sqMakeNewLine ($outString, 0, $outStringCol);
156 $citeLevel = $newCiteLevel;
158 // prepend the quote level if necessary
159 if ($outStringCol == 0) {
160 sqMakeCite ($outString, $citeLevel);
161 // if we added a citation then move the column
162 // out by citelevel + 1 (the cite markers + the space)
163 $outStringCol = $citeLevel +
($citeLevel ?
1 : 0);
164 } else if ($outStringCol > $citeLevel) {
165 // not a cite and we're not at the beginning of a line
166 // in the output. add a space to separate the new text
167 // from previous text.
172 // find the next newline -- we don't want to go further than that
173 $nextNewline = sq_strpos ($body, "\n", $pos);
174 if ($nextNewline === FALSE) {
175 $nextNewline = $length;
178 // Don't wrap unquoted lines at all. For now the textarea
179 // will work fine for this. Maybe revisit this later though
180 // (for completeness more than anything else, I think)
181 if ($citeLevel == 0) {
182 $outString .= sq_substr ($body, $pos, ($nextNewline - $pos));
183 $outStringCol = $nextNewline - $pos;
184 if ($nextNewline != $length) {
185 sqMakeNewLine ($outString, 0, $outStringCol);
187 $pos = $nextNewline +
1;
191 * Set this to false to stop appending short strings to previous lines
194 // inner loop, (obviously) handles wrapping up to
196 while ($pos < $nextNewline) {
197 // skip over initial spaces
198 while (($pos < $nextNewline) && (ctype_space (sq_substr($body,$pos,1)))) {
201 // if this is a short line then just append it and continue outer loop
202 if (($outStringCol +
$nextNewline - $pos) <= ($wrap - $citeLevel - 1) ) {
203 // if this is the final line in the input string then include
204 // any trailing newlines
205 // echo substr($body,$pos,$wrap). "<br />";
206 if (($nextNewline +
1 == $length) && (sq_substr($body,$nextNewline,1) == "\n")) {
210 // trim trailing spaces
211 $lastRealChar = $nextNewline;
212 while (($lastRealChar > $pos && $lastRealChar < $length) && (ctype_space (sq_substr($body,$lastRealChar,1)))) {
215 // decide if appending the short string is what we want
216 if (($nextNewline < $length && sq_substr($body,$nextNewline,1) == "\n") &&
217 isset($lastRealChar)) {
219 //check the first word:
220 while (($mypos < $length) && (sq_substr($body,$mypos,1) == '>')) {
222 // skip over any spaces interleaved among the cite markers
223 while (($mypos < $length) && (sq_substr($body,$mypos,1) == ' ')) {
229 if ($mypos == $nextNewline+1) {
230 while (($mypos < $length) && ($body{$mypos} == ' ')) {
236 $firstword = sq_substr($body,$mypos,sq_strpos($body,' ',$mypos) - $mypos);
237 //if ($dowrap || $ldnspacecnt > 1 || ($firstword && (
238 if (!$smartwrap ||
$firstword && (
239 $firstword{0} == '-' ||
240 $firstword{0} == '+' ||
241 $firstword{0} == '*' ||
242 sq_substr($firstword,0,1) == sq_strtoupper(sq_substr($firstword,0,1)) ||
243 strpos($firstword,':'))) {
244 $outString .= sq_substr($body,$pos,($lastRealChar - $pos+
1));
245 $outStringCol +
= ($lastRealChar - $pos);
246 sqMakeNewLine($outString,$citeLevel,$outStringCol);
255 $outString .= sq_substr ($body, $pos, ($lastRealChar - $pos +
1));
256 $outStringCol +
= ($lastRealChar - $pos);
257 $pos = $nextNewline +
1;
261 $eol = $pos +
$wrap - $citeLevel - $outStringCol;
262 // eol is the tentative end of line.
263 // look backwards for there for a whitespace to break at.
264 // if it's already less than our current position then
265 // our current line is already too long, break immediately
266 // and restart outer loop
268 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
272 // start looking backwards for whitespace to break at.
274 while (($breakPoint > $pos) && (! ctype_space (sq_substr($body,$breakPoint,1)))) {
278 // if we didn't find a breakpoint by looking backward then we
279 // need to figure out what to do about that
280 if ($breakPoint == $pos) {
281 // if we are not at the beginning then end this line
282 // and start a new loop
283 if ($outStringCol > ($citeLevel +
1)) {
284 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
287 // just hard break here. most likely we are breaking
288 // a really long URL. could also try searching
289 // forward for a break point, which is what Mozilla
290 // does. don't bother for now.
295 // special case: maybe we should have wrapped last
296 // time. if the first breakpoint here makes the
297 // current line too long and there is already text on
298 // the current line, break and loop again if at
299 // beginning of current line, don't force break
301 if ((($outStringCol +
($breakPoint - $pos)) > ($wrap +
$SLOP)) && ($outStringCol > ($citeLevel +
1))) {
302 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
306 // skip newlines or whitespace at the beginning of the string
307 $substring = sq_substr ($body, $pos, ($breakPoint - $pos));
308 $substring = rtrim ($substring); // do rtrim and ctype_space have the same ideas about whitespace?
309 $outString .= $substring;
310 $outStringCol +
= sq_strlen ($substring);
311 // advance past the whitespace which caused the wrap
313 while (($pos < $length) && (ctype_space (sq_substr($body,$pos,1)))) {
316 if ($pos < $length) {
317 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
326 * Wraps text at $wrap characters
328 * Has a problem with special HTML characters, so call this before
329 * you do character translation.
331 * Specifically, &#039; comes up as 5 characters instead of 1.
332 * This should not add newlines to the end of lines.
334 * @param string $line the line of text to wrap, by ref
335 * @param int $wrap the maximum line lenth
336 * @param string $charset name of charset used in $line string. Available since v.1.5.1.
340 function sqWordWrap(&$line, $wrap, $charset='') {
341 global $languages, $squirrelmail_language;
343 // Use custom wrapping function, if translation provides it
344 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
345 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap')) {
346 if (mb_detect_encoding($line) != 'ASCII') {
347 $line = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap', $line, $wrap);
352 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
353 $beginning_spaces = $regs[1];
354 if (isset($regs[2])) {
355 $words = explode(' ', $regs[2]);
361 $line = $beginning_spaces;
363 while ($i < count($words)) {
364 /* Force one word to be on a line (minimum) */
366 $line_len = strlen($beginning_spaces) +
sq_strlen($words[$i],$charset) +
2;
367 if (isset($words[$i +
1]))
368 $line_len +
= sq_strlen($words[$i +
1],$charset);
371 /* Add more words (as long as they fit) */
372 while ($line_len < $wrap && $i < count($words)) {
373 $line .= ' ' . $words[$i];
375 if (isset($words[$i]))
376 $line_len +
= sq_strlen($words[$i],$charset) +
1;
381 /* Skip spaces if they are the first thing on a continued line */
382 while (!isset($words[$i]) && $i < count($words)) {
386 /* Go to the next line if we have more to process */
387 if ($i < count($words)) {
394 * Does the opposite of sqWordWrap()
395 * @param string $body the text to un-wordwrap
399 function sqUnWordWrap(&$body) {
400 global $squirrelmail_language;
402 if ($squirrelmail_language == 'ja_JP') {
406 $lines = explode("\n", $body);
408 $PreviousSpaces = '';
409 $cnt = count($lines);
410 for ($i = 0; $i < $cnt; $i ++
) {
411 preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
412 $CurrentSpaces = $regs[1];
413 if (isset($regs[2])) {
414 $CurrentRest = $regs[2];
420 $PreviousSpaces = $CurrentSpaces;
422 } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
423 && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
424 && strlen($CurrentRest)) { /* and there's a line to continue with */
425 $body .= ' ' . $CurrentRest;
427 $body .= "\n" . $lines[$i];
428 $PreviousSpaces = $CurrentSpaces;
435 * If $haystack is a full mailbox name and $needle is the mailbox
436 * separator character, returns the last part of the mailbox name.
438 * @param string haystack full mailbox name to search
439 * @param string needle the mailbox separator character
440 * @return string the last part of the mailbox name
443 function readShortMailboxName($haystack, $needle) {
448 $parts = explode($needle, $haystack);
449 $elem = array_pop($parts);
450 while ($elem == '' && count($parts)) {
451 $elem = array_pop($parts);
461 * Determines the location to forward to, relative to your server.
462 * This is used in HTTP Location: redirects.
463 * If this doesnt work correctly for you (although it should), you can
464 * remove all this code except the last two lines, and have it return
465 * the right URL for your site, something like:
467 * http://www.example.com/squirrelmail/
469 * @return string the base url for this SquirrelMail installation
472 function get_location () {
474 global $imap_server_type;
476 /* Get the path, handle virtual directories */
477 if(strpos(php_self(), '?')) {
478 $path = substr(php_self(), 0, strpos(php_self(), '?'));
482 $path = substr($path, 0, strrpos($path, '/'));
483 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION
) ) {
484 return $full_url . $path;
487 /* Check if this is a HTTPS or regular HTTP request. */
491 * If you have 'SSLOptions +StdEnvVars' in your apache config
492 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
493 * OR if you are on port 443
495 $getEnvVar = getenv('HTTPS');
496 if ((isset($getEnvVar) && strcasecmp($getEnvVar, 'on') === 0) ||
497 (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER
) && strcasecmp($https_on, 'on') === 0) ||
498 (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER
) && $server_port == 443)) {
502 /* Get the hostname from the Host header or server config. */
503 if ( !sqgetGlobalVar('HTTP_X_FORWARDED_HOST', $host, SQ_SERVER
) ||
empty($host) ) {
504 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER
) ||
empty($host) ) {
505 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER
) ||
empty($host) ) {
512 if (! strstr($host, ':')) {
513 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER
)) {
514 if (($server_port != 80 && $proto == 'http://') ||
515 ($server_port != 443 && $proto == 'https://')) {
516 $port = sprintf(':%d', $server_port);
521 /* this is a workaround for the weird macosx caching that
522 causes Apache to return 16080 as the port number, which causes
525 if ($imap_server_type == 'macosx' && $port == ':16080') {
529 /* Fallback is to omit the server name and use a relative */
530 /* URI, although this is not RFC 2616 compliant. */
531 $full_url = ($host ?
$proto . $host . $port : '');
532 sqsession_register($full_url, 'sq_base_url');
533 return $full_url . $path;
540 * These functions are used to encrypt the password before it is
541 * stored in a cookie. The encryption key is generated by
542 * OneTimePadCreate();
544 * @param string $string the (password)string to encrypt
545 * @param string $epad the encryption key
546 * @return string the base64-encoded encrypted password
549 function OneTimePadEncrypt ($string, $epad) {
550 $pad = base64_decode($epad);
552 if (strlen($pad)>0) {
553 // make sure that pad is longer than string
554 while (strlen($string)>strlen($pad)) {
558 // FIXME: what should we do when $epad is not base64 encoded or empty.
562 for ($i = 0; $i < strlen ($string); $i++
) {
563 $encrypted .= chr (ord($string[$i]) ^
ord($pad[$i]));
566 return base64_encode($encrypted);
570 * Decrypts a password from the cookie
572 * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
573 * This uses the encryption key that is stored in the session.
575 * @param string $string the string to decrypt
576 * @param string $epad the encryption key from the session
577 * @return string the decrypted password
580 function OneTimePadDecrypt ($string, $epad) {
581 $pad = base64_decode($epad);
583 if (strlen($pad)>0) {
584 // make sure that pad is longer than string
585 while (strlen($string)>strlen($pad)) {
589 // FIXME: what should we do when $epad is not base64 encoded or empty.
592 $encrypted = base64_decode ($string);
594 for ($i = 0; $i < strlen ($encrypted); $i++
) {
595 $decrypted .= chr (ord($encrypted[$i]) ^
ord($pad[$i]));
603 * Randomizes the mt_rand() function.
605 * Toss this in strings or integers and it will seed the generator
606 * appropriately. With strings, it is better to get them long.
607 * Use md5() to lengthen smaller strings.
609 * @param mixed $val a value to seed the random number generator. mixed = integer or string.
613 function sq_mt_seed($Val) {
614 /* if mt_getrandmax() does not return a 2^n - 1 number,
615 this might not work well. This uses $Max as a bitmask. */
616 $Max = mt_getrandmax();
618 if (! is_int($Val)) {
630 mt_srand(($Val ^
mt_rand(0, $Max)) & $Max);
635 * Init random number generator
637 * This function initializes the random number generator fairly well.
638 * It also only initializes it once, so you don't accidentally get
639 * the same 'random' numbers twice in one session.
644 function sq_mt_randomize() {
652 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER
);
653 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER
);
654 sq_mt_seed((int)((double) microtime() * 1000000));
655 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
658 if (function_exists('getrusage')) {
659 /* Avoid warnings with Win32 */
661 if (isset($dat) && is_array($dat)) {
663 foreach ($dat as $k => $v)
667 sq_mt_seed(md5($Str));
671 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER
)) {
672 sq_mt_seed(md5($unique_id));
679 * Creates encryption key
681 * Creates an encryption key for encrypting the password stored in the cookie.
682 * The encryption key itself is stored in the session.
684 * Pad must be longer or equal to encoded string length in 1.4.4/1.5.0 and older.
685 * @param int $length optional, length of the string to generate
686 * @return string the encryption key
689 function OneTimePadCreate ($length=100) {
693 for ($i = 0; $i < $length; $i++
) {
694 $pad .= chr(mt_rand(0,255));
697 return base64_encode($pad);
701 * Returns a string showing the size of the message/attachment.
703 * @param int $bytes the filesize in bytes
704 * @return string the filesize in human readable format
707 function show_readable_size($bytes) {
711 if ($bytes / 1024 > 1) {
718 settype($bytes, 'integer');
721 settype($bytes, 'integer');
724 return $bytes . ' ' . $type;
728 * Generates a random string from the character set you pass in
730 * @param int $size the length of the string to generate
731 * @param string $chars a string containing the characters to use
732 * @param int $flags a flag to add a specific set to the characters to use:
734 * 1 = add lowercase a-z to $chars
735 * 2 = add uppercase A-Z to $chars
736 * 4 = add numbers 0-9 to $chars
737 * @return string the random string
740 function GenerateRandomString($size, $chars, $flags = 0) {
742 $chars .= 'abcdefghijklmnopqrstuvwxyz';
745 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
748 $chars .= '0123456789';
751 if (($size < 1) ||
(strlen($chars) < 1)) {
755 sq_mt_randomize(); /* Initialize the random number generator */
758 $j = strlen( $chars ) - 1;
759 while (strlen($String) < $size) {
760 $String .= $chars{mt_rand(0, $j)};
767 * Escapes special characters for use in IMAP commands.
769 * @param string $str the string to escape
770 * @return string the escaped string
773 function quoteimap($str) {
774 return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
780 * Trims every element in the array, ie. remove the first char of each element
781 * @param array $array the array to trim
784 function TrimArray(&$array) {
785 foreach ($array as $k => $v) {
788 foreach ($
$k as $k2 => $v2) {
789 $
$k[$k2] = substr($v2, 1);
795 /* Re-assign back to array. */
801 * Create compose link
803 * Returns a link to the compose-page, taking in consideration
804 * the compose_in_new and javascript settings.
805 * @param string $url the URL to the compose page
806 * @param string $text the link text, default "Compose"
807 * @param string $target (since 1.4.3) url target
808 * @return string a link to the compose page
811 function makeComposeLink($url, $text = null, $target='') {
812 global $compose_new_win,$javascript_on, $compose_width, $compose_height;
815 $text = _("Compose");
818 // if not using "compose in new window", make
819 // regular link and be done with it
820 if($compose_new_win != '1') {
821 return makeInternalLink($url, $text, $target);
824 // build the compose in new window link...
827 // if javascript is on, use onclick event to handle it
829 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION
);
830 $compuri = SM_BASE_URI
.$url;
831 return "<a href=\"javascript:void(0)\" onclick=\"comp_in_new('$compuri','$compose_width','$compose_height')\">$text</a>";
834 // otherwise, just open new window using regular HTML
835 return makeInternalLink($url, $text, '_blank');
841 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
843 * Debugging function - does the same as print_r, but makes sure special
844 * characters are converted to htmlentities first. This will allow
845 * values like <some@email.address> to be displayed.
846 * The output is wrapped in <<pre>> and <</pre>> tags.
847 * Since 1.4.2 accepts unlimited number of arguments.
851 function sm_print_r() {
852 ob_start(); // Buffer output
853 foreach(func_get_args() as $var) {
856 // php has get_class_methods function that can print class methods
857 if (is_object($var)) {
858 // get class methods if $var is object
859 $aMethods=get_class_methods(get_class($var));
860 // make sure that $aMethods is array and array is not empty
861 if (is_array($aMethods) && $aMethods!=array()) {
862 echo "Object methods:\n";
863 foreach($aMethods as $method) {
864 echo '* ' . $method . "\n";
870 $buffer = ob_get_contents(); // Grab the print_r output
871 ob_end_clean(); // Silently discard the output & stop buffering
872 print '<div align="left"><pre>';
873 print htmlentities($buffer);
874 print '</pre></div>';
878 * version of fwrite which checks for failure
879 * @param resource $fp
880 * @param string $string
881 * @return number of written bytes. false on failure
884 function sq_fwrite($fp, $string) {
886 $count = @fwrite
($fp,$string);
887 // the number of bytes written should be the length of the string
888 if($count != strlen($string)) {
896 * sq_get_html_translation_table
898 * Returns the translation table used by sq_htmlentities()
900 * @param integer $table html translation table. Possible values (without quotes):
902 * <li>HTML_ENTITIES - full html entities table defined by charset</li>
903 * <li>HTML_SPECIALCHARS - html special characters table</li>
905 * @param integer $quote_style quote encoding style. Possible values (without quotes):
907 * <li>ENT_COMPAT - (default) encode double quotes</li>
908 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
909 * <li>ENT_QUOTES - encode double and single quotes</li>
911 * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
912 * @return array html translation array
915 function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT
,$charset='us-ascii') {
916 global $default_charset;
918 if ($table == HTML_SPECIALCHARS
) $charset='us-ascii';
920 // Start array with ampersand
921 $sq_html_ent_table = array( "&" => '&' );
924 $sq_html_ent_table = array_merge($sq_html_ent_table,
929 if ($quote_style == ENT_COMPAT
)
930 $sq_html_ent_table = array_merge($sq_html_ent_table,
931 array("\"" => '"')
934 // double and single quotes
935 if ($quote_style == ENT_QUOTES
)
936 $sq_html_ent_table = array_merge($sq_html_ent_table,
937 array("\"" => '"',
941 if ($charset=='auto') $charset=$default_charset;
943 // add entities that depend on charset
946 include_once(SM_PATH
. 'functions/htmlentities/iso-8859-1.php');
949 include_once(SM_PATH
. 'functions/htmlentities/utf-8.php');
956 return $sq_html_ent_table;
962 * Convert all applicable characters to HTML entities.
963 * Minimal php requirement - v.4.0.5.
965 * Function is designed for people that want to use full power of htmlentities() in
968 * @param string $string string that has to be sanitized
969 * @param integer $quote_style quote encoding style. Possible values (without quotes):
971 * <li>ENT_COMPAT - (default) encode double quotes</li>
972 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
973 * <li>ENT_QUOTES - encode double and single quotes</li>
975 * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
976 * @return string sanitized string
979 function sq_htmlentities($string,$quote_style=ENT_COMPAT
,$charset='us-ascii') {
980 // get translation table
981 $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES
,$quote_style,$charset);
982 // convert characters
983 return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
987 * Tests if string contains 8bit symbols.
989 * If charset is not set, function defaults to default_charset.
990 * $default_charset global must be set correctly if $charset is
992 * @param string $string tested string
993 * @param string $charset charset used in a string
994 * @return bool true if 8bit symbols are detected
995 * @since 1.5.1 and 1.4.4
997 function sq_is8bit($string,$charset='') {
998 global $default_charset;
1000 if ($charset=='') $charset=$default_charset;
1003 * Don't use \240 in ranges. Sometimes RH 7.2 doesn't like it.
1004 * Don't use \200-\237 for iso-8859-x charsets. This range
1005 * stores control symbols in those charsets.
1006 * Use preg_match instead of ereg in order to avoid problems
1007 * with mbstring overloading
1009 if (preg_match("/^iso-8859/i",$charset)) {
1010 $needle='/\240|[\241-\377]/';
1012 $needle='/[\200-\237]|\240|[\241-\377]/';
1014 return preg_match("$needle",$string);
1018 * Replacement of mb_list_encodings function
1020 * This function provides replacement for function that is available only
1021 * in php 5.x. Function does not test all mbstring encodings. Only the ones
1022 * that might be used in SM translations.
1024 * Supported strings are stored in session in order to reduce number of
1025 * mb_internal_encoding function calls.
1027 * If you want to test all mbstring encodings - fill $list_of_encodings
1029 * @return array list of encodings supported by php mbstring extension
1030 * @since 1.5.1 and 1.4.6
1032 function sq_mb_list_encodings() {
1033 if (! function_exists('mb_internal_encoding'))
1037 if (function_exists('mb_list_encodings')) {
1038 $ret = mb_list_encodings();
1039 array_walk($ret,'sq_lowercase_array_vals');
1043 // don't try to test encodings, if they are already stored in session
1044 if (sqgetGlobalVar('mb_supported_encodings',$mb_supported_encodings,SQ_SESSION
))
1045 return $mb_supported_encodings;
1047 // save original encoding
1048 $orig_encoding=mb_internal_encoding();
1050 $list_of_encoding=array(
1079 $supported_encodings=array();
1081 foreach ($list_of_encoding as $encoding) {
1082 // try setting encodings. suppress warning messages
1083 if (@mb_internal_encoding
($encoding))
1084 $supported_encodings[]=$encoding;
1087 // restore original encoding
1088 mb_internal_encoding($orig_encoding);
1090 // register list in session
1091 sqsession_register($supported_encodings,'mb_supported_encodings');
1093 return $supported_encodings;
1097 * Callback function used to lowercase array values.
1098 * @param string $val array value
1099 * @param mixed $key array key
1100 * @since 1.5.1 and 1.4.6
1102 function sq_lowercase_array_vals(&$val,$key) {
1103 $val = strtolower($val);
1108 * Function returns number of characters in string.
1110 * Returned number might be different from number of bytes in string,
1111 * if $charset is multibyte charset. Detection depends on mbstring
1112 * functions. If mbstring does not support tested multibyte charset,
1113 * vanilla string length function is used.
1114 * @param string $str string
1115 * @param string $charset charset
1116 * @since 1.5.1 and 1.4.6
1117 * @return integer number of characters in string
1119 function sq_strlen($str, $charset=null){
1121 if (is_null($charset)) return strlen($str);
1123 // lowercase charset name
1124 $charset=strtolower($charset);
1126 // use automatic charset detection, if function call asks for it
1127 if ($charset=='auto') {
1128 global $default_charset, $squirrelmail_language;
1130 $charset=$default_charset;
1131 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
1134 // Use mbstring only with listed charsets
1135 $aList_of_mb_charsets=array('utf-8','big5','gb2312','gb18030','euc-jp','euc-cn','euc-tw','euc-kr');
1137 // calculate string length according to charset
1138 if (in_array($charset,$aList_of_mb_charsets) && in_array($charset,sq_mb_list_encodings())) {
1139 $real_length = mb_strlen($str,$charset);
1141 // own strlen detection code is removed because missing strpos,
1142 // strtoupper and substr implementations break string wrapping.
1143 $real_length=strlen($str);
1145 return $real_length;
1149 * string padding with multibyte support
1151 * @link http://www.php.net/str_pad
1152 * @param string $string original string
1153 * @param integer $width padded string width
1154 * @param string $pad padding symbols
1155 * @param integer $padtype padding type
1156 * (internal php defines, see str_pad() description)
1157 * @param string $charset charset used in original string
1158 * @return string padded string
1160 function sq_str_pad($string, $width, $pad, $padtype, $charset='') {
1162 $charset = strtolower($charset);
1163 $padded_string = '';
1171 * all multibyte charsets try to increase width value by
1172 * adding difference between number of bytes and real length
1174 $width = $width - sq_strlen($string,$charset) +
strlen($string);
1176 $padded_string=str_pad($string,$width,$pad,$padtype);
1178 return $padded_string;
1182 * Wrapper that is used to switch between vanilla and multibyte substr
1184 * @param string $string
1185 * @param integer $start
1186 * @param integer $length
1187 * @param string $charset
1190 * @link http://www.php.net/substr
1191 * @link http://www.php.net/mb_substr
1193 function sq_substr($string,$start,$length,$charset='auto') {
1194 // use automatic charset detection, if function call asks for it
1195 if ($charset=='auto') {
1196 global $default_charset, $squirrelmail_language;
1198 $charset=$default_charset;
1199 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
1201 $charset = strtolower($charset);
1202 if (function_exists('mb_internal_encoding') &&
1203 in_array($charset,sq_mb_list_encodings())) {
1204 return mb_substr($string,$start,$length,$charset);
1206 // TODO: add mbstring independent code
1208 // use vanilla string functions as last option
1209 return substr($string,$start,$length);
1213 * Wrapper that is used to switch between vanilla and multibyte strpos
1215 * @param string $haystack
1216 * @param mixed $needle
1217 * @param integer $offset
1218 * @param string $charset
1221 * @link http://www.php.net/strpos
1222 * @link http://www.php.net/mb_strpos
1224 function sq_strpos($haystack,$needle,$offset,$charset='auto') {
1225 // use automatic charset detection, if function call asks for it
1226 if ($charset=='auto') {
1227 global $default_charset, $squirrelmail_language;
1229 $charset=$default_charset;
1230 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
1232 $charset = strtolower($charset);
1233 if (function_exists('mb_internal_encoding') &&
1234 in_array($charset,sq_mb_list_encodings())) {
1235 return mb_strpos($haystack,$needle,$offset,$charset);
1237 // TODO: add mbstring independent code
1239 // use vanilla string functions as last option
1240 return strpos($haystack,$needle,$offset);
1244 * Wrapper that is used to switch between vanilla and multibyte strtoupper
1246 * @param string $string
1247 * @param string $charset
1250 * @link http://www.php.net/strtoupper
1251 * @link http://www.php.net/mb_strtoupper
1253 function sq_strtoupper($string,$charset='auto') {
1254 // use automatic charset detection, if function call asks for it
1255 if ($charset=='auto') {
1256 global $default_charset,$squirrelmail_language;
1258 $charset=$default_charset;
1259 if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
1261 $charset = strtolower($charset);
1262 if (function_exists('mb_strtoupper') &&
1263 in_array($charset,sq_mb_list_encodings())) {
1264 return mb_strtoupper($string,$charset);
1266 // TODO: add mbstring independent code
1268 // use vanilla string functions as last option
1269 return strtoupper($string);
1273 * Counts 8bit bytes in string
1274 * @param string $string tested string
1275 * @return integer number of 8bit bytes
1277 function sq_count8bit($string) {
1279 for ($i=0; $i<strlen($string); $i++
) {
1280 if (ord($string[$i]) > 127) $count++
;
1286 * Callback function to trim whitespace from a value, to be used in array_walk
1287 * @param string $value value to trim
1288 * @since 1.5.2 and 1.4.7
1290 function sq_trim_value ( &$value ) {
1291 $value = trim($value);