PageRenderTime 47ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

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

#
PHP | 880 lines | 600 code | 77 blank | 203 comment | 104 complexity | b4a5ebffd262aac1b9e9a2fb38979f28 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 12798 2007-12-05 05:24:24Z jangliss $
  11. * @package squirrelmail
  12. */
  13. /**
  14. * SquirrelMail version number -- DO NOT CHANGE
  15. */
  16. global $version;
  17. $version = '1.4.12';
  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,12);
  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 have HTTP_X_FORWARDED_PROTO=https in your HTTP_SERVER_VARS
  266. * OR if you are on port 443
  267. */
  268. $getEnvVar = getenv('HTTPS');
  269. if (!sqgetGlobalVar('HTTP_X_FORWARDED_PROTO', $forwarded_proto, SQ_SERVER))
  270. $forwarded_proto = '';
  271. if ((isset($getEnvVar) && strcasecmp($getEnvVar, 'on') === 0) ||
  272. (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && strcasecmp($https_on, 'on') === 0) ||
  273. (strcasecmp($forwarded_proto, 'https') === 0) ||
  274. (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
  275. $proto = 'https://';
  276. }
  277. /* Get the hostname from the Host header or server config. */
  278. if ( !sqgetGlobalVar('HTTP_X_FORWARDED_HOST', $host, SQ_SERVER) || empty($host) ) {
  279. if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
  280. if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
  281. $host = '';
  282. }
  283. }
  284. }
  285. $port = '';
  286. if (strpos($host, ':') === FALSE) {
  287. if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
  288. if (($server_port != 80 && $proto == 'http://') ||
  289. ($server_port != 443 && $proto == 'https://' &&
  290. strcasecmp($forwarded_proto, 'https') !== 0)) {
  291. $port = sprintf(':%d', $server_port);
  292. }
  293. }
  294. }
  295. /* this is a workaround for the weird macosx caching that
  296. causes Apache to return 16080 as the port number, which causes
  297. SM to bail */
  298. if ($imap_server_type == 'macosx' && $port == ':16080') {
  299. $port = '';
  300. }
  301. /* Fallback is to omit the server name and use a relative */
  302. /* URI, although this is not RFC 2616 compliant. */
  303. $full_url = ($host ? $proto . $host . $port : '');
  304. sqsession_register($full_url, 'sq_base_url');
  305. return $full_url . $path;
  306. }
  307. /**
  308. * Encrypts password
  309. *
  310. * These functions are used to encrypt the password before it is
  311. * stored in a cookie. The encryption key is generated by
  312. * OneTimePadCreate();
  313. *
  314. * @param string string the (password)string to encrypt
  315. * @param string epad the encryption key
  316. * @return string the base64-encoded encrypted password
  317. */
  318. function OneTimePadEncrypt ($string, $epad) {
  319. $pad = base64_decode($epad);
  320. if (strlen($pad)>0) {
  321. // make sure that pad is longer than string
  322. while (strlen($string)>strlen($pad)) {
  323. $pad.=$pad;
  324. }
  325. } else {
  326. // FIXME: what should we do when $epad is not base64 encoded or empty.
  327. }
  328. $encrypted = '';
  329. for ($i = 0; $i < strlen ($string); $i++) {
  330. $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
  331. }
  332. return base64_encode($encrypted);
  333. }
  334. /**
  335. * Decrypts a password from the cookie
  336. *
  337. * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
  338. * This uses the encryption key that is stored in the session.
  339. *
  340. * @param string string the string to decrypt
  341. * @param string epad the encryption key from the session
  342. * @return string the decrypted password
  343. */
  344. function OneTimePadDecrypt ($string, $epad) {
  345. $pad = base64_decode($epad);
  346. if (strlen($pad)>0) {
  347. // make sure that pad is longer than string
  348. while (strlen($string)>strlen($pad)) {
  349. $pad.=$pad;
  350. }
  351. } else {
  352. // FIXME: what should we do when $epad is not base64 encoded or empty.
  353. }
  354. $encrypted = base64_decode ($string);
  355. $decrypted = '';
  356. for ($i = 0; $i < strlen ($encrypted); $i++) {
  357. $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
  358. }
  359. return $decrypted;
  360. }
  361. /**
  362. * Randomizes the mt_rand() function.
  363. *
  364. * Toss this in strings or integers and it will seed the generator
  365. * appropriately. With strings, it is better to get them long.
  366. * Use md5() to lengthen smaller strings.
  367. *
  368. * @param mixed val a value to seed the random number generator
  369. * @return void
  370. */
  371. function sq_mt_seed($Val) {
  372. /* if mt_getrandmax() does not return a 2^n - 1 number,
  373. this might not work well. This uses $Max as a bitmask. */
  374. $Max = mt_getrandmax();
  375. if (! is_int($Val)) {
  376. $Val = crc32($Val);
  377. }
  378. if ($Val < 0) {
  379. $Val *= -1;
  380. }
  381. if ($Val == 0) {
  382. return;
  383. }
  384. mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
  385. }
  386. /**
  387. * Init random number generator
  388. *
  389. * This function initializes the random number generator fairly well.
  390. * It also only initializes it once, so you don't accidentally get
  391. * the same 'random' numbers twice in one session.
  392. *
  393. * @return void
  394. */
  395. function sq_mt_randomize() {
  396. static $randomized;
  397. if ($randomized) {
  398. return;
  399. }
  400. /* Global. */
  401. sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
  402. sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
  403. sq_mt_seed((int)((double) microtime() * 1000000));
  404. sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
  405. /* getrusage */
  406. if (function_exists('getrusage')) {
  407. /* Avoid warnings with Win32 */
  408. $dat = @getrusage();
  409. if (isset($dat) && is_array($dat)) {
  410. $Str = '';
  411. foreach ($dat as $k => $v)
  412. {
  413. $Str .= $k . $v;
  414. }
  415. sq_mt_seed(md5($Str));
  416. }
  417. }
  418. if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
  419. sq_mt_seed(md5($unique_id));
  420. }
  421. $randomized = 1;
  422. }
  423. /**
  424. * Creates encryption key
  425. *
  426. * Creates an encryption key for encrypting the password stored in the cookie.
  427. * The encryption key itself is stored in the session.
  428. *
  429. * @param int length optional, length of the string to generate
  430. * @return string the encryption key
  431. */
  432. function OneTimePadCreate ($length=100) {
  433. sq_mt_randomize();
  434. $pad = '';
  435. for ($i = 0; $i < $length; $i++) {
  436. $pad .= chr(mt_rand(0,255));
  437. }
  438. return base64_encode($pad);
  439. }
  440. /**
  441. * Returns a string showing the size of the message/attachment.
  442. *
  443. * @param int bytes the filesize in bytes
  444. * @return string the filesize in human readable format
  445. */
  446. function show_readable_size($bytes) {
  447. $bytes /= 1024;
  448. $type = 'k';
  449. if ($bytes / 1024 > 1) {
  450. $bytes /= 1024;
  451. $type = 'M';
  452. }
  453. if ($bytes < 10) {
  454. $bytes *= 10;
  455. settype($bytes, 'integer');
  456. $bytes /= 10;
  457. } else {
  458. settype($bytes, 'integer');
  459. }
  460. return $bytes . '<small>&nbsp;' . $type . '</small>';
  461. }
  462. /**
  463. * Generates a random string from the caracter set you pass in
  464. *
  465. * @param int size the size of the string to generate
  466. * @param string chars a string containing the characters to use
  467. * @param int flags a flag to add a specific set to the characters to use:
  468. * Flags:
  469. * 1 = add lowercase a-z to $chars
  470. * 2 = add uppercase A-Z to $chars
  471. * 4 = add numbers 0-9 to $chars
  472. * @return string the random string
  473. */
  474. function GenerateRandomString($size, $chars, $flags = 0) {
  475. if ($flags & 0x1) {
  476. $chars .= 'abcdefghijklmnopqrstuvwxyz';
  477. }
  478. if ($flags & 0x2) {
  479. $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  480. }
  481. if ($flags & 0x4) {
  482. $chars .= '0123456789';
  483. }
  484. if (($size < 1) || (strlen($chars) < 1)) {
  485. return '';
  486. }
  487. sq_mt_randomize(); /* Initialize the random number generator */
  488. $String = '';
  489. $j = strlen( $chars ) - 1;
  490. while (strlen($String) < $size) {
  491. $String .= $chars{mt_rand(0, $j)};
  492. }
  493. return $String;
  494. }
  495. /**
  496. * Escapes special characters for use in IMAP commands.
  497. *
  498. * @param string the string to escape
  499. * @return string the escaped string
  500. */
  501. function quoteimap($str) {
  502. return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
  503. }
  504. /**
  505. * Trims array
  506. *
  507. * Trims every element in the array, ie. remove the first char of each element
  508. * Obsolete: will probably removed soon
  509. * @param array array the array to trim
  510. * @obsolete
  511. */
  512. function TrimArray(&$array) {
  513. foreach ($array as $k => $v) {
  514. global $$k;
  515. if (is_array($$k)) {
  516. foreach ($$k as $k2 => $v2) {
  517. $$k[$k2] = substr($v2, 1);
  518. }
  519. } else {
  520. $$k = substr($v, 1);
  521. }
  522. /* Re-assign back to array. */
  523. $array[$k] = $$k;
  524. }
  525. }
  526. /**
  527. * Removes slashes from every element in the array
  528. */
  529. function RemoveSlashes(&$array) {
  530. foreach ($array as $k => $v) {
  531. global $$k;
  532. if (is_array($$k)) {
  533. foreach ($$k as $k2 => $v2) {
  534. $newArray[stripslashes($k2)] = stripslashes($v2);
  535. }
  536. $$k = $newArray;
  537. } else {
  538. $$k = stripslashes($v);
  539. }
  540. /* Re-assign back to the array. */
  541. $array[$k] = $$k;
  542. }
  543. }
  544. /**
  545. * Create compose link
  546. *
  547. * Returns a link to the compose-page, taking in consideration
  548. * the compose_in_new and javascript settings.
  549. * @param string url the URL to the compose page
  550. * @param string text the link text, default "Compose"
  551. * @return string a link to the compose page
  552. */
  553. function makeComposeLink($url, $text = null, $target='')
  554. {
  555. global $compose_new_win,$javascript_on;
  556. if(!$text) {
  557. $text = _("Compose");
  558. }
  559. // if not using "compose in new window", make
  560. // regular link and be done with it
  561. if($compose_new_win != '1') {
  562. return makeInternalLink($url, $text, $target);
  563. }
  564. // build the compose in new window link...
  565. // if javascript is on, use onClick event to handle it
  566. if($javascript_on) {
  567. sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
  568. return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
  569. }
  570. // otherwise, just open new window using regular HTML
  571. return makeInternalLink($url, $text, '_blank');
  572. }
  573. /**
  574. * Print variable
  575. *
  576. * sm_print_r($some_variable, [$some_other_variable [, ...]]);
  577. *
  578. * Debugging function - does the same as print_r, but makes sure special
  579. * characters are converted to htmlentities first. This will allow
  580. * values like <some@email.address> to be displayed.
  581. * The output is wrapped in <<pre>> and <</pre>> tags.
  582. *
  583. * @return void
  584. */
  585. function sm_print_r() {
  586. ob_start(); // Buffer output
  587. foreach(func_get_args() as $var) {
  588. print_r($var);
  589. echo "\n";
  590. }
  591. $buffer = ob_get_contents(); // Grab the print_r output
  592. ob_end_clean(); // Silently discard the output & stop buffering
  593. print '<pre>';
  594. print htmlentities($buffer);
  595. print '</pre>';
  596. }
  597. /**
  598. * version of fwrite which checks for failure
  599. */
  600. function sq_fwrite($fp, $string) {
  601. // write to file
  602. $count = @fwrite($fp,$string);
  603. // the number of bytes written should be the length of the string
  604. if($count != strlen($string)) {
  605. return FALSE;
  606. }
  607. return $count;
  608. }
  609. /**
  610. * Tests if string contains 8bit symbols.
  611. *
  612. * If charset is not set, function defaults to default_charset.
  613. * $default_charset global must be set correctly if $charset is
  614. * not used.
  615. * @param string $string tested string
  616. * @param string $charset charset used in a string
  617. * @return bool true if 8bit symbols are detected
  618. * @since 1.5.1 and 1.4.4
  619. */
  620. function sq_is8bit($string,$charset='') {
  621. global $default_charset;
  622. if ($charset=='') $charset=$default_charset;
  623. /**
  624. * Don't use \240 in ranges. Sometimes RH 7.2 doesn't like it.
  625. * Don't use \200-\237 for iso-8859-x charsets. This ranges
  626. * stores control symbols in those charsets.
  627. * Use preg_match instead of ereg in order to avoid problems
  628. * with mbstring overloading
  629. */
  630. if (preg_match("/^iso-8859/i",$charset)) {
  631. $needle='/\240|[\241-\377]/';
  632. } else {
  633. $needle='/[\200-\237]|\240|[\241-\377]/';
  634. }
  635. return preg_match("$needle",$string);
  636. }
  637. /**
  638. * Function returns number of characters in string.
  639. *
  640. * Returned number might be different from number of bytes in string,
  641. * if $charset is multibyte charset. Detection depends on mbstring
  642. * functions. If mbstring does not support tested multibyte charset,
  643. * vanilla string length function is used.
  644. * @param string $str string
  645. * @param string $charset charset
  646. * @since 1.5.1 and 1.4.6
  647. * @return integer number of characters in string
  648. */
  649. function sq_strlen($str, $charset=null){
  650. // default option
  651. if (is_null($charset)) return strlen($str);
  652. // lowercase charset name
  653. $charset=strtolower($charset);
  654. // use automatic charset detection, if function call asks for it
  655. if ($charset=='auto') {
  656. global $default_charset;
  657. set_my_charset();
  658. $charset=$default_charset;
  659. }
  660. // Use mbstring only with listed charsets
  661. $aList_of_mb_charsets=array('utf-8','big5','gb2312','gb18030','euc-jp','euc-cn','euc-tw','euc-kr');
  662. // calculate string length according to charset
  663. if (in_array($charset,$aList_of_mb_charsets) && in_array($charset,sq_mb_list_encodings())) {
  664. $real_length = mb_strlen($str,$charset);
  665. } else {
  666. // own strlen detection code is removed because missing strpos,
  667. // strtoupper and substr implementations break string wrapping.
  668. $real_length=strlen($str);
  669. }
  670. return $real_length;
  671. }
  672. /**
  673. * Replacement of mb_list_encodings function
  674. *
  675. * This function provides replacement for function that is available only
  676. * in php 5.x. Function does not test all mbstring encodings. Only the ones
  677. * that might be used in SM translations.
  678. *
  679. * Supported strings are stored in session in order to reduce number of
  680. * mb_internal_encoding function calls.
  681. *
  682. * If mb_list_encodings() function is present, code uses it. Main difference
  683. * from original function behaviour - array values are lowercased in order to
  684. * simplify use of returned array in in_array() checks.
  685. *
  686. * If you want to test all mbstring encodings - fill $list_of_encodings
  687. * array.
  688. * @return array list of encodings supported by php mbstring extension
  689. * @since 1.5.1 and 1.4.6
  690. */
  691. function sq_mb_list_encodings() {
  692. // check if mbstring extension is present
  693. if (! function_exists('mb_internal_encoding'))
  694. return array();
  695. // php 5+ function
  696. if (function_exists('mb_list_encodings')) {
  697. $ret = mb_list_encodings();
  698. array_walk($ret,'sq_lowercase_array_vals');
  699. return $ret;
  700. }
  701. // don't try to test encodings, if they are already stored in session
  702. if (sqgetGlobalVar('mb_supported_encodings',$mb_supported_encodings,SQ_SESSION))
  703. return $mb_supported_encodings;
  704. // save original encoding
  705. $orig_encoding=mb_internal_encoding();
  706. $list_of_encoding=array(
  707. 'pass',
  708. 'auto',
  709. 'ascii',
  710. 'jis',
  711. 'utf-8',
  712. 'sjis',
  713. 'euc-jp',
  714. 'iso-8859-1',
  715. 'iso-8859-2',
  716. 'iso-8859-7',
  717. 'iso-8859-9',
  718. 'iso-8859-15',
  719. 'koi8-r',
  720. 'koi8-u',
  721. 'big5',
  722. 'gb2312',
  723. 'gb18030',
  724. 'windows-1251',
  725. 'windows-1255',
  726. 'windows-1256',
  727. 'tis-620',
  728. 'iso-2022-jp',
  729. 'euc-cn',
  730. 'euc-kr',
  731. 'euc-tw',
  732. 'uhc',
  733. 'utf7-imap');
  734. $supported_encodings=array();
  735. foreach ($list_of_encoding as $encoding) {
  736. // try setting encodings. suppress warning messages
  737. if (@mb_internal_encoding($encoding))
  738. $supported_encodings[]=$encoding;
  739. }
  740. // restore original encoding
  741. mb_internal_encoding($orig_encoding);
  742. // register list in session
  743. sqsession_register($supported_encodings,'mb_supported_encodings');
  744. return $supported_encodings;
  745. }
  746. /**
  747. * Callback function used to lowercase array values.
  748. * @param string $val array value
  749. * @param mixed $key array key
  750. * @since 1.5.1 and 1.4.6
  751. */
  752. function sq_lowercase_array_vals(&$val,$key) {
  753. $val = strtolower($val);
  754. }
  755. /**
  756. * Callback function to trim whitespace from a value, to be used in array_walk
  757. * @param string $value value to trim
  758. * @since 1.5.2 and 1.4.7
  759. */
  760. function sq_trim_value ( &$value ) {
  761. $value = trim($value);
  762. }
  763. $PHP_SELF = php_self();
  764. ?>