PageRenderTime 59ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

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

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