PageRenderTime 51ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/tags/webmail-release-1_4_22/functions/strings.php

#
PHP | 1458 lines | 1119 code | 89 blank | 250 comment | 104 complexity | 5b39fbcf63e560509db6ce19c56438d3 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 1999-2011 The SquirrelMail Project Team
  9. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  10. * @version $Id: strings.php 14123 2011-07-12 19:10:50Z pdontthink $
  11. * @package squirrelmail
  12. */
  13. /**
  14. * SquirrelMail version number -- DO NOT CHANGE
  15. */
  16. global $version;
  17. $version = '1.4.22';
  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,22);
  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. preg_match('/^([\t >]*)([^\t >].*)?$/', $line, $regs);
  52. $beginning_spaces = $regs[1];
  53. if (isset($regs[2])) {
  54. $words = explode(' ', $regs[2]);
  55. } else {
  56. $words = array();
  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 the given string so that it has at
  124. * most $max_chars characters. NOTE that a "character"
  125. * may be a multibyte character, or (optionally), an
  126. * HTML entity, so this function is different than
  127. * using substr() or mb_substr().
  128. *
  129. * NOTE that if $elipses is given and used, the returned
  130. * number of characters will be $max_chars PLUS the
  131. * length of $elipses
  132. *
  133. * @param string $string The string to truncate
  134. * @param int $max_chars The maximum allowable characters
  135. * @param string $elipses A string that will be added to
  136. * the end of the truncated string
  137. * (ONLY if it is truncated) (OPTIONAL;
  138. * default not used)
  139. * @param boolean $html_entities_as_chars Whether or not to keep
  140. * HTML entities together
  141. * (OPTIONAL; default ignore
  142. * HTML entities)
  143. *
  144. * @return string The truncated string
  145. *
  146. * @since 1.4.20 and 1.5.2 (replaced truncateWithEntities())
  147. *
  148. */
  149. function sm_truncate_string($string, $max_chars, $elipses='',
  150. $html_entities_as_chars=FALSE)
  151. {
  152. // if the length of the string is less than
  153. // the allowable number of characters, just
  154. // return it as is (even if it contains any
  155. // HTML entities, that would just make the
  156. // actual length even smaller)
  157. //
  158. $actual_strlen = sq_strlen($string, 'auto');
  159. if ($max_chars <= 0 || $actual_strlen <= $max_chars)
  160. return $string;
  161. // if needed, count the number of HTML entities in
  162. // the string up to the maximum character limit,
  163. // pushing that limit up for each entity found
  164. //
  165. $adjusted_max_chars = $max_chars;
  166. if ($html_entities_as_chars)
  167. {
  168. // $loop_count is needed to prevent an endless loop
  169. // which is caused by buggy mbstring versions that
  170. // return 0 (zero) instead of FALSE in some rare
  171. // cases. Thanks, PHP.
  172. // see: http://bugs.php.net/bug.php?id=52731
  173. // also: tracker $3053349
  174. //
  175. $loop_count = 0;
  176. $entity_pos = $entity_end_pos = -1;
  177. while ($entity_end_pos + 1 < $actual_strlen
  178. && ($entity_pos = sq_strpos($string, '&', $entity_end_pos + 1)) !== FALSE
  179. && ($entity_end_pos = sq_strpos($string, ';', $entity_pos)) !== FALSE
  180. && $entity_pos <= $adjusted_max_chars
  181. && $loop_count++ < $max_chars)
  182. {
  183. $adjusted_max_chars += $entity_end_pos - $entity_pos;
  184. }
  185. // this isn't necessary because sq_substr() would figure this
  186. // out anyway, but we can avoid a sq_substr() call and we
  187. // know that we don't have to add an elipses (this is now
  188. // an accurate comparison, since $adjusted_max_chars, like
  189. // $actual_strlen, does not take into account HTML entities)
  190. //
  191. if ($actual_strlen <= $adjusted_max_chars)
  192. return $string;
  193. }
  194. // get the truncated string
  195. //
  196. $truncated_string = sq_substr($string, 0, $adjusted_max_chars);
  197. // return with added elipses
  198. //
  199. return $truncated_string . $elipses;
  200. }
  201. /**
  202. * If $haystack is a full mailbox name and $needle is the mailbox
  203. * separator character, returns the last part of the mailbox name.
  204. *
  205. * @param string haystack full mailbox name to search
  206. * @param string needle the mailbox separator character
  207. * @return string the last part of the mailbox name
  208. */
  209. function readShortMailboxName($haystack, $needle) {
  210. if ($needle == '') {
  211. $elem = $haystack;
  212. } else {
  213. $parts = explode($needle, $haystack);
  214. $elem = array_pop($parts);
  215. while ($elem == '' && count($parts)) {
  216. $elem = array_pop($parts);
  217. }
  218. }
  219. return( $elem );
  220. }
  221. /**
  222. * php_self
  223. *
  224. * Attempts to determine the path and filename and any arguments
  225. * for the currently executing script. This is usually found in
  226. * $_SERVER['REQUEST_URI'], but some environments may differ, so
  227. * this function tries to standardize this value.
  228. *
  229. * @since 1.2.3
  230. * @return string The path, filename and any arguments for the
  231. * current script
  232. */
  233. function php_self() {
  234. $request_uri = '';
  235. // first try $_SERVER['PHP_SELF'], which seems most reliable
  236. // (albeit it usually won't include the query string)
  237. //
  238. $request_uri = '';
  239. if (!sqgetGlobalVar('PHP_SELF', $request_uri, SQ_SERVER)
  240. || empty($request_uri)) {
  241. // well, then let's try $_SERVER['REQUEST_URI']
  242. //
  243. $request_uri = '';
  244. if (!sqgetGlobalVar('REQUEST_URI', $request_uri, SQ_SERVER)
  245. || empty($request_uri)) {
  246. // TODO: anyone have any other ideas? maybe $_SERVER['SCRIPT_NAME']???
  247. //
  248. return '';
  249. }
  250. }
  251. // we may or may not have any query arguments, depending on
  252. // which environment variable was used above, and the PHP
  253. // version, etc., so let's check for it now
  254. //
  255. $query_string = '';
  256. if (strpos($request_uri, '?') === FALSE
  257. && sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER)
  258. && !empty($query_string)) {
  259. $request_uri .= '?' . $query_string;
  260. }
  261. return $request_uri;
  262. }
  263. /**
  264. * Find out where squirrelmail lives and try to be smart about it.
  265. * The only problem would be when squirrelmail lives in directories
  266. * called "src", "functions", or "plugins", but people who do that need
  267. * to be beaten with a steel pipe anyway.
  268. *
  269. * @return string the base uri of squirrelmail installation.
  270. */
  271. function sqm_baseuri(){
  272. global $base_uri, $PHP_SELF;
  273. /**
  274. * If it is in the session, just return it.
  275. */
  276. if (sqgetGlobalVar('base_uri',$base_uri,SQ_SESSION)){
  277. return $base_uri;
  278. }
  279. $dirs = array('|src/.*|', '|plugins/.*|', '|functions/.*|');
  280. $repl = array('', '', '');
  281. $base_uri = preg_replace($dirs, $repl, $PHP_SELF);
  282. return $base_uri;
  283. }
  284. /**
  285. * get_location
  286. *
  287. * Determines the location to forward to, relative to your server.
  288. * This is used in HTTP Location: redirects.
  289. * If set, it uses $config_location_base as the first part of the URL,
  290. * specifically, the protocol, hostname and port parts. The path is
  291. * always autodetected.
  292. *
  293. * @return string the base url for this SquirrelMail installation
  294. */
  295. function get_location () {
  296. global $imap_server_type, $config_location_base,
  297. $is_secure_connection, $sq_ignore_http_x_forwarded_headers;
  298. /* Get the path, handle virtual directories */
  299. if(strpos(php_self(), '?')) {
  300. $path = substr(php_self(), 0, strpos(php_self(), '?'));
  301. } else {
  302. $path = php_self();
  303. }
  304. $path = substr($path, 0, strrpos($path, '/'));
  305. // proto+host+port are already set in config:
  306. if ( !empty($config_location_base) ) {
  307. // register it in the session just in case some plugin depends on this
  308. sqsession_register($config_location_base . $path, 'sq_base_url');
  309. return $config_location_base . $path ;
  310. }
  311. // we computed it before, get it from the session:
  312. if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
  313. return $full_url . $path;
  314. }
  315. // else: autodetect
  316. /* Check if this is a HTTPS or regular HTTP request. */
  317. $proto = 'http://';
  318. if ($is_secure_connection)
  319. $proto = 'https://';
  320. /* Get the hostname from the Host header or server config. */
  321. if ($sq_ignore_http_x_forwarded_headers
  322. || !sqgetGlobalVar('HTTP_X_FORWARDED_HOST', $host, SQ_SERVER)
  323. || empty($host)) {
  324. if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
  325. if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
  326. $host = '';
  327. }
  328. }
  329. }
  330. $port = '';
  331. if (strpos($host, ':') === FALSE) {
  332. // Note: HTTP_X_FORWARDED_PROTO could be sent from the client and
  333. // therefore possibly spoofed/hackable - for now, the
  334. // administrator can tell SM to ignore this value by setting
  335. // $sq_ignore_http_x_forwarded_headers to boolean TRUE in
  336. // config/config_local.php, but in the future we may
  337. // want to default this to TRUE and make administrators
  338. // who use proxy systems turn it off (see 1.5.2+).
  339. global $sq_ignore_http_x_forwarded_headers;
  340. if ($sq_ignore_http_x_forwarded_headers
  341. || !sqgetGlobalVar('HTTP_X_FORWARDED_PROTO', $forwarded_proto, SQ_SERVER))
  342. $forwarded_proto = '';
  343. if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
  344. if (($server_port != 80 && $proto == 'http://') ||
  345. ($server_port != 443 && $proto == 'https://' &&
  346. strcasecmp($forwarded_proto, 'https') !== 0)) {
  347. $port = sprintf(':%d', $server_port);
  348. }
  349. }
  350. }
  351. /* this is a workaround for the weird macosx caching that
  352. causes Apache to return 16080 as the port number, which causes
  353. SM to bail */
  354. if ($imap_server_type == 'macosx' && $port == ':16080') {
  355. $port = '';
  356. }
  357. /* Fallback is to omit the server name and use a relative */
  358. /* URI, although this is not RFC 2616 compliant. */
  359. $full_url = ($host ? $proto . $host . $port : '');
  360. sqsession_register($full_url, 'sq_base_url');
  361. return $full_url . $path;
  362. }
  363. /**
  364. * Encrypts password
  365. *
  366. * These functions are used to encrypt the password before it is
  367. * stored in a cookie. The encryption key is generated by
  368. * OneTimePadCreate();
  369. *
  370. * @param string string the (password)string to encrypt
  371. * @param string epad the encryption key
  372. * @return string the base64-encoded encrypted password
  373. */
  374. function OneTimePadEncrypt ($string, $epad) {
  375. $pad = base64_decode($epad);
  376. if (strlen($pad)>0) {
  377. // make sure that pad is longer than string
  378. while (strlen($string)>strlen($pad)) {
  379. $pad.=$pad;
  380. }
  381. } else {
  382. // FIXME: what should we do when $epad is not base64 encoded or empty.
  383. }
  384. $encrypted = '';
  385. for ($i = 0; $i < strlen ($string); $i++) {
  386. $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
  387. }
  388. return base64_encode($encrypted);
  389. }
  390. /**
  391. * Decrypts a password from the cookie
  392. *
  393. * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
  394. * This uses the encryption key that is stored in the session.
  395. *
  396. * @param string string the string to decrypt
  397. * @param string epad the encryption key from the session
  398. * @return string the decrypted password
  399. */
  400. function OneTimePadDecrypt ($string, $epad) {
  401. $pad = base64_decode($epad);
  402. if (strlen($pad)>0) {
  403. // make sure that pad is longer than string
  404. while (strlen($string)>strlen($pad)) {
  405. $pad.=$pad;
  406. }
  407. } else {
  408. // FIXME: what should we do when $epad is not base64 encoded or empty.
  409. }
  410. $encrypted = base64_decode ($string);
  411. $decrypted = '';
  412. for ($i = 0; $i < strlen ($encrypted); $i++) {
  413. $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
  414. }
  415. return $decrypted;
  416. }
  417. /**
  418. * Randomizes the mt_rand() function.
  419. *
  420. * Toss this in strings or integers and it will seed the generator
  421. * appropriately. With strings, it is better to get them long.
  422. * Use md5() to lengthen smaller strings.
  423. *
  424. * @param mixed val a value to seed the random number generator
  425. * @return void
  426. */
  427. function sq_mt_seed($Val) {
  428. /* if mt_getrandmax() does not return a 2^n - 1 number,
  429. this might not work well. This uses $Max as a bitmask. */
  430. $Max = mt_getrandmax();
  431. if (! is_int($Val)) {
  432. $Val = crc32($Val);
  433. }
  434. if ($Val < 0) {
  435. $Val *= -1;
  436. }
  437. if ($Val == 0) {
  438. return;
  439. }
  440. mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
  441. }
  442. /**
  443. * Init random number generator
  444. *
  445. * This function initializes the random number generator fairly well.
  446. * It also only initializes it once, so you don't accidentally get
  447. * the same 'random' numbers twice in one session.
  448. *
  449. * @return void
  450. */
  451. function sq_mt_randomize() {
  452. static $randomized;
  453. if ($randomized) {
  454. return;
  455. }
  456. /* Global. */
  457. sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
  458. sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
  459. sq_mt_seed((int)((double) microtime() * 1000000));
  460. sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
  461. /* getrusage */
  462. if (function_exists('getrusage')) {
  463. /* Avoid warnings with Win32 */
  464. $dat = @getrusage();
  465. if (isset($dat) && is_array($dat)) {
  466. $Str = '';
  467. foreach ($dat as $k => $v)
  468. {
  469. $Str .= $k . $v;
  470. }
  471. sq_mt_seed(md5($Str));
  472. }
  473. }
  474. if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
  475. sq_mt_seed(md5($unique_id));
  476. }
  477. $randomized = 1;
  478. }
  479. /**
  480. * Creates encryption key
  481. *
  482. * Creates an encryption key for encrypting the password stored in the cookie.
  483. * The encryption key itself is stored in the session.
  484. *
  485. * @param int length optional, length of the string to generate
  486. * @return string the encryption key
  487. */
  488. function OneTimePadCreate ($length=100) {
  489. sq_mt_randomize();
  490. $pad = '';
  491. for ($i = 0; $i < $length; $i++) {
  492. $pad .= chr(mt_rand(0,255));
  493. }
  494. return base64_encode($pad);
  495. }
  496. /**
  497. * Returns a string showing the size of the message/attachment.
  498. *
  499. * @param int bytes the filesize in bytes
  500. * @return string the filesize in human readable format
  501. */
  502. function show_readable_size($bytes) {
  503. $bytes /= 1024;
  504. $type = 'k';
  505. if ($bytes / 1024 > 1) {
  506. $bytes /= 1024;
  507. $type = 'M';
  508. }
  509. if ($bytes < 10) {
  510. $bytes *= 10;
  511. settype($bytes, 'integer');
  512. $bytes /= 10;
  513. } else {
  514. settype($bytes, 'integer');
  515. }
  516. return $bytes . '<small>&nbsp;' . $type . '</small>';
  517. }
  518. /**
  519. * Generates a random string from the caracter set you pass in
  520. *
  521. * @param int size the size of the string to generate
  522. * @param string chars a string containing the characters to use
  523. * @param int flags a flag to add a specific set to the characters to use:
  524. * Flags:
  525. * 1 = add lowercase a-z to $chars
  526. * 2 = add uppercase A-Z to $chars
  527. * 4 = add numbers 0-9 to $chars
  528. * @return string the random string
  529. */
  530. function GenerateRandomString($size, $chars, $flags = 0) {
  531. if ($flags & 0x1) {
  532. $chars .= 'abcdefghijklmnopqrstuvwxyz';
  533. }
  534. if ($flags & 0x2) {
  535. $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  536. }
  537. if ($flags & 0x4) {
  538. $chars .= '0123456789';
  539. }
  540. if (($size < 1) || (strlen($chars) < 1)) {
  541. return '';
  542. }
  543. sq_mt_randomize(); /* Initialize the random number generator */
  544. $String = '';
  545. $j = strlen( $chars ) - 1;
  546. while (strlen($String) < $size) {
  547. $String .= $chars{mt_rand(0, $j)};
  548. }
  549. return $String;
  550. }
  551. /**
  552. * Escapes special characters for use in IMAP commands.
  553. *
  554. * @param string the string to escape
  555. * @return string the escaped string
  556. */
  557. function quoteimap($str) {
  558. // FIXME use this performance improvement (not changing because this is STABLE branch): return str_replace(array('\\', '"'), array('\\\\', '\\"'), $str);
  559. return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
  560. }
  561. /**
  562. * Trims array
  563. *
  564. * Trims every element in the array, ie. remove the first char of each element
  565. * Obsolete: will probably removed soon
  566. * @param array array the array to trim
  567. * @obsolete
  568. */
  569. function TrimArray(&$array) {
  570. foreach ($array as $k => $v) {
  571. global $$k;
  572. if (is_array($$k)) {
  573. foreach ($$k as $k2 => $v2) {
  574. $$k[$k2] = substr($v2, 1);
  575. }
  576. } else {
  577. $$k = substr($v, 1);
  578. }
  579. /* Re-assign back to array. */
  580. $array[$k] = $$k;
  581. }
  582. }
  583. /**
  584. * Removes slashes from every element in the array
  585. */
  586. function RemoveSlashes(&$array) {
  587. foreach ($array as $k => $v) {
  588. global $$k;
  589. if (is_array($$k)) {
  590. foreach ($$k as $k2 => $v2) {
  591. $newArray[stripslashes($k2)] = stripslashes($v2);
  592. }
  593. $$k = $newArray;
  594. } else {
  595. $$k = stripslashes($v);
  596. }
  597. /* Re-assign back to the array. */
  598. $array[$k] = $$k;
  599. }
  600. }
  601. /**
  602. * Create compose link
  603. *
  604. * Returns a link to the compose-page, taking in consideration
  605. * the compose_in_new and javascript settings.
  606. * @param string url the URL to the compose page
  607. * @param string text the link text, default "Compose"
  608. * @return string a link to the compose page
  609. */
  610. function makeComposeLink($url, $text = null, $target='')
  611. {
  612. global $compose_new_win,$javascript_on;
  613. if(!$text) {
  614. $text = _("Compose");
  615. }
  616. // if not using "compose in new window", make
  617. // regular link and be done with it
  618. if($compose_new_win != '1') {
  619. return makeInternalLink($url, $text, $target);
  620. }
  621. // build the compose in new window link...
  622. // if javascript is on, use onClick event to handle it
  623. if($javascript_on) {
  624. sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
  625. return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
  626. }
  627. // otherwise, just open new window using regular HTML
  628. return makeInternalLink($url, $text, '_blank');
  629. }
  630. /**
  631. * Print variable
  632. *
  633. * sm_print_r($some_variable, [$some_other_variable [, ...]]);
  634. *
  635. * Debugging function - does the same as print_r, but makes sure special
  636. * characters are converted to htmlentities first. This will allow
  637. * values like <some@email.address> to be displayed.
  638. * The output is wrapped in <<pre>> and <</pre>> tags.
  639. *
  640. * @return void
  641. */
  642. function sm_print_r() {
  643. ob_start(); // Buffer output
  644. foreach(func_get_args() as $var) {
  645. print_r($var);
  646. echo "\n";
  647. }
  648. $buffer = ob_get_contents(); // Grab the print_r output
  649. ob_end_clean(); // Silently discard the output & stop buffering
  650. print '<pre>';
  651. print htmlentities($buffer);
  652. print '</pre>';
  653. }
  654. /**
  655. * version of fwrite which checks for failure
  656. */
  657. function sq_fwrite($fp, $string) {
  658. // write to file
  659. $count = @fwrite($fp,$string);
  660. // the number of bytes written should be the length of the string
  661. if($count != strlen($string)) {
  662. return FALSE;
  663. }
  664. return $count;
  665. }
  666. /**
  667. * Tests if string contains 8bit symbols.
  668. *
  669. * If charset is not set, function defaults to default_charset.
  670. * $default_charset global must be set correctly if $charset is
  671. * not used.
  672. * @param string $string tested string
  673. * @param string $charset charset used in a string
  674. * @return bool true if 8bit symbols are detected
  675. * @since 1.5.1 and 1.4.4
  676. */
  677. function sq_is8bit($string,$charset='') {
  678. global $default_charset;
  679. if ($charset=='') $charset=$default_charset;
  680. /**
  681. * Don't use \240 in ranges. Sometimes RH 7.2 doesn't like it.
  682. * Don't use \200-\237 for iso-8859-x charsets. This ranges
  683. * stores control symbols in those charsets.
  684. * Use preg_match instead of ereg in order to avoid problems
  685. * with mbstring overloading
  686. */
  687. if (preg_match("/^iso-8859/i",$charset)) {
  688. $needle='/\240|[\241-\377]/';
  689. } else {
  690. $needle='/[\200-\237]|\240|[\241-\377]/';
  691. }
  692. return preg_match("$needle",$string);
  693. }
  694. /**
  695. * Function returns number of characters in string.
  696. *
  697. * Returned number might be different from number of bytes in string,
  698. * if $charset is multibyte charset. Detection depends on mbstring
  699. * functions. If mbstring does not support tested multibyte charset,
  700. * vanilla string length function is used.
  701. * @param string $str string
  702. * @param string $charset charset
  703. * @since 1.5.1 and 1.4.6
  704. * @return integer number of characters in string
  705. */
  706. function sq_strlen($string, $charset=NULL){
  707. // NULL charset? Just use strlen()
  708. //
  709. if (is_null($charset))
  710. return strlen($string);
  711. // use current character set?
  712. //
  713. if ($charset == 'auto')
  714. {
  715. //FIXME: this may or may not be better as a session value instead of a global one
  716. global $sq_string_func_auto_charset;
  717. if (!isset($sq_string_func_auto_charset))
  718. {
  719. global $default_charset, $squirrelmail_language;
  720. set_my_charset();
  721. $sq_string_func_auto_charset = $default_charset;
  722. if ($squirrelmail_language == 'ja_JP') $sq_string_func_auto_charset = 'euc-jp';
  723. }
  724. $charset = $sq_string_func_auto_charset;
  725. }
  726. // standardize character set name
  727. //
  728. $charset = strtolower($charset);
  729. /* ===== FIXME: this list is not used in 1.5.x, but if we need it, unless this differs between all our string function wrappers, we should store this info in the session
  730. // only use mbstring with the following character sets
  731. //
  732. $sq_strlen_mb_charsets = array(
  733. 'utf-8',
  734. 'big5',
  735. 'gb2312',
  736. 'gb18030',
  737. 'euc-jp',
  738. 'euc-cn',
  739. 'euc-tw',
  740. 'euc-kr'
  741. );
  742. // now we can use mb_strlen() if needed
  743. //
  744. if (in_array($charset, $sq_strlen_mb_charsets)
  745. && in_array($charset, sq_mb_list_encodings()))
  746. ===== */
  747. //FIXME: is there any reason why this cannot be a static global array used by all string wrapper functions?
  748. if (in_array($charset, sq_mb_list_encodings()))
  749. return mb_strlen($string, $charset);
  750. // else use normal strlen()
  751. //
  752. return strlen($string);
  753. }
  754. /**
  755. * This is a replacement for PHP's strpos() that is
  756. * multibyte-aware.
  757. *
  758. * @param string $haystack The string to search within
  759. * @param string $needle The substring to search for
  760. * @param int $offset The offset from the beginning of $haystack
  761. * from which to start searching
  762. * (OPTIONAL; default none)
  763. * @param string $charset The charset of the given string. A value of NULL
  764. * here will force the use of PHP's standard strpos().
  765. * (OPTIONAL; default is "auto", which indicates that
  766. * the user's current charset should be used).
  767. *
  768. * @return mixed The integer offset of the next $needle in $haystack,
  769. * if found, or FALSE if not found
  770. *
  771. */
  772. function sq_strpos($haystack, $needle, $offset=0, $charset='auto')
  773. {
  774. // NULL charset? Just use strpos()
  775. //
  776. if (is_null($charset))
  777. return strpos($haystack, $needle, $offset);
  778. // use current character set?
  779. //
  780. if ($charset == 'auto')
  781. {
  782. //FIXME: this may or may not be better as a session value instead of a global one
  783. global $sq_string_func_auto_charset;
  784. if (!isset($sq_string_func_auto_charset))
  785. {
  786. global $default_charset, $squirrelmail_language;
  787. set_my_charset();
  788. $sq_string_func_auto_charset = $default_charset;
  789. if ($squirrelmail_language == 'ja_JP') $sq_string_func_auto_charset = 'euc-jp';
  790. }
  791. $charset = $sq_string_func_auto_charset;
  792. }
  793. // standardize character set name
  794. //
  795. $charset = strtolower($charset);
  796. /* ===== FIXME: this list is not used in 1.5.x, but if we need it, unless this differs between all our string function wrappers, we should store this info in the session
  797. // only use mbstring with the following character sets
  798. //
  799. $sq_strpos_mb_charsets = array(
  800. 'utf-8',
  801. 'big5',
  802. 'gb2312',
  803. 'gb18030',
  804. 'euc-jp',
  805. 'euc-cn',
  806. 'euc-tw',
  807. 'euc-kr'
  808. );
  809. // now we can use mb_strpos() if needed
  810. //
  811. if (in_array($charset, $sq_strpos_mb_charsets)
  812. && in_array($charset, sq_mb_list_encodings()))
  813. ===== */
  814. //FIXME: is there any reason why this cannot be a static global array used by all string wrapper functions?
  815. if (in_array($charset, sq_mb_list_encodings()))
  816. return mb_strpos($haystack, $needle, $offset, $charset);
  817. // else use normal strpos()
  818. //
  819. return strpos($haystack, $needle, $offset);
  820. }
  821. /**
  822. * This is a replacement for PHP's substr() that is
  823. * multibyte-aware.
  824. *
  825. * @param string $string The string to operate upon
  826. * @param int $start The offset at which to begin substring extraction
  827. * @param int $length The number of characters after $start to return
  828. * NOTE that if you need to specify a charset but
  829. * want to achieve normal substr() behavior where
  830. * $length is not specified, use NULL (OPTIONAL;
  831. * default from $start to end of string)
  832. * @param string $charset The charset of the given string. A value of NULL
  833. * here will force the use of PHP's standard substr().
  834. * (OPTIONAL; default is "auto", which indicates that
  835. * the user's current charset should be used).
  836. *
  837. * @return string The desired substring
  838. *
  839. * Of course, you can use more advanced (e.g., negative) values
  840. * for $start and $length as needed - see the PHP manual for more
  841. * information: http://www.php.net/manual/function.substr.php
  842. *
  843. */
  844. function sq_substr($string, $start, $length=NULL, $charset='auto')
  845. {
  846. // if $length is NULL, use the full string length...
  847. // we have to do this to mimick the use of substr()
  848. // where $length is not given
  849. //
  850. if (is_null($length))
  851. $length = sq_strlen($length, $charset);
  852. // NULL charset? Just use substr()
  853. //
  854. if (is_null($charset))
  855. return substr($string, $start, $length);
  856. // use current character set?
  857. //
  858. if ($charset == 'auto')
  859. {
  860. //FIXME: this may or may not be better as a session value instead of a global one
  861. global $sq_string_func_auto_charset;
  862. if (!isset($sq_string_func_auto_charset))
  863. {
  864. global $default_charset, $squirrelmail_language;
  865. set_my_charset();
  866. $sq_string_func_auto_charset = $default_charset;
  867. if ($squirrelmail_language == 'ja_JP') $sq_string_func_auto_charset = 'euc-jp';
  868. }
  869. $charset = $sq_string_func_auto_charset;
  870. }
  871. // standardize character set name
  872. //
  873. $charset = strtolower($charset);
  874. /* ===== FIXME: this list is not used in 1.5.x, but if we need it, unless this differs between all our string function wrappers, we should store this info in the session
  875. // only use mbstring with the following character sets
  876. //
  877. $sq_substr_mb_charsets = array(
  878. 'utf-8',
  879. 'big5',
  880. 'gb2312',
  881. 'gb18030',
  882. 'euc-jp',
  883. 'euc-cn',
  884. 'euc-tw',
  885. 'euc-kr'
  886. );
  887. // now we can use mb_substr() if needed
  888. //
  889. if (in_array($charset, $sq_substr_mb_charsets)
  890. && in_array($charset, sq_mb_list_encodings()))
  891. ===== */
  892. //FIXME: is there any reason why this cannot be a global array used by all string wrapper functions?
  893. if (in_array($charset, sq_mb_list_encodings()))
  894. return mb_substr($string, $start, $length, $charset);
  895. // else use normal substr()
  896. //
  897. return substr($string, $start, $length);
  898. }
  899. /**
  900. * This is a replacement for PHP's substr_replace() that is
  901. * multibyte-aware.
  902. *
  903. * @param string $string The string to operate upon
  904. * @param string $replacement The string to be inserted
  905. * @param int $start The offset at which to begin substring replacement
  906. * @param int $length The number of characters after $start to remove
  907. * NOTE that if you need to specify a charset but
  908. * want to achieve normal substr_replace() behavior
  909. * where $length is not specified, use NULL (OPTIONAL;
  910. * default from $start to end of string)
  911. * @param string $charset The charset of the given string. A value of NULL
  912. * here will force the use of PHP's standard substr().
  913. * (OPTIONAL; default is "auto", which indicates that
  914. * the user's current charset should be used).
  915. *
  916. * @return string The manipulated string
  917. *
  918. * Of course, you can use more advanced (e.g., negative) values
  919. * for $start and $length as needed - see the PHP manual for more
  920. * information: http://www.php.net/manual/function.substr-replace.php
  921. *
  922. */
  923. function sq_substr_replace($string, $replacement, $start, $length=NULL,
  924. $charset='auto')
  925. {
  926. // NULL charset? Just use substr_replace()
  927. //
  928. if (is_null($charset))
  929. return is_null($length) ? substr_replace($string, $replacement, $start)
  930. : substr_replace($string, $replacement, $start, $length);
  931. // use current character set?
  932. //
  933. if ($charset == 'auto')
  934. {
  935. //FIXME: this may or may not be better as a session value instead of a global one
  936. $charset = $auto_charset;
  937. global $sq_string_func_auto_charset;
  938. if (!isset($sq_string_func_auto_charset))
  939. {
  940. global $default_charset, $squirrelmail_language;
  941. set_my_charset();
  942. $sq_string_func_auto_charset = $default_charset;
  943. if ($squirrelmail_language == 'ja_JP') $sq_string_func_auto_charset = 'euc-jp';
  944. }
  945. $charset = $sq_string_func_auto_charset;
  946. }
  947. // standardize character set name
  948. //
  949. $charset = strtolower($charset);
  950. /* ===== FIXME: this list is not used in 1.5.x, but if we need it, unless this differs between all our string function wrappers, we should store this info in the session
  951. // only use mbstring with the following character sets
  952. //
  953. $sq_substr_replace_mb_charsets = array(
  954. 'utf-8',
  955. 'big5',
  956. 'gb2312',
  957. 'gb18030',
  958. 'euc-jp',
  959. 'euc-cn',
  960. 'euc-tw',
  961. 'euc-kr'
  962. );
  963. // now we can use our own implementation using
  964. // mb_substr() and mb_strlen() if needed
  965. //
  966. if (in_array($charset, $sq_substr_replace_mb_charsets)
  967. && in_array($charset, sq_mb_list_encodings()))
  968. ===== */
  969. //FIXME: is there any reason why this cannot be a global array used by all string wrapper functions?
  970. if (in_array($charset, sq_mb_list_encodings()))
  971. {
  972. $string_length = mb_strlen($string, $charset);
  973. if ($start < 0)
  974. $start = max(0, $string_length + $start);
  975. else if ($start > $string_length)
  976. $start = $string_length;
  977. if ($length < 0)
  978. $length = max(0, $string_length - $start + $length);
  979. else if (is_null($length) || $length > $string_length)
  980. $length = $string_length;
  981. if ($start + $length > $string_length)
  982. $length = $string_length - $start;
  983. return mb_substr($string, 0, $start, $charset)
  984. . $replacement
  985. . mb_substr($string,
  986. $start + $length,
  987. $string_length, // FIXME: I can't see why this is needed: - $start - $length,
  988. $charset);
  989. }
  990. // else use normal substr_replace()
  991. //
  992. return is_null($length) ? substr_replace($string, $replacement, $start)
  993. : substr_replace($string, $replacement, $start, $length);
  994. }
  995. /**
  996. * Replacement of mb_list_encodings function
  997. *
  998. * This function provides replacement for function that is available only
  999. * in php 5.x. Function does not test all mbstring encodings. Only the ones
  1000. * that might be used in SM translations.
  1001. *
  1002. * Supported strings are stored in session in order to reduce number of
  1003. * mb_internal_encoding function calls.
  1004. *
  1005. * If mb_list_encodings() function is present, code uses it. Main difference
  1006. * from original function behaviour - array values are lowercased in order to
  1007. * simplify use of returned array in in_array() checks.
  1008. *
  1009. * If you want to test all mbstring encodings - fill $list_of_encodings
  1010. * array.
  1011. * @return array list of encodings supported by php mbstring extension
  1012. * @since 1.5.1 and 1.4.6
  1013. */
  1014. function sq_mb_list_encodings() {
  1015. // if it's already in the session, don't need to regenerate it
  1016. if (sqgetGlobalVar('mb_supported_encodings',$mb_supported_encodings,SQ_SESSION)
  1017. && is_array($mb_supported_encodings))
  1018. return $mb_supported_encodings;
  1019. // check if mbstring extension is present
  1020. if (! function_exists('mb_internal_encoding')) {
  1021. $supported_encodings = array();
  1022. sqsession_register($supported_encodings, 'mb_supported_encodings');
  1023. return $supported_encodings;
  1024. }
  1025. // php 5+ function
  1026. if (function_exists('mb_list_encodings')) {
  1027. $supported_encodings = mb_list_encodings();
  1028. array_walk($supported_encodings, 'sq_lowercase_array_vals');
  1029. sqsession_register($supported_encodings, 'mb_supported_encodings');
  1030. return $supported_encodings;
  1031. }
  1032. // save original encoding
  1033. $orig_encoding=mb_internal_encoding();
  1034. $list_of_encoding=array(
  1035. 'pass',
  1036. 'auto',
  1037. 'ascii',
  1038. 'jis',
  1039. 'utf-8',
  1040. 'sjis',
  1041. 'euc-jp',
  1042. 'iso-8859-1',
  1043. 'iso-8859-2',
  1044. 'iso-8859-7',
  1045. 'iso-8859-9',
  1046. 'iso-8859-15',
  1047. 'koi8-r',
  1048. 'koi8-u',
  1049. 'big5',
  1050. 'gb2312',
  1051. 'gb18030',
  1052. 'windows-1251',
  1053. 'windows-1255',
  1054. 'windows-1256',
  1055. 'tis-620',
  1056. 'iso-2022-jp',
  1057. 'euc-cn',
  1058. 'euc-kr',
  1059. 'euc-tw',
  1060. 'uhc',
  1061. 'utf7-imap');
  1062. $supported_encodings=array();
  1063. foreach ($list_of_encoding as $encoding) {
  1064. // try setting encodings. suppress warning messages
  1065. if (@mb_internal_encoding($encoding))
  1066. $supported_encodings[]=$encoding;
  1067. }
  1068. // restore original encoding
  1069. mb_internal_encoding($orig_encoding);
  1070. // register list in session
  1071. sqsession_register($supported_encodings, 'mb_supported_encodings');
  1072. return $supported_encodings;
  1073. }
  1074. /**
  1075. * Callback function used to lowercase array values.
  1076. * @param string $val array value
  1077. * @param mixed $key array key
  1078. * @since 1.5.1 and 1.4.6
  1079. */
  1080. function sq_lowercase_array_vals(&$val,$key) {
  1081. $val = strtolower($val);
  1082. }
  1083. /**
  1084. * Callback function to trim whitespace from a value, to be used in array_walk
  1085. * @param string $value value to trim
  1086. * @since 1.5.2 and 1.4.7
  1087. */
  1088. function sq_trim_value ( &$value ) {
  1089. $value = trim($value);
  1090. }
  1091. /**
  1092. * Gathers the list of secuirty tokens currently
  1093. * stored in the user's preferences and optionally
  1094. * purges old ones from the list.
  1095. *
  1096. * @param boolean $purge_old Indicates if old tokens
  1097. * should be purged from the
  1098. * list ("old" is 2 days or
  1099. * older unless the administrator
  1100. * overrides that value using
  1101. * $max_token_age_days in
  1102. * config/config_local.php)
  1103. * (OPTIONAL; default is to always
  1104. * purge old tokens)
  1105. *
  1106. * @return array The list of tokens
  1107. *
  1108. * @since 1.4.19 and 1.5.2
  1109. *
  1110. */
  1111. function sm_get_user_security_tokens($purge_old=TRUE)
  1112. {
  1113. global $data_dir, $username, $max_token_age_days;
  1114. $tokens = getPref($data_dir, $username, 'security_tokens', '');
  1115. if (($tokens = unserialize($tokens)) === FALSE || !is_array($tokens))
  1116. $tokens = array();
  1117. // purge old tokens if necessary
  1118. //
  1119. if ($purge_old)
  1120. {
  1121. if (empty($max_token_age_days)) $max_token_age_days = 2;
  1122. $now = time();
  1123. $discard_token_date = $now - ($max_token_age_days * 86400);
  1124. $cleaned_tokens = array();
  1125. foreach ($tokens as $token => $timestamp)
  1126. if ($timestamp >= $discard_token_date)
  1127. $cleaned_tokens[$token] = $timestamp;
  1128. $tokens = $cleaned_tokens;
  1129. }
  1130. return $tokens;
  1131. }
  1132. /**
  1133. * Generates a security token that is then stored in
  1134. * the user's preferences with a timestamp for later
  1135. * verification/use.
  1136. *
  1137. * WARNING: If the administrator has turned the token system
  1138. * off by setting $disable_security_tokens to TRUE in
  1139. * config/config.php or the configuration tool, this
  1140. * function will not store tokens in the user
  1141. * preferences (but it will still generate and return
  1142. * a random string).
  1143. *
  1144. * @return string A security token
  1145. *
  1146. * @since 1.4.19 and 1.5.2
  1147. *
  1148. */
  1149. function sm_generate_security_token()
  1150. {
  1151. global $data_dir, $username, $disable_security_tokens;
  1152. $max_generation_tries = 1000;
  1153. $tokens = sm_get_user_security_tokens();
  1154. $new_token = GenerateRandomString(12, '', 7);
  1155. $count = 0;
  1156. while (isset($tokens[$new_token]))
  1157. {
  1158. $new_token = GenerateRandomString(12, '', 7);
  1159. if (++$count > $max_generation_tries)
  1160. {
  1161. logout_error(_("Fatal token generation error; please contact your system administrator or the SquirrelMail Team"));
  1162. exit;
  1163. }
  1164. }
  1165. // is the token system enabled? CAREFUL!
  1166. //
  1167. if (!$disable_security_tokens)
  1168. {
  1169. $tokens[$new_token] = time();
  1170. setPref($data_dir, $username, 'security_tokens', serialize($tokens));
  1171. }
  1172. return $new_token;
  1173. }
  1174. /**
  1175. * Validates a given security token and optionally remove it
  1176. * from the user's preferences if it was valid. If the token
  1177. * is too old but otherwise valid, it will still be rejected.
  1178. *
  1179. * "Too old" is 2 days or older unless the administrator
  1180. * overrides that value using $max_token_age_days in
  1181. * config/config_local.php
  1182. *
  1183. * WARNING: If the administrator has turned the token system
  1184. * off by setting $disable_security_tokens to TRUE in
  1185. * config/config.php or the configuration tool, this
  1186. * function will always return TRUE.
  1187. *
  1188. * @param string $token The token to validate
  1189. * @param int $validity_period The number of seconds tokens are valid
  1190. * for (set to zero to remove valid tokens
  1191. * after only one use; use 3600 to allow
  1192. * tokens to be reused for an hour)
  1193. * (OPTIONAL; default is to only allow tokens
  1194. * to be used once)
  1195. * @param boolean $show_error Indicates that if the token is not
  1196. * valid, this function should display
  1197. * a generic error, log the user out
  1198. * and exit - this function will never
  1199. * return in that case.
  1200. * (OPTIONAL; default FALSE)
  1201. *
  1202. * @return boolean TRUE if the token validated; FALSE otherwise
  1203. *
  1204. * @since 1.4.19 and 1.5.2
  1205. *
  1206. */
  1207. function sm_validate_security_token($token, $validity_period=0, $show_error=FALSE)
  1208. {
  1209. global $data_dir, $username, $max_token_age_days,
  1210. $disable_security_tokens;
  1211. // bypass token validation? CAREFUL!
  1212. //
  1213. if ($disable_security_tokens) return TRUE;
  1214. // don't purge old tokens here because we already
  1215. // do it when generating tokens
  1216. //
  1217. $tokens = sm_get_user_security_tokens(FALSE);
  1218. // token not found?
  1219. //
  1220. if (empty($tokens[$token]))
  1221. {
  1222. if (!$show_error) return FALSE;
  1223. logout_error(_("This page request could not be verified and appears to have expired."));
  1224. exit;
  1225. }
  1226. $now = time();
  1227. $timestamp = $tokens[$token];
  1228. // whether valid or not, we want to remove it from
  1229. // user prefs if it's old enough
  1230. //
  1231. if ($timestamp < $now - $validity_period)
  1232. {
  1233. unset($tokens[$token]);
  1234. setPref($data_dir, $username, 'security_tokens', serialize($tokens));
  1235. }
  1236. // reject tokens that are too old
  1237. //
  1238. if (empty($max_token_age_days)) $max_token_age_days = 2;
  1239. $old_token_date = $now - ($max_token_age_days * 86400);
  1240. if ($timestamp < $old_token_date)
  1241. {
  1242. if (!$show_error) return FALSE;
  1243. logout_error(_("The current page request appears to have originated from an untrusted source."));
  1244. exit;
  1245. }
  1246. // token OK!
  1247. //
  1248. return TRUE;
  1249. }
  1250. $PHP_SELF = php_self();