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

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

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