ea6291259edfdf887d6b846708b417b51fdb29ca
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 * SquirrelMail version number -- DO NOT CHANGE
20 $version = '1.5.1 [CVS]';
23 * SquirrelMail internal version number -- DO NOT CHANGE
24 * $sm_internal_version = array (release, major, minor)
26 global $SQM_INTERNAL_VERSION;
27 $SQM_INTERNAL_VERSION = array(1,5,1);
30 * There can be a circular issue with includes, where the $version string is
31 * referenced by the include of global.php, etc. before it's defined.
32 * For that reason, bring in global.php AFTER we define the version strings.
34 require_once(SM_PATH
. 'functions/global.php');
37 * Appends citation markers to the string.
38 * Also appends a trailing space.
40 * @author Justus Pendleton
42 * @param string str The string to append to
43 * @param int citeLevel the number of markers to append
46 function sqMakeCite (&$str, $citeLevel) {
47 for ($i = 0; $i < $citeLevel; $i++
) {
50 if ($citeLevel != 0) {
56 * Create a newline in the string, adding citation
57 * markers to the newline as necessary.
59 * @author Justus Pendleton
61 * @param string str the string to make a newline in
62 * @param int citeLevel the citation level the newline is at
63 * @param int column starting column of the newline
66 function sqMakeNewLine (&$str, $citeLevel, &$column) {
70 sqMakeCite ($str, $citeLevel);
71 $column = $citeLevel +
1;
78 * Checks for spaces in strings - only used if PHP doesn't have native ctype support
80 * You might be able to rewrite the function by adding short evaluation form.
83 * - iso-2022-xx charsets - hex 20 might be part of other symbol. I might
84 * be wrong. 0x20 is not used in iso-2022-jp. I haven't checked iso-2022-kr
85 * and iso-2022-cn mappings.
87 * - no-break space ( ) - it is 8bit symbol, that depends on charset.
88 * there are at least three different charset groups that have nbsp in
91 * I don't see any charset/nbsp options in php ctype either.
93 * @param string $string tested string
94 * @return bool true when only whitespace symbols are present in test string
96 function sm_ctype_space($string) {
97 if ( preg_match('/^[\x09-\x0D]|^\x20/', $string) ||
$string=='') {
105 * Wraps text at $wrap characters. While sqWordWrap takes
106 * a single line of text and wraps it, this function works
107 * on the entire corpus at once, this allows it to be a little
108 * bit smarter and when and how to wrap.
110 * @author Justus Pendleton
112 * @param string body the entire body of text
113 * @param int wrap the maximum line length
114 * @return string the wrapped text
116 function &sqBodyWrap (&$body, $wrap) {
117 //check for ctype support, and fake it if it doesn't exist
118 if (!function_exists('ctype_space')) {
119 function ctype_space ($string) {
120 return sm_ctype_space($string);
124 // the newly wrapped text
126 // current column since the last newline in the outstring
128 $length = sq_strlen($body);
129 // where we are in the original string
131 // the number of >>> citation markers we are currently at
134 // the main loop, whenever we start a newline of input text
135 // we start from here
136 while ($pos < $length) {
137 // we're at the beginning of a line, get the new cite level
140 while (($pos < $length) && (sq_substr($body,$pos,1) == '>')) {
144 // skip over any spaces interleaved among the cite markers
145 while (($pos < $length) && (sq_substr($body,$pos,1) == ' ')) {
150 if ($pos >= $length) {
155 // special case: if this is a blank line then maintain it
156 // (i.e. try to preserve original paragraph breaks)
157 // unless they occur at the very beginning of the text
158 if ((sq_substr($body,$pos,1) == "\n" ) && (sq_strlen($outString) != 0)) {
159 $outStringLast = $outString{sq_strlen($outString) - 1};
160 if ($outStringLast != "\n") {
163 sqMakeCite ($outString, $newCiteLevel);
170 // if the cite level has changed, then start a new line
171 // with the new cite level.
172 if (($citeLevel != $newCiteLevel) && ($pos > ($newCiteLevel +
1)) && ($outStringCol != 0)) {
173 sqMakeNewLine ($outString, 0, $outStringCol);
176 $citeLevel = $newCiteLevel;
178 // prepend the quote level if necessary
179 if ($outStringCol == 0) {
180 sqMakeCite ($outString, $citeLevel);
181 // if we added a citation then move the column
182 // out by citelevel + 1 (the cite markers + the space)
183 $outStringCol = $citeLevel +
($citeLevel ?
1 : 0);
184 } else if ($outStringCol > $citeLevel) {
185 // not a cite and we're not at the beginning of a line
186 // in the output. add a space to separate the new text
187 // from previous text.
192 // find the next newline -- we don't want to go further than that
193 $nextNewline = sq_strpos ($body, "\n", $pos);
194 if ($nextNewline === FALSE) {
195 $nextNewline = $length;
198 // Don't wrap unquoted lines at all. For now the textarea
199 // will work fine for this. Maybe revisit this later though
200 // (for completeness more than anything else, I think)
201 if ($citeLevel == 0) {
202 $outString .= sq_substr ($body, $pos, ($nextNewline - $pos));
203 $outStringCol = $nextNewline - $pos;
204 if ($nextNewline != $length) {
205 sqMakeNewLine ($outString, 0, $outStringCol);
207 $pos = $nextNewline +
1;
211 * Set this to false to stop appending short strings to previous lines
214 // inner loop, (obviously) handles wrapping up to
216 while ($pos < $nextNewline) {
217 // skip over initial spaces
218 while (($pos < $nextNewline) && (ctype_space (sq_substr($body,$pos,1)))) {
221 // if this is a short line then just append it and continue outer loop
222 if (($outStringCol +
$nextNewline - $pos) <= ($wrap - $citeLevel - 1) ) {
223 // if this is the final line in the input string then include
224 // any trailing newlines
225 // echo substr($body,$pos,$wrap). "<br />";
226 if (($nextNewline +
1 == $length) && (sq_substr($body,$nextNewline,1) == "\n")) {
230 // trim trailing spaces
231 $lastRealChar = $nextNewline;
232 while (($lastRealChar > $pos && $lastRealChar < $length) && (ctype_space (sq_substr($body,$lastRealChar,1)))) {
235 // decide if appending the short string is what we want
236 if (($nextNewline < $length && sq_substr($body,$nextNewline,1) == "\n") &&
237 isset($lastRealChar)) {
239 //check the first word:
240 while (($mypos < $length) && (sq_substr($body,$mypos,1) == '>')) {
242 // skip over any spaces interleaved among the cite markers
243 while (($mypos < $length) && (sq_substr($body,$mypos,1) == ' ')) {
249 if ($mypos == $nextNewline+1) {
250 while (($mypos < $length) && ($body{$mypos} == ' ')) {
256 $firstword = sq_substr($body,$mypos,sq_strpos($body,' ',$mypos) - $mypos);
257 //if ($dowrap || $ldnspacecnt > 1 || ($firstword && (
258 if (!$smartwrap ||
$firstword && (
259 $firstword{0} == '-' ||
260 $firstword{0} == '+' ||
261 $firstword{0} == '*' ||
262 sq_substr($firstword,0,1) == sq_strtoupper(sq_substr($firstword,0,1)) ||
263 strpos($firstword,':'))) {
264 $outString .= sq_substr($body,$pos,($lastRealChar - $pos+
1));
265 $outStringCol +
= ($lastRealChar - $pos);
266 sqMakeNewLine($outString,$citeLevel,$outStringCol);
275 $outString .= sq_substr ($body, $pos, ($lastRealChar - $pos +
1));
276 $outStringCol +
= ($lastRealChar - $pos);
277 $pos = $nextNewline +
1;
281 $eol = $pos +
$wrap - $citeLevel - $outStringCol;
282 // eol is the tentative end of line.
283 // look backwards for there for a whitespace to break at.
284 // if it's already less than our current position then
285 // our current line is already too long, break immediately
286 // and restart outer loop
288 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
292 // start looking backwards for whitespace to break at.
294 while (($breakPoint > $pos) && (! ctype_space (sq_substr($body,$breakPoint,1)))) {
298 // if we didn't find a breakpoint by looking backward then we
299 // need to figure out what to do about that
300 if ($breakPoint == $pos) {
301 // if we are not at the beginning then end this line
302 // and start a new loop
303 if ($outStringCol > ($citeLevel +
1)) {
304 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
307 // just hard break here. most likely we are breaking
308 // a really long URL. could also try searching
309 // forward for a break point, which is what Mozilla
310 // does. don't bother for now.
315 // special case: maybe we should have wrapped last
316 // time. if the first breakpoint here makes the
317 // current line too long and there is already text on
318 // the current line, break and loop again if at
319 // beginning of current line, don't force break
321 if ((($outStringCol +
($breakPoint - $pos)) > ($wrap +
$SLOP)) && ($outStringCol > ($citeLevel +
1))) {
322 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
326 // skip newlines or whitespace at the beginning of the string
327 $substring = sq_substr ($body, $pos, ($breakPoint - $pos));
328 $substring = rtrim ($substring); // do rtrim and ctype_space have the same ideas about whitespace?
329 $outString .= $substring;
330 $outStringCol +
= sq_strlen ($substring);
331 // advance past the whitespace which caused the wrap
333 while (($pos < $length) && (ctype_space (sq_substr($body,$pos,1)))) {
336 if ($pos < $length) {
337 sqMakeNewLine ($outString, $citeLevel, $outStringCol);
346 * Wraps text at $wrap characters
348 * Has a problem with special HTML characters, so call this before
349 * you do character translation.
351 * Specifically, &#039; comes up as 5 characters instead of 1.
352 * This should not add newlines to the end of lines.
354 * @param string line the line of text to wrap, by ref
355 * @param int wrap the maximum line lenth
356 * @param string charset name of charset used in $line string. Available since v.1.5.1.
359 function sqWordWrap(&$line, $wrap, $charset='') {
360 global $languages, $squirrelmail_language;
362 // Use custom wrapping function, if translation provides it
363 if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
364 function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap')) {
365 if (mb_detect_encoding($line) != 'ASCII') {
366 $line = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap', $line, $wrap);
371 ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
372 $beginning_spaces = $regs[1];
373 if (isset($regs[2])) {
374 $words = explode(' ', $regs[2]);
380 $line = $beginning_spaces;
382 while ($i < count($words)) {
383 /* Force one word to be on a line (minimum) */
385 $line_len = strlen($beginning_spaces) +
sq_strlen($words[$i],$charset) +
2;
386 if (isset($words[$i +
1]))
387 $line_len +
= sq_strlen($words[$i +
1],$charset);
390 /* Add more words (as long as they fit) */
391 while ($line_len < $wrap && $i < count($words)) {
392 $line .= ' ' . $words[$i];
394 if (isset($words[$i]))
395 $line_len +
= sq_strlen($words[$i],$charset) +
1;
400 /* Skip spaces if they are the first thing on a continued line */
401 while (!isset($words[$i]) && $i < count($words)) {
405 /* Go to the next line if we have more to process */
406 if ($i < count($words)) {
413 * Does the opposite of sqWordWrap()
414 * @param string body the text to un-wordwrap
417 function sqUnWordWrap(&$body) {
418 global $squirrelmail_language;
420 if ($squirrelmail_language == 'ja_JP') {
424 $lines = explode("\n", $body);
426 $PreviousSpaces = '';
427 $cnt = count($lines);
428 for ($i = 0; $i < $cnt; $i ++
) {
429 preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
430 $CurrentSpaces = $regs[1];
431 if (isset($regs[2])) {
432 $CurrentRest = $regs[2];
438 $PreviousSpaces = $CurrentSpaces;
440 } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
441 && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
442 && strlen($CurrentRest)) { /* and there's a line to continue with */
443 $body .= ' ' . $CurrentRest;
445 $body .= "\n" . $lines[$i];
446 $PreviousSpaces = $CurrentSpaces;
453 * If $haystack is a full mailbox name and $needle is the mailbox
454 * separator character, returns the last part of the mailbox name.
456 * @param string haystack full mailbox name to search
457 * @param string needle the mailbox separator character
458 * @return string the last part of the mailbox name
460 function readShortMailboxName($haystack, $needle) {
465 $parts = explode($needle, $haystack);
466 $elem = array_pop($parts);
467 while ($elem == '' && count($parts)) {
468 $elem = array_pop($parts);
477 * Creates an URL for the page calling this function, using either the PHP global
478 * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added.
480 * @return string the complete url for this page
482 function php_self () {
483 if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER
) && !empty($req_uri) ) {
487 if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER
) && !empty($php_self) ) {
489 // need to add query string to end of PHP_SELF to match REQUEST_URI
491 if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER
) && !empty($query_string) ) {
492 $php_self .= '?' . $query_string;
505 * Determines the location to forward to, relative to your server.
506 * This is used in HTTP Location: redirects.
507 * If this doesnt work correctly for you (although it should), you can
508 * remove all this code except the last two lines, and have it return
509 * the right URL for your site, something like:
511 * http://www.example.com/squirrelmail/
513 * @return string the base url for this SquirrelMail installation
515 function get_location () {
517 global $imap_server_type;
519 /* Get the path, handle virtual directories */
520 if(strpos(php_self(), '?')) {
521 $path = substr(php_self(), 0, strpos(php_self(), '?'));
525 $path = substr($path, 0, strrpos($path, '/'));
526 if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION
) ) {
527 return $full_url . $path;
530 /* Check if this is a HTTPS or regular HTTP request. */
534 * If you have 'SSLOptions +StdEnvVars' in your apache config
535 * OR if you have HTTPS=on in your HTTP_SERVER_VARS
536 * OR if you are on port 443
538 $getEnvVar = getenv('HTTPS');
539 if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
540 (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER
) && !strcasecmp($https_on, 'on')) ||
541 (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER
) && $server_port == 443)) {
545 /* Get the hostname from the Host header or server config. */
546 if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER
) ||
empty($host) ) {
547 if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER
) ||
empty($host) ) {
553 if (! strstr($host, ':')) {
554 if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER
)) {
555 if (($server_port != 80 && $proto == 'http://') ||
556 ($server_port != 443 && $proto == 'https://')) {
557 $port = sprintf(':%d', $server_port);
562 /* this is a workaround for the weird macosx caching that
563 causes Apache to return 16080 as the port number, which causes
566 if ($imap_server_type == 'macosx' && $port == ':16080') {
570 /* Fallback is to omit the server name and use a relative */
571 /* URI, although this is not RFC 2616 compliant. */
572 $full_url = ($host ?
$proto . $host . $port : '');
573 sqsession_register($full_url, 'sq_base_url');
574 return $full_url . $path;
581 * These functions are used to encrypt the password before it is
582 * stored in a cookie. The encryption key is generated by
583 * OneTimePadCreate();
585 * @param string string the (password)string to encrypt
586 * @param string epad the encryption key
587 * @return string the base64-encoded encrypted password
589 function OneTimePadEncrypt ($string, $epad) {
590 $pad = base64_decode($epad);
592 for ($i = 0; $i < strlen ($string); $i++
) {
593 $encrypted .= chr (ord($string[$i]) ^
ord($pad[$i]));
596 return base64_encode($encrypted);
600 * Decrypts a password from the cookie
602 * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
603 * This uses the encryption key that is stored in the session.
605 * @param string string the string to decrypt
606 * @param string epad the encryption key from the session
607 * @return string the decrypted password
609 function OneTimePadDecrypt ($string, $epad) {
610 $pad = base64_decode($epad);
611 $encrypted = base64_decode ($string);
613 for ($i = 0; $i < strlen ($encrypted); $i++
) {
614 $decrypted .= chr (ord($encrypted[$i]) ^
ord($pad[$i]));
622 * Randomizes the mt_rand() function.
624 * Toss this in strings or integers and it will seed the generator
625 * appropriately. With strings, it is better to get them long.
626 * Use md5() to lengthen smaller strings.
628 * @param mixed val a value to seed the random number generator
631 function sq_mt_seed($Val) {
632 /* if mt_getrandmax() does not return a 2^n - 1 number,
633 this might not work well. This uses $Max as a bitmask. */
634 $Max = mt_getrandmax();
636 if (! is_int($Val)) {
648 mt_srand(($Val ^
mt_rand(0, $Max)) & $Max);
653 * Init random number generator
655 * This function initializes the random number generator fairly well.
656 * It also only initializes it once, so you don't accidentally get
657 * the same 'random' numbers twice in one session.
661 function sq_mt_randomize() {
669 sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER
);
670 sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER
);
671 sq_mt_seed((int)((double) microtime() * 1000000));
672 sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
675 if (function_exists('getrusage')) {
676 /* Avoid warnings with Win32 */
678 if (isset($dat) && is_array($dat)) {
680 foreach ($dat as $k => $v)
684 sq_mt_seed(md5($Str));
688 if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER
)) {
689 sq_mt_seed(md5($unique_id));
696 * Creates encryption key
698 * Creates an encryption key for encrypting the password stored in the cookie.
699 * The encryption key itself is stored in the session.
701 * @param int length optional, length of the string to generate
702 * @return string the encryption key
704 function OneTimePadCreate ($length=100) {
708 for ($i = 0; $i < $length; $i++
) {
709 $pad .= chr(mt_rand(0,255));
712 return base64_encode($pad);
716 * Returns a string showing the size of the message/attachment.
718 * @param int bytes the filesize in bytes
719 * @return string the filesize in human readable format
721 function show_readable_size($bytes) {
725 if ($bytes / 1024 > 1) {
732 settype($bytes, 'integer');
735 settype($bytes, 'integer');
738 return $bytes . ' ' . $type;
742 * Generates a random string from the character set you pass in
744 * @param int size the size of the string to generate
745 * @param string chars a string containing the characters to use
746 * @param int flags a flag to add a specific set to the characters to use:
748 * 1 = add lowercase a-z to $chars
749 * 2 = add uppercase A-Z to $chars
750 * 4 = add numbers 0-9 to $chars
751 * @return string the random string
753 function GenerateRandomString($size, $chars, $flags = 0) {
755 $chars .= 'abcdefghijklmnopqrstuvwxyz';
758 $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
761 $chars .= '0123456789';
764 if (($size < 1) ||
(strlen($chars) < 1)) {
768 sq_mt_randomize(); /* Initialize the random number generator */
771 $j = strlen( $chars ) - 1;
772 while (strlen($String) < $size) {
773 $String .= $chars{mt_rand(0, $j)};
780 * Escapes special characters for use in IMAP commands.
782 * @param string the string to escape
783 * @return string the escaped string
785 function quoteimap($str) {
786 return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
792 * Trims every element in the array, ie. remove the first char of each element
793 * @param array array the array to trim
795 function TrimArray(&$array) {
796 foreach ($array as $k => $v) {
799 foreach ($
$k as $k2 => $v2) {
800 $
$k[$k2] = substr($v2, 1);
806 /* Re-assign back to array. */
812 * Create compose link
814 * Returns a link to the compose-page, taking in consideration
815 * the compose_in_new and javascript settings.
816 * @param string url the URL to the compose page
817 * @param string text the link text, default "Compose"
818 * @return string a link to the compose page
820 function makeComposeLink($url, $text = null, $target='')
822 global $compose_new_win,$javascript_on;
825 $text = _("Compose");
829 // if not using "compose in new window", make
830 // regular link and be done with it
831 if($compose_new_win != '1') {
832 return makeInternalLink($url, $text, $target);
836 // build the compose in new window link...
839 // if javascript is on, use onclick event to handle it
841 sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION
);
842 return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
846 // otherwise, just open new window using regular HTML
847 return makeInternalLink($url, $text, '_blank');
854 * sm_print_r($some_variable, [$some_other_variable [, ...]]);
856 * Debugging function - does the same as print_r, but makes sure special
857 * characters are converted to htmlentities first. This will allow
858 * values like <some@email.address> to be displayed.
859 * The output is wrapped in <<pre>> and <</pre>> tags.
860 * Since 1.4.2 accepts unlimited number of arguments.
865 function sm_print_r() {
866 ob_start(); // Buffer output
867 foreach(func_get_args() as $var) {
870 // php has get_class_methods function that can print class methods
871 if (is_object($var)) {
872 // get class methods if $var is object
873 $aMethods=get_class_methods(get_class($var));
874 // make sure that $aMethods is array and array is not empty
875 if (is_array($aMethods) && $aMethods!=array()) {
876 echo "Object methods:\n";
877 foreach($aMethods as $method) {
878 echo '* ' . $method . "\n";
884 $buffer = ob_get_contents(); // Grab the print_r output
885 ob_end_clean(); // Silently discard the output & stop buffering
886 print '<div align="left"><pre>';
887 print htmlentities($buffer);
888 print '</pre></div>';
892 * version of fwrite which checks for failure
894 function sq_fwrite($fp, $string) {
896 $count = @fwrite
($fp,$string);
897 // the number of bytes written should be the length of the string
898 if($count != strlen($string)) {
906 * sq_get_html_translation_table
908 * Returns the translation table used by sq_htmlentities()
910 * @param integer $table html translation table. Possible values (without quotes):
912 * <li>HTML_ENTITIES - full html entities table defined by charset</li>
913 * <li>HTML_SPECIALCHARS - html special characters table</li>
915 * @param integer $quote_style quote encoding style. Possible values (without quotes):
917 * <li>ENT_COMPAT - (default) encode double quotes</li>
918 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
919 * <li>ENT_QUOTES - encode double and single quotes</li>
921 * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
922 * @return array html translation array
924 function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT
,$charset='us-ascii') {
925 global $default_charset;
927 if ($table == HTML_SPECIALCHARS
) $charset='us-ascii';
929 // Start array with ampersand
930 $sq_html_ent_table = array( "&" => '&' );
933 $sq_html_ent_table = array_merge($sq_html_ent_table,
938 if ($quote_style == ENT_COMPAT
)
939 $sq_html_ent_table = array_merge($sq_html_ent_table,
940 array("\"" => '"')
943 // double and single quotes
944 if ($quote_style == ENT_QUOTES
)
945 $sq_html_ent_table = array_merge($sq_html_ent_table,
946 array("\"" => '"',
950 if ($charset=='auto') $charset=$default_charset;
952 // add entities that depend on charset
955 include_once(SM_PATH
. 'functions/htmlentities/iso-8859-1.php');
958 include_once(SM_PATH
. 'functions/htmlentities/utf-8.php');
965 return $sq_html_ent_table;
971 * Convert all applicable characters to HTML entities.
972 * Minimal php requirement - v.4.0.5.
974 * Function is designed for people that want to use full power of htmlentities() in
977 * @param string $string string that has to be sanitized
978 * @param integer $quote_style quote encoding style. Possible values (without quotes):
980 * <li>ENT_COMPAT - (default) encode double quotes</li>
981 * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
982 * <li>ENT_QUOTES - encode double and single quotes</li>
984 * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
985 * @return string sanitized string
987 function sq_htmlentities($string,$quote_style=ENT_COMPAT
,$charset='us-ascii') {
988 // get translation table
989 $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES
,$quote_style,$charset);
990 // convert characters
991 return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
995 * Tests if string contains 8bit symbols.
997 * If charset is not set, function defaults to default_charset.
998 * $default_charset global must be set correctly if $charset is
1000 * @param string $string tested string
1001 * @param string $charset charset used in a string
1002 * @return bool true if 8bit symbols are detected
1003 * @since 1.5.1 and 1.4.4
1005 function sq_is8bit($string,$charset='') {
1006 global $default_charset;
1008 if ($charset=='') $charset=$default_charset;
1011 * Don't use \240 in ranges. Sometimes RH 7.2 doesn't like it.
1012 * Don't use \200-\237 for iso-8859-x charsets. This range
1013 * stores control symbols in those charsets.
1014 * Use preg_match instead of ereg in order to avoid problems
1015 * with mbstring overloading
1017 if (preg_match("/^iso-8859/i",$charset)) {
1018 $needle='/\240|[\241-\377]/';
1020 $needle='/[\200-\237]|\240|[\241-\377]/';
1022 return preg_match("$needle",$string);
1026 * Replacement of mb_list_encodings function
1028 * This function provides replacement for function that is available only
1029 * in php 5.x. Function does not test all mbstring encodings. Only the ones
1030 * that might be used in SM translations.
1032 * Supported strings are stored in session in order to reduce number of
1033 * mb_internal_encoding function calls.
1035 * If you want to test all mbstring encodings - fill $list_of_encodings
1037 * @return array list of encodings supported by php mbstring extension
1040 function sq_mb_list_encodings() {
1041 if (! function_exists('mb_internal_encoding'))
1044 // don't try to test encodings, if they are already stored in session
1045 if (sqgetGlobalVar('mb_supported_encodings',$mb_supported_encodings,SQ_SESSION
))
1046 return $mb_supported_encodings;
1048 // save original encoding
1049 $orig_encoding=mb_internal_encoding();
1051 $list_of_encoding=array(
1077 $supported_encodings=array();
1079 foreach ($list_of_encoding as $encoding) {
1080 // try setting encodings. suppress warning messages
1081 if (@mb_internal_encoding
($encoding))
1082 $supported_encodings[]=$encoding;
1085 // restore original encoding
1086 mb_internal_encoding($orig_encoding);
1088 // register list in session
1089 sqsession_register($supported_encodings,'mb_supported_encodings');
1091 return $supported_encodings;
1095 * Function returns number of characters in string.
1097 * Returned number might be different from number of bytes in string,
1098 * if $charset is multibyte charset. Detection depends on mbstring
1099 * functions. If mbstring does not support tested multibyte charset,
1100 * vanilla string length function is used.
1101 * @param string $str string
1102 * @param string $charset charset
1104 * @return integer number of characters in string
1106 function sq_strlen($str, $charset=''){
1108 if ($charset=='') return strlen($str);
1110 // use automatic charset detection, if function call asks for it
1111 if ($charset=='auto') {
1112 global $default_charset;
1114 $charset=$default_charset;
1117 // lowercase charset name
1118 $charset=strtolower($charset);
1120 // Use mbstring only with listed charsets
1121 $aList_of_mb_charsets=array('utf-8','big5','gb2312','gb18030','euc-jp','euc-cn','euc-tw','euc-kr');
1123 // calculate string length according to charset
1124 if (in_array($charset,$aList_of_mb_charsets) && in_array($charset,sq_mb_list_encodings())) {
1125 $real_length = mb_strlen($str,$charset);
1127 // own strlen detection code is removed because missing strpos,
1128 // strtoupper and substr implementations break string wrapping.
1129 $real_length=strlen($str);
1131 return $real_length;
1135 * string padding with multibyte support
1137 * @link http://www.php.net/str_pad
1138 * @param string $string original string
1139 * @param integer $width padded string width
1140 * @param string $pad padding symbols
1141 * @param integer $padtype padding type
1142 * (internal php defines, see str_pad() description)
1143 * @param string $charset charset used in original string
1144 * @return string padded string
1146 function sq_str_pad($string, $width, $pad, $padtype, $charset='') {
1148 $charset = strtolower($charset);
1149 $padded_string = '';
1157 * all multibyte charsets try to increase width value by
1158 * adding difference between number of bytes and real length
1160 $width = $width - sq_strlen($string,$charset) +
strlen($string);
1162 $padded_string=str_pad($string,$width,$pad,$padtype);
1164 return $padded_string;
1168 * Wrapper that is used to switch between vanilla and multibyte substr
1170 * @param string $string
1171 * @param integer $start
1172 * @param integer $length
1173 * @param string $charset
1176 * @link http://www.php.net/substr
1177 * @link http://www.php.net/mb_substr
1179 function sq_substr($string,$start,$length,$charset='auto') {
1180 // use automatic charset detection, if function call asks for it
1181 if ($charset=='auto') {
1182 global $default_charset;
1184 $charset=$default_charset;
1186 $charset = strtolower($charset);
1187 if (function_exists('mb_internal_encoding') &&
1188 in_array($charset,sq_mb_list_encodings())) {
1189 return mb_substr($string,$start,$length,$charset);
1191 // TODO: add mbstring independent code
1193 // use vanilla string functions as last option
1194 return substr($string,$start,$length);
1198 * Wrapper that is used to switch between vanilla and multibyte strpos
1200 * @param string $haystack
1201 * @param mixed $needle
1202 * @param integer $offset
1203 * @param string $charset
1206 * @link http://www.php.net/strpos
1207 * @link http://www.php.net/mb_strpos
1209 function sq_strpos($haystack,$needle,$offset,$charset='auto') {
1210 // use automatic charset detection, if function call asks for it
1211 if ($charset=='auto') {
1212 global $default_charset;
1214 $charset=$default_charset;
1216 $charset = strtolower($charset);
1217 if (function_exists('mb_internal_encoding') &&
1218 in_array($charset,sq_mb_list_encodings())) {
1219 return mb_strpos($haystack,$needle,$offset,$charset);
1221 // TODO: add mbstring independent code
1223 // use vanilla string functions as last option
1224 return strpos($haystack,$needle,$offset);
1228 * Wrapper that is used to switch between vanilla and multibyte strtoupper
1230 * @param string $string
1231 * @param string $charset
1234 * @link http://www.php.net/strtoupper
1235 * @link http://www.php.net/mb_strtoupper
1237 function sq_strtoupper($string,$charset='auto') {
1238 // use automatic charset detection, if function call asks for it
1239 if ($charset=='auto') {
1240 global $default_charset;
1242 $charset=$default_charset;
1244 $charset = strtolower($charset);
1245 if (function_exists('mb_strtoupper') &&
1246 in_array($charset,sq_mb_list_encodings())) {
1247 return mb_strtoupper($string,$charset);
1249 // TODO: add mbstring independent code
1251 // use vanilla string functions as last option
1252 return strtoupper($string);
1254 $PHP_SELF = php_self();