PageRenderTime 49ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/tags/rel-1_4_10a/functions/strings.php

#
PHP | 875 lines | 596 code | 77 blank | 202 comment | 103 complexity | b233a4b3eab67d69c5f62d42e0b55d31 MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0
  1. <?php
  2. /**
  3. * strings.php
  4. *
  5. * This code provides various string manipulation functions that are
  6. * used by the rest of the SquirrelMail code.
  7. *
  8. * @copyright &copy; 1999-2007 The SquirrelMail Project Team
  9. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  10. * @version $Id: strings.php 12383 2007-05-10 08:28:31Z kink $
  11. * @package squirrelmail
  12. */
  13. /**
  14. * SquirrelMail version number -- DO NOT CHANGE
  15. */
  16. global $version;
  17. $version = '1.4.10a';
  18. /**
  19. * SquirrelMail internal version number -- DO NOT CHANGE
  20. * $sm_internal_version = array (release, major, minor)
  21. */
  22. global $SQM_INTERNAL_VERSION;
  23. $SQM_INTERNAL_VERSION = array(1,4,10);
  24. /**
  25. * There can be a circular issue with includes, where the $version string is
  26. * referenced by the include of global.php, etc. before it's defined.
  27. * For that reason, bring in global.php AFTER we define the version strings.
  28. */
  29. require_once(SM_PATH . 'functions/global.php');
  30. /**
  31. * Wraps text at $wrap characters
  32. *
  33. * Has a problem with special HTML characters, so call this before
  34. * you do character translation.
  35. *
  36. * Specifically, &#039 comes up as 5 characters instead of 1.
  37. * This should not add newlines to the end of lines.
  38. */
  39. function sqWordWrap(&$line, $wrap, $charset=null) {
  40. global $languages, $squirrelmail_language;
  41. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  42. function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
  43. if (mb_detect_encoding($line) != 'ASCII') {
  44. $line = $languages[$squirrelmail_language]['XTRA_CODE']('wordwrap', $line, $wrap);
  45. return;
  46. }
  47. }
  48. ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
  49. $beginning_spaces = $regs[1];
  50. if (isset($regs[2])) {
  51. $words = explode(' ', $regs[2]);
  52. } else {
  53. $words = '';
  54. }
  55. $i = 0;
  56. $line = $beginning_spaces;
  57. while ($i < count($words)) {
  58. /* Force one word to be on a line (minimum) */
  59. $line .= $words[$i];
  60. $line_len = strlen($beginning_spaces) + sq_strlen($words[$i],$charset) + 2;
  61. if (isset($words[$i + 1]))
  62. $line_len += sq_strlen($words[$i + 1],$charset);
  63. $i ++;
  64. /* Add more words (as long as they fit) */
  65. while ($line_len < $wrap && $i < count($words)) {
  66. $line .= ' ' . $words[$i];
  67. $i++;
  68. if (isset($words[$i]))
  69. $line_len += sq_strlen($words[$i],$charset) + 1;
  70. else
  71. $line_len += 1;
  72. }
  73. /* Skip spaces if they are the first thing on a continued line */
  74. while (!isset($words[$i]) && $i < count($words)) {
  75. $i ++;
  76. }
  77. /* Go to the next line if we have more to process */
  78. if ($i < count($words)) {
  79. $line .= "\n";
  80. }
  81. }
  82. }
  83. /**
  84. * Does the opposite of sqWordWrap()
  85. * @param string body the text to un-wordwrap
  86. * @return void
  87. */
  88. function sqUnWordWrap(&$body) {
  89. global $squirrelmail_language;
  90. if ($squirrelmail_language == 'ja_JP') {
  91. return;
  92. }
  93. $lines = explode("\n", $body);
  94. $body = '';
  95. $PreviousSpaces = '';
  96. $cnt = count($lines);
  97. for ($i = 0; $i < $cnt; $i ++) {
  98. preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
  99. $CurrentSpaces = $regs[1];
  100. if (isset($regs[2])) {
  101. $CurrentRest = $regs[2];
  102. } else {
  103. $CurrentRest = '';
  104. }
  105. if ($i == 0) {
  106. $PreviousSpaces = $CurrentSpaces;
  107. $body = $lines[$i];
  108. } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
  109. && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
  110. && strlen($CurrentRest)) { /* and there's a line to continue with */
  111. $body .= ' ' . $CurrentRest;
  112. } else {
  113. $body .= "\n" . $lines[$i];
  114. $PreviousSpaces = $CurrentSpaces;
  115. }
  116. }
  117. $body .= "\n";
  118. }
  119. /**
  120. * Truncates a string and take care of html encoded characters
  121. *
  122. * @param string $s string to truncate
  123. * @param int $iTrimAt Trim at nn characters
  124. * @return string Trimmed string
  125. */
  126. function truncateWithEntities($s, $iTrimAt) {
  127. global $languages, $squirrelmail_language;
  128. $ent_strlen = strlen($s);
  129. if (($iTrimAt <= 0) || ($ent_strlen <= $iTrimAt))
  130. return $s;
  131. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  132. function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
  133. return $languages[$squirrelmail_language]['XTRA_CODE']('strimwidth', $s, $iTrimAt);
  134. } else {
  135. /*
  136. * see if this is entities-encoded string
  137. * If so, Iterate through the whole string, find out
  138. * the real number of characters, and if more
  139. * than $iTrimAt, substr with an updated trim value.
  140. */
  141. $trim_val = $iTrimAt;
  142. $ent_offset = 0;
  143. $ent_loc = 0;
  144. while ( $ent_loc < $trim_val && (($ent_loc = strpos($s, '&', $ent_offset)) !== false) &&
  145. (($ent_loc_end = strpos($s, ';', $ent_loc+3)) !== false) ) {
  146. $trim_val += ($ent_loc_end-$ent_loc);
  147. $ent_offset = $ent_loc_end+1;
  148. }
  149. if (($trim_val > $iTrimAt) && ($ent_strlen > $trim_val) && (strpos($s,';',$trim_val) < ($trim_val + 6))) {
  150. $i = strpos($s,';',$trim_val);
  151. if ($i !== false) {
  152. $trim_val = strpos($s,';',$trim_val)+1;
  153. }
  154. }
  155. // only print '...' when we're actually dropping part of the subject
  156. if ($ent_strlen <= $trim_val)
  157. return $s;
  158. }
  159. return substr_replace($s, '...', $trim_val);
  160. }
  161. /**
  162. * If $haystack is a full mailbox name and $needle is the mailbox
  163. * separator character, returns the last part of the mailbox name.
  164. *
  165. * @param string haystack full mailbox name to search
  166. * @param string needle the mailbox separator character
  167. * @return string the last part of the mailbox name
  168. */
  169. function readShortMailboxName($haystack, $needle) {
  170. if ($needle == '') {
  171. $elem = $haystack;
  172. } else {
  173. $parts = explode($needle, $haystack);
  174. $elem = array_pop($parts);
  175. while ($elem == '' && count($parts)) {
  176. $elem = array_pop($parts);
  177. }
  178. }
  179. return( $elem );
  180. }
  181. /**
  182. * php_self
  183. *
  184. * Creates an URL for the page calling this function, using either the PHP global
  185. * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added.
  186. *
  187. * @return string the complete url for this page
  188. */
  189. function php_self () {
  190. /*
  191. * PHP 4.4.4 is giving the wrong REQUEST_URI. The Query string is missing.
  192. * => I (stekkel) commented out the code because it's not realy needed. PHP_SELF in combinatiob
  193. * with QUERY_STRING should do the job.
  194. */
  195. // if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
  196. // return $req_uri;
  197. // }
  198. if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
  199. // need to add query string to end of PHP_SELF to match REQUEST_URI
  200. //
  201. if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER) && !empty($query_string) ) {
  202. $php_self .= '?' . $query_string;
  203. }
  204. return $php_self;
  205. }
  206. return '';
  207. }
  208. /**
  209. * Find out where squirrelmail lives and try to be smart about it.
  210. * The only problem would be when squirrelmail lives in directories
  211. * called "src", "functions", or "plugins", but people who do that need
  212. * to be beaten with a steel pipe anyway.
  213. *
  214. * @return string the base uri of squirrelmail installation.
  215. */
  216. function sqm_baseuri(){
  217. global $base_uri, $PHP_SELF;
  218. /**
  219. * If it is in the session, just return it.
  220. */
  221. if (sqgetGlobalVar('base_uri',$base_uri,SQ_SESSION)){
  222. return $base_uri;
  223. }
  224. $dirs = array('|src/.*|', '|plugins/.*|', '|functions/.*|');
  225. $repl = array('', '', '');
  226. $base_uri = preg_replace($dirs, $repl, $PHP_SELF);
  227. return $base_uri;
  228. }
  229. /**
  230. * get_location
  231. *
  232. * Determines the location to forward to, relative to your server.
  233. * This is used in HTTP Location: redirects.
  234. * If set, it uses $config_location_base as the first part of the URL,
  235. * specifically, the protocol, hostname and port parts. The path is
  236. * always autodetected.
  237. *
  238. * @return string the base url for this SquirrelMail installation
  239. */
  240. function get_location () {
  241. global $imap_server_type, $config_location_base;
  242. /* Get the path, handle virtual directories */
  243. if(strpos(php_self(), '?')) {
  244. $path = substr(php_self(), 0, strpos(php_self(), '?'));
  245. } else {
  246. $path = php_self();
  247. }
  248. $path = substr($path, 0, strrpos($path, '/'));
  249. // proto+host+port are already set in config:
  250. if ( !empty($config_location_base) ) {
  251. // register it in the session just in case some plugin depends on this
  252. sqsession_register($config_location_base . $path, 'sq_base_url');
  253. return $config_location_base . $path ;
  254. }
  255. // we computed it before, get it from the session:
  256. if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
  257. return $full_url . $path;
  258. }
  259. // else: autodetect
  260. /* Check if this is a HTTPS or regular HTTP request. */
  261. $proto = 'http://';
  262. /*
  263. * If you have 'SSLOptions +StdEnvVars' in your apache config
  264. * OR if you have HTTPS=on in your HTTP_SERVER_VARS
  265. * OR if you are on port 443
  266. */
  267. $getEnvVar = getenv('HTTPS');
  268. if ((isset($getEnvVar) && strcasecmp($getEnvVar, 'on') === 0) ||
  269. (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && strcasecmp($https_on, 'on') === 0) ||
  270. (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
  271. $proto = 'https://';
  272. }
  273. /* Get the hostname from the Host header or server config. */
  274. if ( !sqgetGlobalVar('HTTP_X_FORWARDED_HOST', $host, SQ_SERVER) || empty($host) ) {
  275. if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
  276. if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
  277. $host = '';
  278. }
  279. }
  280. }
  281. $port = '';
  282. if (! strstr($host, ':')) {
  283. if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
  284. if (($server_port != 80 && $proto == 'http://') ||
  285. ($server_port != 443 && $proto == 'https://')) {
  286. $port = sprintf(':%d', $server_port);
  287. }
  288. }
  289. }
  290. /* this is a workaround for the weird macosx caching that
  291. causes Apache to return 16080 as the port number, which causes
  292. SM to bail */
  293. if ($imap_server_type == 'macosx' && $port == ':16080') {
  294. $port = '';
  295. }
  296. /* Fallback is to omit the server name and use a relative */
  297. /* URI, although this is not RFC 2616 compliant. */
  298. $full_url = ($host ? $proto . $host . $port : '');
  299. sqsession_register($full_url, 'sq_base_url');
  300. return $full_url . $path;
  301. }
  302. /**
  303. * Encrypts password
  304. *
  305. * These functions are used to encrypt the password before it is
  306. * stored in a cookie. The encryption key is generated by
  307. * OneTimePadCreate();
  308. *
  309. * @param string string the (password)string to encrypt
  310. * @param string epad the encryption key
  311. * @return string the base64-encoded encrypted password
  312. */
  313. function OneTimePadEncrypt ($string, $epad) {
  314. $pad = base64_decode($epad);
  315. if (strlen($pad)>0) {
  316. // make sure that pad is longer than string
  317. while (strlen($string)>strlen($pad)) {
  318. $pad.=$pad;
  319. }
  320. } else {
  321. // FIXME: what should we do when $epad is not base64 encoded or empty.
  322. }
  323. $encrypted = '';
  324. for ($i = 0; $i < strlen ($string); $i++) {
  325. $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
  326. }
  327. return base64_encode($encrypted);
  328. }
  329. /**
  330. * Decrypts a password from the cookie
  331. *
  332. * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
  333. * This uses the encryption key that is stored in the session.
  334. *
  335. * @param string string the string to decrypt
  336. * @param string epad the encryption key from the session
  337. * @return string the decrypted password
  338. */
  339. function OneTimePadDecrypt ($string, $epad) {
  340. $pad = base64_decode($epad);
  341. if (strlen($pad)>0) {
  342. // make sure that pad is longer than string
  343. while (strlen($string)>strlen($pad)) {
  344. $pad.=$pad;
  345. }
  346. } else {
  347. // FIXME: what should we do when $epad is not base64 encoded or empty.
  348. }
  349. $encrypted = base64_decode ($string);
  350. $decrypted = '';
  351. for ($i = 0; $i < strlen ($encrypted); $i++) {
  352. $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
  353. }
  354. return $decrypted;
  355. }
  356. /**
  357. * Randomizes the mt_rand() function.
  358. *
  359. * Toss this in strings or integers and it will seed the generator
  360. * appropriately. With strings, it is better to get them long.
  361. * Use md5() to lengthen smaller strings.
  362. *
  363. * @param mixed val a value to seed the random number generator
  364. * @return void
  365. */
  366. function sq_mt_seed($Val) {
  367. /* if mt_getrandmax() does not return a 2^n - 1 number,
  368. this might not work well. This uses $Max as a bitmask. */
  369. $Max = mt_getrandmax();
  370. if (! is_int($Val)) {
  371. $Val = crc32($Val);
  372. }
  373. if ($Val < 0) {
  374. $Val *= -1;
  375. }
  376. if ($Val == 0) {
  377. return;
  378. }
  379. mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
  380. }
  381. /**
  382. * Init random number generator
  383. *
  384. * This function initializes the random number generator fairly well.
  385. * It also only initializes it once, so you don't accidentally get
  386. * the same 'random' numbers twice in one session.
  387. *
  388. * @return void
  389. */
  390. function sq_mt_randomize() {
  391. static $randomized;
  392. if ($randomized) {
  393. return;
  394. }
  395. /* Global. */
  396. sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
  397. sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
  398. sq_mt_seed((int)((double) microtime() * 1000000));
  399. sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
  400. /* getrusage */
  401. if (function_exists('getrusage')) {
  402. /* Avoid warnings with Win32 */
  403. $dat = @getrusage();
  404. if (isset($dat) && is_array($dat)) {
  405. $Str = '';
  406. foreach ($dat as $k => $v)
  407. {
  408. $Str .= $k . $v;
  409. }
  410. sq_mt_seed(md5($Str));
  411. }
  412. }
  413. if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
  414. sq_mt_seed(md5($unique_id));
  415. }
  416. $randomized = 1;
  417. }
  418. /**
  419. * Creates encryption key
  420. *
  421. * Creates an encryption key for encrypting the password stored in the cookie.
  422. * The encryption key itself is stored in the session.
  423. *
  424. * @param int length optional, length of the string to generate
  425. * @return string the encryption key
  426. */
  427. function OneTimePadCreate ($length=100) {
  428. sq_mt_randomize();
  429. $pad = '';
  430. for ($i = 0; $i < $length; $i++) {
  431. $pad .= chr(mt_rand(0,255));
  432. }
  433. return base64_encode($pad);
  434. }
  435. /**
  436. * Returns a string showing the size of the message/attachment.
  437. *
  438. * @param int bytes the filesize in bytes
  439. * @return string the filesize in human readable format
  440. */
  441. function show_readable_size($bytes) {
  442. $bytes /= 1024;
  443. $type = 'k';
  444. if ($bytes / 1024 > 1) {
  445. $bytes /= 1024;
  446. $type = 'M';
  447. }
  448. if ($bytes < 10) {
  449. $bytes *= 10;
  450. settype($bytes, 'integer');
  451. $bytes /= 10;
  452. } else {
  453. settype($bytes, 'integer');
  454. }
  455. return $bytes . '<small>&nbsp;' . $type . '</small>';
  456. }
  457. /**
  458. * Generates a random string from the caracter set you pass in
  459. *
  460. * @param int size the size of the string to generate
  461. * @param string chars a string containing the characters to use
  462. * @param int flags a flag to add a specific set to the characters to use:
  463. * Flags:
  464. * 1 = add lowercase a-z to $chars
  465. * 2 = add uppercase A-Z to $chars
  466. * 4 = add numbers 0-9 to $chars
  467. * @return string the random string
  468. */
  469. function GenerateRandomString($size, $chars, $flags = 0) {
  470. if ($flags & 0x1) {
  471. $chars .= 'abcdefghijklmnopqrstuvwxyz';
  472. }
  473. if ($flags & 0x2) {
  474. $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  475. }
  476. if ($flags & 0x4) {
  477. $chars .= '0123456789';
  478. }
  479. if (($size < 1) || (strlen($chars) < 1)) {
  480. return '';
  481. }
  482. sq_mt_randomize(); /* Initialize the random number generator */
  483. $String = '';
  484. $j = strlen( $chars ) - 1;
  485. while (strlen($String) < $size) {
  486. $String .= $chars{mt_rand(0, $j)};
  487. }
  488. return $String;
  489. }
  490. /**
  491. * Escapes special characters for use in IMAP commands.
  492. *
  493. * @param string the string to escape
  494. * @return string the escaped string
  495. */
  496. function quoteimap($str) {
  497. return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
  498. }
  499. /**
  500. * Trims array
  501. *
  502. * Trims every element in the array, ie. remove the first char of each element
  503. * Obsolete: will probably removed soon
  504. * @param array array the array to trim
  505. * @obsolete
  506. */
  507. function TrimArray(&$array) {
  508. foreach ($array as $k => $v) {
  509. global $$k;
  510. if (is_array($$k)) {
  511. foreach ($$k as $k2 => $v2) {
  512. $$k[$k2] = substr($v2, 1);
  513. }
  514. } else {
  515. $$k = substr($v, 1);
  516. }
  517. /* Re-assign back to array. */
  518. $array[$k] = $$k;
  519. }
  520. }
  521. /**
  522. * Removes slashes from every element in the array
  523. */
  524. function RemoveSlashes(&$array) {
  525. foreach ($array as $k => $v) {
  526. global $$k;
  527. if (is_array($$k)) {
  528. foreach ($$k as $k2 => $v2) {
  529. $newArray[stripslashes($k2)] = stripslashes($v2);
  530. }
  531. $$k = $newArray;
  532. } else {
  533. $$k = stripslashes($v);
  534. }
  535. /* Re-assign back to the array. */
  536. $array[$k] = $$k;
  537. }
  538. }
  539. /**
  540. * Create compose link
  541. *
  542. * Returns a link to the compose-page, taking in consideration
  543. * the compose_in_new and javascript settings.
  544. * @param string url the URL to the compose page
  545. * @param string text the link text, default "Compose"
  546. * @return string a link to the compose page
  547. */
  548. function makeComposeLink($url, $text = null, $target='')
  549. {
  550. global $compose_new_win,$javascript_on;
  551. if(!$text) {
  552. $text = _("Compose");
  553. }
  554. // if not using "compose in new window", make
  555. // regular link and be done with it
  556. if($compose_new_win != '1') {
  557. return makeInternalLink($url, $text, $target);
  558. }
  559. // build the compose in new window link...
  560. // if javascript is on, use onClick event to handle it
  561. if($javascript_on) {
  562. sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
  563. return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
  564. }
  565. // otherwise, just open new window using regular HTML
  566. return makeInternalLink($url, $text, '_blank');
  567. }
  568. /**
  569. * Print variable
  570. *
  571. * sm_print_r($some_variable, [$some_other_variable [, ...]]);
  572. *
  573. * Debugging function - does the same as print_r, but makes sure special
  574. * characters are converted to htmlentities first. This will allow
  575. * values like <some@email.address> to be displayed.
  576. * The output is wrapped in <<pre>> and <</pre>> tags.
  577. *
  578. * @return void
  579. */
  580. function sm_print_r() {
  581. ob_start(); // Buffer output
  582. foreach(func_get_args() as $var) {
  583. print_r($var);
  584. echo "\n";
  585. }
  586. $buffer = ob_get_contents(); // Grab the print_r output
  587. ob_end_clean(); // Silently discard the output & stop buffering
  588. print '<pre>';
  589. print htmlentities($buffer);
  590. print '</pre>';
  591. }
  592. /**
  593. * version of fwrite which checks for failure
  594. */
  595. function sq_fwrite($fp, $string) {
  596. // write to file
  597. $count = @fwrite($fp,$string);
  598. // the number of bytes written should be the length of the string
  599. if($count != strlen($string)) {
  600. return FALSE;
  601. }
  602. return $count;
  603. }
  604. /**
  605. * Tests if string contains 8bit symbols.
  606. *
  607. * If charset is not set, function defaults to default_charset.
  608. * $default_charset global must be set correctly if $charset is
  609. * not used.
  610. * @param string $string tested string
  611. * @param string $charset charset used in a string
  612. * @return bool true if 8bit symbols are detected
  613. * @since 1.5.1 and 1.4.4
  614. */
  615. function sq_is8bit($string,$charset='') {
  616. global $default_charset;
  617. if ($charset=='') $charset=$default_charset;
  618. /**
  619. * Don't use \240 in ranges. Sometimes RH 7.2 doesn't like it.
  620. * Don't use \200-\237 for iso-8859-x charsets. This ranges
  621. * stores control symbols in those charsets.
  622. * Use preg_match instead of ereg in order to avoid problems
  623. * with mbstring overloading
  624. */
  625. if (preg_match("/^iso-8859/i",$charset)) {
  626. $needle='/\240|[\241-\377]/';
  627. } else {
  628. $needle='/[\200-\237]|\240|[\241-\377]/';
  629. }
  630. return preg_match("$needle",$string);
  631. }
  632. /**
  633. * Function returns number of characters in string.
  634. *
  635. * Returned number might be different from number of bytes in string,
  636. * if $charset is multibyte charset. Detection depends on mbstring
  637. * functions. If mbstring does not support tested multibyte charset,
  638. * vanilla string length function is used.
  639. * @param string $str string
  640. * @param string $charset charset
  641. * @since 1.5.1 and 1.4.6
  642. * @return integer number of characters in string
  643. */
  644. function sq_strlen($str, $charset=null){
  645. // default option
  646. if (is_null($charset)) return strlen($str);
  647. // lowercase charset name
  648. $charset=strtolower($charset);
  649. // use automatic charset detection, if function call asks for it
  650. if ($charset=='auto') {
  651. global $default_charset;
  652. set_my_charset();
  653. $charset=$default_charset;
  654. }
  655. // Use mbstring only with listed charsets
  656. $aList_of_mb_charsets=array('utf-8','big5','gb2312','gb18030','euc-jp','euc-cn','euc-tw','euc-kr');
  657. // calculate string length according to charset
  658. if (in_array($charset,$aList_of_mb_charsets) && in_array($charset,sq_mb_list_encodings())) {
  659. $real_length = mb_strlen($str,$charset);
  660. } else {
  661. // own strlen detection code is removed because missing strpos,
  662. // strtoupper and substr implementations break string wrapping.
  663. $real_length=strlen($str);
  664. }
  665. return $real_length;
  666. }
  667. /**
  668. * Replacement of mb_list_encodings function
  669. *
  670. * This function provides replacement for function that is available only
  671. * in php 5.x. Function does not test all mbstring encodings. Only the ones
  672. * that might be used in SM translations.
  673. *
  674. * Supported strings are stored in session in order to reduce number of
  675. * mb_internal_encoding function calls.
  676. *
  677. * If mb_list_encodings() function is present, code uses it. Main difference
  678. * from original function behaviour - array values are lowercased in order to
  679. * simplify use of returned array in in_array() checks.
  680. *
  681. * If you want to test all mbstring encodings - fill $list_of_encodings
  682. * array.
  683. * @return array list of encodings supported by php mbstring extension
  684. * @since 1.5.1 and 1.4.6
  685. */
  686. function sq_mb_list_encodings() {
  687. // check if mbstring extension is present
  688. if (! function_exists('mb_internal_encoding'))
  689. return array();
  690. // php 5+ function
  691. if (function_exists('mb_list_encodings')) {
  692. $ret = mb_list_encodings();
  693. array_walk($ret,'sq_lowercase_array_vals');
  694. return $ret;
  695. }
  696. // don't try to test encodings, if they are already stored in session
  697. if (sqgetGlobalVar('mb_supported_encodings',$mb_supported_encodings,SQ_SESSION))
  698. return $mb_supported_encodings;
  699. // save original encoding
  700. $orig_encoding=mb_internal_encoding();
  701. $list_of_encoding=array(
  702. 'pass',
  703. 'auto',
  704. 'ascii',
  705. 'jis',
  706. 'utf-8',
  707. 'sjis',
  708. 'euc-jp',
  709. 'iso-8859-1',
  710. 'iso-8859-2',
  711. 'iso-8859-7',
  712. 'iso-8859-9',
  713. 'iso-8859-15',
  714. 'koi8-r',
  715. 'koi8-u',
  716. 'big5',
  717. 'gb2312',
  718. 'gb18030',
  719. 'windows-1251',
  720. 'windows-1255',
  721. 'windows-1256',
  722. 'tis-620',
  723. 'iso-2022-jp',
  724. 'euc-cn',
  725. 'euc-kr',
  726. 'euc-tw',
  727. 'uhc',
  728. 'utf7-imap');
  729. $supported_encodings=array();
  730. foreach ($list_of_encoding as $encoding) {
  731. // try setting encodings. suppress warning messages
  732. if (@mb_internal_encoding($encoding))
  733. $supported_encodings[]=$encoding;
  734. }
  735. // restore original encoding
  736. mb_internal_encoding($orig_encoding);
  737. // register list in session
  738. sqsession_register($supported_encodings,'mb_supported_encodings');
  739. return $supported_encodings;
  740. }
  741. /**
  742. * Callback function used to lowercase array values.
  743. * @param string $val array value
  744. * @param mixed $key array key
  745. * @since 1.5.1 and 1.4.6
  746. */
  747. function sq_lowercase_array_vals(&$val,$key) {
  748. $val = strtolower($val);
  749. }
  750. /**
  751. * Callback function to trim whitespace from a value, to be used in array_walk
  752. * @param string $value value to trim
  753. * @since 1.5.2 and 1.4.7
  754. */
  755. function sq_trim_value ( &$value ) {
  756. $value = trim($value);
  757. }
  758. $PHP_SELF = php_self();
  759. ?>