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

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

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