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

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

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