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

/branches/GSoC-config/squirrelmail/functions/strings.php

#
PHP | 1289 lines | 912 code | 89 blank | 288 comment | 165 complexity | f90bc64e854b87195a0b0887252c2fb2 MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0
  1. <?php
  2. /**
  3. * strings.php
  4. *
  5. * This code provides various string manipulation functions that are
  6. * used by the rest of the SquirrelMail code.
  7. *
  8. * @copyright &copy; 1999-2007 The SquirrelMail Project Team
  9. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  10. * @version $Id: strings.php 12128 2007-01-13 20:15:44Z kink $
  11. * @package squirrelmail
  12. */
  13. /**
  14. * Appends citation markers to the string.
  15. * Also appends a trailing space.
  16. *
  17. * @author Justus Pendleton
  18. * @param string $str The string to append to
  19. * @param int $citeLevel the number of markers to append
  20. * @return null
  21. * @since 1.5.1
  22. */
  23. function sqMakeCite (&$str, $citeLevel) {
  24. for ($i = 0; $i < $citeLevel; $i++) {
  25. $str .= '>';
  26. }
  27. if ($citeLevel != 0) {
  28. $str .= ' ';
  29. }
  30. }
  31. /**
  32. * Create a newline in the string, adding citation
  33. * markers to the newline as necessary.
  34. *
  35. * @author Justus Pendleton
  36. * @param string $str the string to make a newline in
  37. * @param int $citeLevel the citation level the newline is at
  38. * @param int $column starting column of the newline
  39. * @return null
  40. * @since 1.5.1
  41. */
  42. function sqMakeNewLine (&$str, $citeLevel, &$column) {
  43. $str .= "\n";
  44. $column = 0;
  45. if ($citeLevel > 0) {
  46. sqMakeCite ($str, $citeLevel);
  47. $column = $citeLevel + 1;
  48. } else {
  49. $column = 0;
  50. }
  51. }
  52. /**
  53. * Checks for spaces in strings - only used if PHP doesn't have native ctype support
  54. *
  55. * You might be able to rewrite the function by adding short evaluation form.
  56. *
  57. * possible problems:
  58. * - iso-2022-xx charsets - hex 20 might be part of other symbol. I might
  59. * be wrong. 0x20 is not used in iso-2022-jp. I haven't checked iso-2022-kr
  60. * and iso-2022-cn mappings.
  61. *
  62. * - no-break space (&nbsp;) - it is 8bit symbol, that depends on charset.
  63. * there are at least three different charset groups that have nbsp in
  64. * different places.
  65. *
  66. * I don't see any charset/nbsp options in php ctype either.
  67. *
  68. * @param string $string tested string
  69. * @return bool true when only whitespace symbols are present in test string
  70. * @since 1.5.1
  71. */
  72. function sm_ctype_space($string) {
  73. if ( preg_match('/^[\x09-\x0D]|^\x20/', $string) || $string=='') {
  74. return true;
  75. } else {
  76. return false;
  77. }
  78. }
  79. /**
  80. * Wraps text at $wrap characters. While sqWordWrap takes
  81. * a single line of text and wraps it, this function works
  82. * on the entire corpus at once, this allows it to be a little
  83. * bit smarter and when and how to wrap.
  84. *
  85. * @author Justus Pendleton
  86. * @param string $body the entire body of text
  87. * @param int $wrap the maximum line length
  88. * @return string the wrapped text
  89. * @since 1.5.1
  90. */
  91. function &sqBodyWrap (&$body, $wrap) {
  92. //check for ctype support, and fake it if it doesn't exist
  93. if (!function_exists('ctype_space')) {
  94. function ctype_space ($string) {
  95. return sm_ctype_space($string);
  96. }
  97. }
  98. // the newly wrapped text
  99. $outString = '';
  100. // current column since the last newline in the outstring
  101. $outStringCol = 0;
  102. $length = sq_strlen($body);
  103. // where we are in the original string
  104. $pos = 0;
  105. // the number of >>> citation markers we are currently at
  106. $citeLevel = 0;
  107. // the main loop, whenever we start a newline of input text
  108. // we start from here
  109. while ($pos < $length) {
  110. // we're at the beginning of a line, get the new cite level
  111. $newCiteLevel = 0;
  112. while (($pos < $length) && (sq_substr($body,$pos,1) == '>')) {
  113. $newCiteLevel++;
  114. $pos++;
  115. // skip over any spaces interleaved among the cite markers
  116. while (($pos < $length) && (sq_substr($body,$pos,1) == ' ')) {
  117. $pos++;
  118. }
  119. if ($pos >= $length) {
  120. break;
  121. }
  122. }
  123. // special case: if this is a blank line then maintain it
  124. // (i.e. try to preserve original paragraph breaks)
  125. // unless they occur at the very beginning of the text
  126. if ((sq_substr($body,$pos,1) == "\n" ) && (sq_strlen($outString) != 0)) {
  127. $outStringLast = $outString{sq_strlen($outString) - 1};
  128. if ($outStringLast != "\n") {
  129. $outString .= "\n";
  130. }
  131. sqMakeCite ($outString, $newCiteLevel);
  132. $outString .= "\n";
  133. $pos++;
  134. $outStringCol = 0;
  135. continue;
  136. }
  137. // if the cite level has changed, then start a new line
  138. // with the new cite level.
  139. if (($citeLevel != $newCiteLevel) && ($pos > ($newCiteLevel + 1)) && ($outStringCol != 0)) {
  140. sqMakeNewLine ($outString, 0, $outStringCol);
  141. }
  142. $citeLevel = $newCiteLevel;
  143. // prepend the quote level if necessary
  144. if ($outStringCol == 0) {
  145. sqMakeCite ($outString, $citeLevel);
  146. // if we added a citation then move the column
  147. // out by citelevel + 1 (the cite markers + the space)
  148. $outStringCol = $citeLevel + ($citeLevel ? 1 : 0);
  149. } else if ($outStringCol > $citeLevel) {
  150. // not a cite and we're not at the beginning of a line
  151. // in the output. add a space to separate the new text
  152. // from previous text.
  153. $outString .= ' ';
  154. $outStringCol++;
  155. }
  156. // find the next newline -- we don't want to go further than that
  157. $nextNewline = sq_strpos ($body, "\n", $pos);
  158. if ($nextNewline === FALSE) {
  159. $nextNewline = $length;
  160. }
  161. // Don't wrap unquoted lines at all. For now the textarea
  162. // will work fine for this. Maybe revisit this later though
  163. // (for completeness more than anything else, I think)
  164. if ($citeLevel == 0) {
  165. $outString .= sq_substr ($body, $pos, ($nextNewline - $pos));
  166. $outStringCol = $nextNewline - $pos;
  167. if ($nextNewline != $length) {
  168. sqMakeNewLine ($outString, 0, $outStringCol);
  169. }
  170. $pos = $nextNewline + 1;
  171. continue;
  172. }
  173. /**
  174. * Set this to false to stop appending short strings to previous lines
  175. */
  176. $smartwrap = true;
  177. // inner loop, (obviously) handles wrapping up to
  178. // the next newline
  179. while ($pos < $nextNewline) {
  180. // skip over initial spaces
  181. while (($pos < $nextNewline) && (ctype_space (sq_substr($body,$pos,1)))) {
  182. $pos++;
  183. }
  184. // if this is a short line then just append it and continue outer loop
  185. if (($outStringCol + $nextNewline - $pos) <= ($wrap - $citeLevel - 1) ) {
  186. // if this is the final line in the input string then include
  187. // any trailing newlines
  188. // echo substr($body,$pos,$wrap). "<br />";
  189. if (($nextNewline + 1 == $length) && (sq_substr($body,$nextNewline,1) == "\n")) {
  190. $nextNewline++;
  191. }
  192. // trim trailing spaces
  193. $lastRealChar = $nextNewline;
  194. while (($lastRealChar > $pos && $lastRealChar < $length) && (ctype_space (sq_substr($body,$lastRealChar,1)))) {
  195. $lastRealChar--;
  196. }
  197. // decide if appending the short string is what we want
  198. if (($nextNewline < $length && sq_substr($body,$nextNewline,1) == "\n") &&
  199. isset($lastRealChar)) {
  200. $mypos = $pos;
  201. //check the first word:
  202. while (($mypos < $length) && (sq_substr($body,$mypos,1) == '>')) {
  203. $mypos++;
  204. // skip over any spaces interleaved among the cite markers
  205. while (($mypos < $length) && (sq_substr($body,$mypos,1) == ' ')) {
  206. $mypos++;
  207. }
  208. }
  209. /*
  210. $ldnspacecnt = 0;
  211. if ($mypos == $nextNewline+1) {
  212. while (($mypos < $length) && ($body{$mypos} == ' ')) {
  213. $ldnspacecnt++;
  214. }
  215. }
  216. */
  217. $firstword = sq_substr($body,$mypos,sq_strpos($body,' ',$mypos) - $mypos);
  218. //if ($dowrap || $ldnspacecnt > 1 || ($firstword && (
  219. if (!$smartwrap || $firstword && (
  220. $firstword{0} == '-' ||
  221. $firstword{0} == '+' ||
  222. $firstword{0} == '*' ||
  223. sq_substr($firstword,0,1) == sq_strtoupper(sq_substr($firstword,0,1)) ||
  224. strpos($firstword,':'))) {
  225. $outString .= sq_substr($body,$pos,($lastRealChar - $pos+1));
  226. $outStringCol += ($lastRealChar - $pos);
  227. sqMakeNewLine($outString,$citeLevel,$outStringCol);
  228. $nextNewline++;
  229. $pos = $nextNewline;
  230. $outStringCol--;
  231. continue;
  232. }
  233. }
  234. $outString .= sq_substr ($body, $pos, ($lastRealChar - $pos + 1));
  235. $outStringCol += ($lastRealChar - $pos);
  236. $pos = $nextNewline + 1;
  237. continue;
  238. }
  239. $eol = $pos + $wrap - $citeLevel - $outStringCol;
  240. // eol is the tentative end of line.
  241. // look backwards for there for a whitespace to break at.
  242. // if it's already less than our current position then
  243. // our current line is already too long, break immediately
  244. // and restart outer loop
  245. if ($eol <= $pos) {
  246. sqMakeNewLine ($outString, $citeLevel, $outStringCol);
  247. continue;
  248. }
  249. // start looking backwards for whitespace to break at.
  250. $breakPoint = $eol;
  251. while (($breakPoint > $pos) && (! ctype_space (sq_substr($body,$breakPoint,1)))) {
  252. $breakPoint--;
  253. }
  254. // if we didn't find a breakpoint by looking backward then we
  255. // need to figure out what to do about that
  256. if ($breakPoint == $pos) {
  257. // if we are not at the beginning then end this line
  258. // and start a new loop
  259. if ($outStringCol > ($citeLevel + 1)) {
  260. sqMakeNewLine ($outString, $citeLevel, $outStringCol);
  261. continue;
  262. } else {
  263. // just hard break here. most likely we are breaking
  264. // a really long URL. could also try searching
  265. // forward for a break point, which is what Mozilla
  266. // does. don't bother for now.
  267. $breakPoint = $eol;
  268. }
  269. }
  270. // special case: maybe we should have wrapped last
  271. // time. if the first breakpoint here makes the
  272. // current line too long and there is already text on
  273. // the current line, break and loop again if at
  274. // beginning of current line, don't force break
  275. $SLOP = 6;
  276. if ((($outStringCol + ($breakPoint - $pos)) > ($wrap + $SLOP)) && ($outStringCol > ($citeLevel + 1))) {
  277. sqMakeNewLine ($outString, $citeLevel, $outStringCol);
  278. continue;
  279. }
  280. // skip newlines or whitespace at the beginning of the string
  281. $substring = sq_substr ($body, $pos, ($breakPoint - $pos));
  282. $substring = rtrim ($substring); // do rtrim and ctype_space have the same ideas about whitespace?
  283. $outString .= $substring;
  284. $outStringCol += sq_strlen ($substring);
  285. // advance past the whitespace which caused the wrap
  286. $pos = $breakPoint;
  287. while (($pos < $length) && (ctype_space (sq_substr($body,$pos,1)))) {
  288. $pos++;
  289. }
  290. if ($pos < $length) {
  291. sqMakeNewLine ($outString, $citeLevel, $outStringCol);
  292. }
  293. }
  294. }
  295. return $outString;
  296. }
  297. /**
  298. * Wraps text at $wrap characters
  299. *
  300. * Has a problem with special HTML characters, so call this before
  301. * you do character translation.
  302. *
  303. * Specifically, &amp;#039; comes up as 5 characters instead of 1.
  304. * This should not add newlines to the end of lines.
  305. *
  306. * @param string $line the line of text to wrap, by ref
  307. * @param int $wrap the maximum line lenth
  308. * @param string $charset name of charset used in $line string. Available since v.1.5.1.
  309. * @return void
  310. * @since 1.0
  311. */
  312. function sqWordWrap(&$line, $wrap, $charset='') {
  313. global $languages, $squirrelmail_language;
  314. // Use custom wrapping function, if translation provides it
  315. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  316. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap')) {
  317. if (mb_detect_encoding($line) != 'ASCII') {
  318. $line = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap', $line, $wrap);
  319. return;
  320. }
  321. }
  322. ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
  323. $beginning_spaces = $regs[1];
  324. if (isset($regs[2])) {
  325. $words = explode(' ', $regs[2]);
  326. } else {
  327. $words = '';
  328. }
  329. $i = 0;
  330. $line = $beginning_spaces;
  331. while ($i < count($words)) {
  332. /* Force one word to be on a line (minimum) */
  333. $line .= $words[$i];
  334. $line_len = strlen($beginning_spaces) + sq_strlen($words[$i],$charset) + 2;
  335. if (isset($words[$i + 1]))
  336. $line_len += sq_strlen($words[$i + 1],$charset);
  337. $i ++;
  338. /* Add more words (as long as they fit) */
  339. while ($line_len < $wrap && $i < count($words)) {
  340. $line .= ' ' . $words[$i];
  341. $i++;
  342. if (isset($words[$i]))
  343. $line_len += sq_strlen($words[$i],$charset) + 1;
  344. else
  345. $line_len += 1;
  346. }
  347. /* Skip spaces if they are the first thing on a continued line */
  348. while (!isset($words[$i]) && $i < count($words)) {
  349. $i ++;
  350. }
  351. /* Go to the next line if we have more to process */
  352. if ($i < count($words)) {
  353. $line .= "\n";
  354. }
  355. }
  356. }
  357. /**
  358. * Does the opposite of sqWordWrap()
  359. * @param string $body the text to un-wordwrap
  360. * @return void
  361. * @since 1.0
  362. */
  363. function sqUnWordWrap(&$body) {
  364. global $squirrelmail_language;
  365. if ($squirrelmail_language == 'ja_JP') {
  366. return;
  367. }
  368. $lines = explode("\n", $body);
  369. $body = '';
  370. $PreviousSpaces = '';
  371. $cnt = count($lines);
  372. for ($i = 0; $i < $cnt; $i ++) {
  373. preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
  374. $CurrentSpaces = $regs[1];
  375. if (isset($regs[2])) {
  376. $CurrentRest = $regs[2];
  377. } else {
  378. $CurrentRest = '';
  379. }
  380. if ($i == 0) {
  381. $PreviousSpaces = $CurrentSpaces;
  382. $body = $lines[$i];
  383. } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
  384. && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
  385. && strlen($CurrentRest)) { /* and there's a line to continue with */
  386. $body .= ' ' . $CurrentRest;
  387. } else {
  388. $body .= "\n" . $lines[$i];
  389. $PreviousSpaces = $CurrentSpaces;
  390. }
  391. }
  392. $body .= "\n";
  393. }
  394. /**
  395. * If $haystack is a full mailbox name and $needle is the mailbox
  396. * separator character, returns the last part of the mailbox name.
  397. *
  398. * @param string haystack full mailbox name to search
  399. * @param string needle the mailbox separator character
  400. * @return string the last part of the mailbox name
  401. * @since 1.0
  402. */
  403. function readShortMailboxName($haystack, $needle) {
  404. if ($needle == '') {
  405. $elem = $haystack;
  406. } else {
  407. $parts = explode($needle, $haystack);
  408. $elem = array_pop($parts);
  409. while ($elem == '' && count($parts)) {
  410. $elem = array_pop($parts);
  411. }
  412. }
  413. return( $elem );
  414. }
  415. /**
  416. * get_location
  417. *
  418. * Determines the location to forward to, relative to your server.
  419. * This is used in HTTP Location: redirects.
  420. *
  421. * If set, it uses $config_location_base as the first part of the URL,
  422. * specifically, the protocol, hostname and port parts. The path is
  423. * always autodetected.
  424. *
  425. * @return string the base url for this SquirrelMail installation
  426. * @since 1.0
  427. */
  428. function get_location () {
  429. global $imap_server_type, $config_location_base;
  430. /* Get the path, handle virtual directories */
  431. if(strpos(php_self(), '?')) {
  432. $path = substr(php_self(), 0, strpos(php_self(), '?'));
  433. } else {
  434. $path = php_self();
  435. }
  436. $path = substr($path, 0, strrpos($path, '/'));
  437. // proto+host+port are already set in config:
  438. if ( !empty($config_location_base) ) {
  439. return $config_location_base . $path ;
  440. }
  441. // we computed it before, get it from the session:
  442. if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
  443. return $full_url . $path;
  444. }
  445. // else: autodetect
  446. /* Check if this is a HTTPS or regular HTTP request. */
  447. $proto = 'http://';
  448. /*
  449. * If you have 'SSLOptions +StdEnvVars' in your apache config
  450. * OR if you have HTTPS=on in your HTTP_SERVER_VARS
  451. * OR if you are on port 443
  452. */
  453. $getEnvVar = getenv('HTTPS');
  454. if ((isset($getEnvVar) && strcasecmp($getEnvVar, 'on') === 0) ||
  455. (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && strcasecmp($https_on, 'on') === 0) ||
  456. (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
  457. $proto = 'https://';
  458. }
  459. /* Get the hostname from the Host header or server config. */
  460. if ( !sqgetGlobalVar('HTTP_X_FORWARDED_HOST', $host, SQ_SERVER) || empty($host) ) {
  461. if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
  462. if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
  463. $host = '';
  464. }
  465. }
  466. }
  467. $port = '';
  468. if (! strstr($host, ':')) {
  469. if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
  470. if (($server_port != 80 && $proto == 'http://') ||
  471. ($server_port != 443 && $proto == 'https://')) {
  472. $port = sprintf(':%d', $server_port);
  473. }
  474. }
  475. }
  476. /* this is a workaround for the weird macosx caching that
  477. * causes Apache to return 16080 as the port number, which causes
  478. * SM to bail */
  479. if ($imap_server_type == 'macosx' && $port == ':16080') {
  480. $port = '';
  481. }
  482. /* Fallback is to omit the server name and use a relative */
  483. /* URI, although this is not RFC 2616 compliant. */
  484. $full_url = ($host ? $proto . $host . $port : '');
  485. sqsession_register($full_url, 'sq_base_url');
  486. return $full_url . $path;
  487. }
  488. /**
  489. * Encrypts password
  490. *
  491. * These functions are used to encrypt the password before it is
  492. * stored in a cookie. The encryption key is generated by
  493. * OneTimePadCreate();
  494. *
  495. * @param string $string the (password)string to encrypt
  496. * @param string $epad the encryption key
  497. * @return string the base64-encoded encrypted password
  498. * @since 1.0
  499. */
  500. function OneTimePadEncrypt ($string, $epad) {
  501. $pad = base64_decode($epad);
  502. if (strlen($pad)>0) {
  503. // make sure that pad is longer than string
  504. while (strlen($string)>strlen($pad)) {
  505. $pad.=$pad;
  506. }
  507. } else {
  508. // FIXME: what should we do when $epad is not base64 encoded or empty.
  509. }
  510. $encrypted = '';
  511. for ($i = 0; $i < strlen ($string); $i++) {
  512. $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
  513. }
  514. return base64_encode($encrypted);
  515. }
  516. /**
  517. * Decrypts a password from the cookie
  518. *
  519. * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
  520. * This uses the encryption key that is stored in the session.
  521. *
  522. * @param string $string the string to decrypt
  523. * @param string $epad the encryption key from the session
  524. * @return string the decrypted password
  525. * @since 1.0
  526. */
  527. function OneTimePadDecrypt ($string, $epad) {
  528. $pad = base64_decode($epad);
  529. if (strlen($pad)>0) {
  530. // make sure that pad is longer than string
  531. while (strlen($string)>strlen($pad)) {
  532. $pad.=$pad;
  533. }
  534. } else {
  535. // FIXME: what should we do when $epad is not base64 encoded or empty.
  536. }
  537. $encrypted = base64_decode ($string);
  538. $decrypted = '';
  539. for ($i = 0; $i < strlen ($encrypted); $i++) {
  540. $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
  541. }
  542. return $decrypted;
  543. }
  544. /**
  545. * Randomizes the mt_rand() function.
  546. *
  547. * Toss this in strings or integers and it will seed the generator
  548. * appropriately. With strings, it is better to get them long.
  549. * Use md5() to lengthen smaller strings.
  550. *
  551. * @param mixed $val a value to seed the random number generator. mixed = integer or string.
  552. * @return void
  553. * @since 1.0
  554. */
  555. function sq_mt_seed($Val) {
  556. /* if mt_getrandmax() does not return a 2^n - 1 number,
  557. this might not work well. This uses $Max as a bitmask. */
  558. $Max = mt_getrandmax();
  559. if (! is_int($Val)) {
  560. $Val = crc32($Val);
  561. }
  562. if ($Val < 0) {
  563. $Val *= -1;
  564. }
  565. if ($Val == 0) {
  566. return;
  567. }
  568. mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
  569. }
  570. /**
  571. * Init random number generator
  572. *
  573. * This function initializes the random number generator fairly well.
  574. * It also only initializes it once, so you don't accidentally get
  575. * the same 'random' numbers twice in one session.
  576. *
  577. * @return void
  578. * @since 1.0
  579. */
  580. function sq_mt_randomize() {
  581. static $randomized;
  582. if ($randomized) {
  583. return;
  584. }
  585. /* Global. */
  586. sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
  587. sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
  588. sq_mt_seed((int)((double) microtime() * 1000000));
  589. sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
  590. /* getrusage */
  591. if (function_exists('getrusage')) {
  592. /* Avoid warnings with Win32 */
  593. $dat = @getrusage();
  594. if (isset($dat) && is_array($dat)) {
  595. $Str = '';
  596. foreach ($dat as $k => $v)
  597. {
  598. $Str .= $k . $v;
  599. }
  600. sq_mt_seed(md5($Str));
  601. }
  602. }
  603. if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
  604. sq_mt_seed(md5($unique_id));
  605. }
  606. $randomized = 1;
  607. }
  608. /**
  609. * Creates encryption key
  610. *
  611. * Creates an encryption key for encrypting the password stored in the cookie.
  612. * The encryption key itself is stored in the session.
  613. *
  614. * Pad must be longer or equal to encoded string length in 1.4.4/1.5.0 and older.
  615. * @param int $length optional, length of the string to generate
  616. * @return string the encryption key
  617. * @since 1.0
  618. */
  619. function OneTimePadCreate ($length=100) {
  620. sq_mt_randomize();
  621. $pad = '';
  622. for ($i = 0; $i < $length; $i++) {
  623. $pad .= chr(mt_rand(0,255));
  624. }
  625. return base64_encode($pad);
  626. }
  627. /**
  628. * Returns a string showing the size of the message/attachment.
  629. *
  630. * @param int $bytes the filesize in bytes
  631. * @return string the filesize in human readable format
  632. * @since 1.0
  633. */
  634. function show_readable_size($bytes) {
  635. $bytes /= 1024;
  636. $type = 'KiB';
  637. if ($bytes / 1024 > 1) {
  638. $bytes /= 1024;
  639. $type = 'MiB';
  640. }
  641. if ($bytes < 10) {
  642. $bytes *= 10;
  643. settype($bytes, 'integer');
  644. $bytes /= 10;
  645. } else {
  646. settype($bytes, 'integer');
  647. }
  648. return $bytes . '&nbsp;' . $type;
  649. }
  650. /**
  651. * Generates a random string from the character set you pass in
  652. *
  653. * @param int $size the length of the string to generate
  654. * @param string $chars a string containing the characters to use
  655. * @param int $flags a flag to add a specific set to the characters to use:
  656. * Flags:
  657. * 1 = add lowercase a-z to $chars
  658. * 2 = add uppercase A-Z to $chars
  659. * 4 = add numbers 0-9 to $chars
  660. * @return string the random string
  661. * @since 1.0
  662. */
  663. function GenerateRandomString($size, $chars, $flags = 0) {
  664. if ($flags & 0x1) {
  665. $chars .= 'abcdefghijklmnopqrstuvwxyz';
  666. }
  667. if ($flags & 0x2) {
  668. $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  669. }
  670. if ($flags & 0x4) {
  671. $chars .= '0123456789';
  672. }
  673. if (($size < 1) || (strlen($chars) < 1)) {
  674. return '';
  675. }
  676. sq_mt_randomize(); /* Initialize the random number generator */
  677. $String = '';
  678. $j = strlen( $chars ) - 1;
  679. while (strlen($String) < $size) {
  680. $String .= $chars{mt_rand(0, $j)};
  681. }
  682. return $String;
  683. }
  684. /**
  685. * Escapes special characters for use in IMAP commands.
  686. *
  687. * @param string $str the string to escape
  688. * @return string the escaped string
  689. * @since 1.0.3
  690. */
  691. function quoteimap($str) {
  692. return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
  693. }
  694. /**
  695. * Create compose link
  696. *
  697. * Returns a link to the compose-page, taking in consideration
  698. * the compose_in_new and javascript settings.
  699. * @param string $url the URL to the compose page
  700. * @param string $text the link text, default "Compose"
  701. * @param string $target (since 1.4.3) url target
  702. * @return string a link to the compose page
  703. * @since 1.4.2
  704. */
  705. function makeComposeLink($url, $text = null, $target='') {
  706. global $compose_new_win, $compose_width,
  707. $compose_height, $oTemplate;
  708. if(!$text) {
  709. $text = _("Compose");
  710. }
  711. // if not using "compose in new window", make
  712. // regular link and be done with it
  713. if($compose_new_win != '1') {
  714. return makeInternalLink($url, $text, $target);
  715. }
  716. // build the compose in new window link...
  717. // if javascript is on, use onclick event to handle it
  718. if(checkForJavascript()) {
  719. sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
  720. $compuri = SM_BASE_URI.$url;
  721. return create_hyperlink('javascript:void(0)', $text, '', "comp_in_new('$compuri','$compose_width','$compose_height')");
  722. }
  723. // otherwise, just open new window using regular HTML
  724. return makeInternalLink($url, $text, '_blank');
  725. }
  726. /**
  727. * version of fwrite which checks for failure
  728. * @param resource $fp
  729. * @param string $string
  730. * @return number of written bytes. false on failure
  731. * @since 1.4.3
  732. */
  733. function sq_fwrite($fp, $string) {
  734. // write to file
  735. $count = @fwrite($fp,$string);
  736. // the number of bytes written should be the length of the string
  737. if($count != strlen($string)) {
  738. return FALSE;
  739. }
  740. return $count;
  741. }
  742. /**
  743. * sq_get_html_translation_table
  744. *
  745. * Returns the translation table used by sq_htmlentities()
  746. *
  747. * @param integer $table html translation table. Possible values (without quotes):
  748. * <ul>
  749. * <li>HTML_ENTITIES - full html entities table defined by charset</li>
  750. * <li>HTML_SPECIALCHARS - html special characters table</li>
  751. * </ul>
  752. * @param integer $quote_style quote encoding style. Possible values (without quotes):
  753. * <ul>
  754. * <li>ENT_COMPAT - (default) encode double quotes</li>
  755. * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
  756. * <li>ENT_QUOTES - encode double and single quotes</li>
  757. * </ul>
  758. * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
  759. * @return array html translation array
  760. * @since 1.5.1
  761. */
  762. function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT,$charset='us-ascii') {
  763. global $default_charset;
  764. if ($table == HTML_SPECIALCHARS) $charset='us-ascii';
  765. // Start array with ampersand
  766. $sq_html_ent_table = array( "&" => '&amp;' );
  767. // < and >
  768. $sq_html_ent_table = array_merge($sq_html_ent_table,
  769. array("<" => '&lt;',
  770. ">" => '&gt;')
  771. );
  772. // double quotes
  773. if ($quote_style == ENT_COMPAT)
  774. $sq_html_ent_table = array_merge($sq_html_ent_table,
  775. array("\"" => '&quot;')
  776. );
  777. // double and single quotes
  778. if ($quote_style == ENT_QUOTES)
  779. $sq_html_ent_table = array_merge($sq_html_ent_table,
  780. array("\"" => '&quot;',
  781. "'" => '&#39;')
  782. );
  783. if ($charset=='auto') $charset=$default_charset;
  784. // add entities that depend on charset
  785. switch($charset){
  786. case 'iso-8859-1':
  787. include_once(SM_PATH . 'functions/htmlentities/iso-8859-1.php');
  788. break;
  789. case 'utf-8':
  790. include_once(SM_PATH . 'functions/htmlentities/utf-8.php');
  791. break;
  792. case 'us-ascii':
  793. default:
  794. break;
  795. }
  796. // return table
  797. return $sq_html_ent_table;
  798. }
  799. /**
  800. * sq_htmlentities
  801. *
  802. * Convert all applicable characters to HTML entities.
  803. * Minimal php requirement - v.4.0.5.
  804. *
  805. * Function is designed for people that want to use full power of htmlentities() in
  806. * i18n environment.
  807. *
  808. * @param string $string string that has to be sanitized
  809. * @param integer $quote_style quote encoding style. Possible values (without quotes):
  810. * <ul>
  811. * <li>ENT_COMPAT - (default) encode double quotes</li>
  812. * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
  813. * <li>ENT_QUOTES - encode double and single quotes</li>
  814. * </ul>
  815. * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
  816. * @return string sanitized string
  817. * @since 1.5.1
  818. */
  819. function sq_htmlentities($string,$quote_style=ENT_COMPAT,$charset='us-ascii') {
  820. // get translation table
  821. $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES,$quote_style,$charset);
  822. // convert characters
  823. return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
  824. }
  825. /**
  826. * Tests if string contains 8bit symbols.
  827. *
  828. * If charset is not set, function defaults to default_charset.
  829. * $default_charset global must be set correctly if $charset is
  830. * not used.
  831. * @param string $string tested string
  832. * @param string $charset charset used in a string
  833. * @return bool true if 8bit symbols are detected
  834. * @since 1.5.1 and 1.4.4
  835. */
  836. function sq_is8bit($string,$charset='') {
  837. global $default_charset;
  838. if ($charset=='') $charset=$default_charset;
  839. /**
  840. * Don't use \240 in ranges. Sometimes RH 7.2 doesn't like it.
  841. * Don't use \200-\237 for iso-8859-x charsets. This range
  842. * stores control symbols in those charsets.
  843. * Use preg_match instead of ereg in order to avoid problems
  844. * with mbstring overloading
  845. */
  846. if (preg_match("/^iso-8859/i",$charset)) {
  847. $needle='/\240|[\241-\377]/';
  848. } else {
  849. $needle='/[\200-\237]|\240|[\241-\377]/';
  850. }
  851. return preg_match("$needle",$string);
  852. }
  853. /**
  854. * Replacement of mb_list_encodings function
  855. *
  856. * This function provides replacement for function that is available only
  857. * in php 5.x. Function does not test all mbstring encodings. Only the ones
  858. * that might be used in SM translations.
  859. *
  860. * Supported strings are stored in session in order to reduce number of
  861. * mb_internal_encoding function calls.
  862. *
  863. * If you want to test all mbstring encodings - fill $list_of_encodings
  864. * array.
  865. * @return array list of encodings supported by php mbstring extension
  866. * @since 1.5.1 and 1.4.6
  867. */
  868. function sq_mb_list_encodings() {
  869. if (! function_exists('mb_internal_encoding'))
  870. return array();
  871. // php 5+ function
  872. if (function_exists('mb_list_encodings')) {
  873. $ret = mb_list_encodings();
  874. array_walk($ret,'sq_lowercase_array_vals');
  875. return $ret;
  876. }
  877. // don't try to test encodings, if they are already stored in session
  878. if (sqgetGlobalVar('mb_supported_encodings',$mb_supported_encodings,SQ_SESSION))
  879. return $mb_supported_encodings;
  880. // save original encoding
  881. $orig_encoding=mb_internal_encoding();
  882. $list_of_encoding=array(
  883. 'pass',
  884. 'auto',
  885. 'ascii',
  886. 'jis',
  887. 'utf-8',
  888. 'sjis',
  889. 'euc-jp',
  890. 'iso-8859-1',
  891. 'iso-8859-2',
  892. 'iso-8859-7',
  893. 'iso-8859-9',
  894. 'iso-8859-15',
  895. 'koi8-r',
  896. 'koi8-u',
  897. 'big5',
  898. 'gb2312',
  899. 'gb18030',
  900. 'windows-1251',
  901. 'windows-1255',
  902. 'windows-1256',
  903. 'tis-620',
  904. 'iso-2022-jp',
  905. 'euc-cn',
  906. 'euc-kr',
  907. 'euc-tw',
  908. 'uhc',
  909. 'utf7-imap');
  910. $supported_encodings=array();
  911. foreach ($list_of_encoding as $encoding) {
  912. // try setting encodings. suppress warning messages
  913. if (@mb_internal_encoding($encoding))
  914. $supported_encodings[]=$encoding;
  915. }
  916. // restore original encoding
  917. mb_internal_encoding($orig_encoding);
  918. // register list in session
  919. sqsession_register($supported_encodings,'mb_supported_encodings');
  920. return $supported_encodings;
  921. }
  922. /**
  923. * Callback function used to lowercase array values.
  924. * @param string $val array value
  925. * @param mixed $key array key
  926. * @since 1.5.1 and 1.4.6
  927. */
  928. function sq_lowercase_array_vals(&$val,$key) {
  929. $val = strtolower($val);
  930. }
  931. /**
  932. * Function returns number of characters in string.
  933. *
  934. * Returned number might be different from number of bytes in string,
  935. * if $charset is multibyte charset. Detection depends on mbstring
  936. * functions. If mbstring does not support tested multibyte charset,
  937. * vanilla string length function is used.
  938. * @param string $str string
  939. * @param string $charset charset
  940. * @since 1.5.1 and 1.4.6
  941. * @return integer number of characters in string
  942. */
  943. function sq_strlen($str, $charset=null){
  944. // default option
  945. if (is_null($charset)) return strlen($str);
  946. // lowercase charset name
  947. $charset=strtolower($charset);
  948. // use automatic charset detection, if function call asks for it
  949. if ($charset=='auto') {
  950. global $default_charset, $squirrelmail_language;
  951. set_my_charset();
  952. $charset=$default_charset;
  953. if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
  954. }
  955. // Use mbstring only with listed charsets
  956. $aList_of_mb_charsets=array('utf-8','big5','gb2312','gb18030','euc-jp','euc-cn','euc-tw','euc-kr');
  957. // calculate string length according to charset
  958. if (in_array($charset,$aList_of_mb_charsets) && in_array($charset,sq_mb_list_encodings())) {
  959. $real_length = mb_strlen($str,$charset);
  960. } else {
  961. // own strlen detection code is removed because missing strpos,
  962. // strtoupper and substr implementations break string wrapping.
  963. $real_length=strlen($str);
  964. }
  965. return $real_length;
  966. }
  967. /**
  968. * string padding with multibyte support
  969. *
  970. * @link http://www.php.net/str_pad
  971. * @param string $string original string
  972. * @param integer $width padded string width
  973. * @param string $pad padding symbols
  974. * @param integer $padtype padding type
  975. * (internal php defines, see str_pad() description)
  976. * @param string $charset charset used in original string
  977. * @return string padded string
  978. */
  979. function sq_str_pad($string, $width, $pad, $padtype, $charset='') {
  980. $charset = strtolower($charset);
  981. $padded_string = '';
  982. switch ($charset) {
  983. case 'utf-8':
  984. case 'big5':
  985. case 'gb2312':
  986. case 'euc-kr':
  987. /*
  988. * all multibyte charsets try to increase width value by
  989. * adding difference between number of bytes and real length
  990. */
  991. $width = $width - sq_strlen($string,$charset) + strlen($string);
  992. default:
  993. $padded_string=str_pad($string,$width,$pad,$padtype);
  994. }
  995. return $padded_string;
  996. }
  997. /**
  998. * Wrapper that is used to switch between vanilla and multibyte substr
  999. * functions.
  1000. * @param string $string
  1001. * @param integer $start
  1002. * @param integer $length
  1003. * @param string $charset
  1004. * @return string
  1005. * @since 1.5.1
  1006. * @link http://www.php.net/substr
  1007. * @link http://www.php.net/mb_substr
  1008. */
  1009. function sq_substr($string,$start,$length,$charset='auto') {
  1010. // use automatic charset detection, if function call asks for it
  1011. static $charset_auto, $bUse_mb;
  1012. if ($charset=='auto') {
  1013. if (!isset($charset_auto)) {
  1014. global $default_charset, $squirrelmail_language;
  1015. set_my_charset();
  1016. $charset=$default_charset;
  1017. if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
  1018. $charset_auto = $charset;
  1019. } else {
  1020. $charset = $charset_auto;
  1021. }
  1022. }
  1023. $charset = strtolower($charset);
  1024. // in_array call is expensive => do it once and use a static var for
  1025. // storing the results
  1026. if (!isset($bUse_mb)) {
  1027. if (in_array($charset,sq_mb_list_encodings())) {
  1028. $bUse_mb = true;
  1029. } else {
  1030. $bUse_mb = false;
  1031. }
  1032. }
  1033. if ($bUse_mb) {
  1034. return mb_substr($string,$start,$length,$charset);
  1035. }
  1036. // TODO: add mbstring independent code
  1037. // use vanilla string functions as last option
  1038. return substr($string,$start,$length);
  1039. }
  1040. /**
  1041. * Wrapper that is used to switch between vanilla and multibyte strpos
  1042. * functions.
  1043. * @param string $haystack
  1044. * @param mixed $needle
  1045. * @param integer $offset
  1046. * @param string $charset
  1047. * @return string
  1048. * @since 1.5.1
  1049. * @link http://www.php.net/strpos
  1050. * @link http://www.php.net/mb_strpos
  1051. */
  1052. function sq_strpos($haystack,$needle,$offset,$charset='auto') {
  1053. // use automatic charset detection, if function call asks for it
  1054. static $charset_auto, $bUse_mb;
  1055. if ($charset=='auto') {
  1056. if (!isset($charset_auto)) {
  1057. global $default_charset, $squirrelmail_language;
  1058. set_my_charset();
  1059. $charset=$default_charset;
  1060. if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
  1061. $charset_auto = $charset;
  1062. } else {
  1063. $charset = $charset_auto;
  1064. }
  1065. }
  1066. $charset = strtolower($charset);
  1067. // in_array call is expensive => do it once and use a static var for
  1068. // storing the results
  1069. if (!isset($bUse_mb)) {
  1070. if (in_array($charset,sq_mb_list_encodings())) {
  1071. $bUse_mb = true;
  1072. } else {
  1073. $bUse_mb = false;
  1074. }
  1075. }
  1076. if ($bUse_mb) {
  1077. return mb_strpos($haystack,$needle,$offset,$charset);
  1078. }
  1079. // TODO: add mbstring independent code
  1080. // use vanilla string functions as last option
  1081. return strpos($haystack,$needle,$offset);
  1082. }
  1083. /**
  1084. * Wrapper that is used to switch between vanilla and multibyte strtoupper
  1085. * functions.
  1086. * @param string $string
  1087. * @param string $charset
  1088. * @return string
  1089. * @since 1.5.1
  1090. * @link http://www.php.net/strtoupper
  1091. * @link http://www.php.net/mb_strtoupper
  1092. */
  1093. function sq_strtoupper($string,$charset='auto') {
  1094. // use automatic charset detection, if function call asks for it
  1095. static $charset_auto, $bUse_mb;
  1096. if ($charset=='auto') {
  1097. if (!isset($charset_auto)) {
  1098. global $default_charset, $squirrelmail_language;
  1099. set_my_charset();
  1100. $charset=$default_charset;
  1101. if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
  1102. $charset_auto = $charset;
  1103. } else {
  1104. $charset = $charset_auto;
  1105. }
  1106. }
  1107. $charset = strtolower($charset);
  1108. // in_array call is expensive => do it once and use a static var for
  1109. // storing the results
  1110. if (!isset($bUse_mb)) {
  1111. if (function_exists('mb_strtoupper') &&
  1112. in_array($charset,sq_mb_list_encodings())) {
  1113. $bUse_mb = true;
  1114. } else {
  1115. $bUse_mb = false;
  1116. }
  1117. }
  1118. if ($bUse_mb) {
  1119. return mb_strtoupper($string,$charset);
  1120. }
  1121. // TODO: add mbstring independent code
  1122. // use vanilla string functions as last option
  1123. return strtoupper($string);
  1124. }
  1125. /**
  1126. * Counts 8bit bytes in string
  1127. * @param string $string tested string
  1128. * @return integer number of 8bit bytes
  1129. */
  1130. function sq_count8bit($string) {
  1131. $count=0;
  1132. for ($i=0; $i<strlen($string); $i++) {
  1133. if (ord($string[$i]) > 127) $count++;
  1134. }
  1135. return $count;
  1136. }
  1137. /**
  1138. * Callback function to trim whitespace from a value, to be used in array_walk
  1139. * @param string $value value to trim
  1140. * @since 1.5.2 and 1.4.7
  1141. */
  1142. function sq_trim_value ( &$value ) {
  1143. $value = trim($value);
  1144. }