PageRenderTime 51ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

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

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