PageRenderTime 36ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/branches/DEVEL_MARC/squirrelmail/functions/strings.php

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