strings.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  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$
  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. // inner loop, (obviously) handles wrapping up to
  193. // the next newline
  194. while ($pos < $nextNewline) {
  195. // skip over initial spaces
  196. while (($pos < $nextNewline) && (ctype_space ($body{$pos}))) {
  197. $pos++;
  198. }
  199. // if this is a short line then just append it and continue outer loop
  200. if (($outStringCol + $nextNewline - $pos) <= ($wrap - $citeLevel - 1)) {
  201. // if this is the final line in the input string then include
  202. // any trailing newlines
  203. if (($nextNewline + 1 == $length) && ($body{$nextNewline} == "\n")) {
  204. $nextNewline++;
  205. }
  206. // trim trailing spaces
  207. $lastRealChar = $nextNewline;
  208. while (($lastRealChar > $pos) && (ctype_space ($body{$lastRealChar}))) {
  209. $lastRealChar--;
  210. }
  211. $outString .= substr ($body, $pos, ($lastRealChar - $pos + 1));
  212. $outStringCol += ($lastRealChar - $pos);
  213. $pos = $nextNewline + 1;
  214. continue;
  215. }
  216. $eol = $pos + $wrap - $citeLevel - $outStringCol;
  217. // eol is the tentative end of line.
  218. // look backwards for there for a whitespace to break at.
  219. // if it's already less than our current position then
  220. // our current line is already too long, break immediately
  221. // and restart outer loop
  222. if ($eol <= $pos) {
  223. sqMakeNewLine ($outString, $citeLeve, $outStringCol);
  224. continue;
  225. }
  226. // start looking backwards for whitespace to break at.
  227. $breakPoint = $eol;
  228. while (($breakPoint > $pos) && (! ctype_space ($body{$breakPoint}))) {
  229. $breakPoint--;
  230. }
  231. // if we didn't find a breakpoint by looking backward then we
  232. // need to figure out what to do about that
  233. if ($breakPoint == $pos) {
  234. // if we are not at the beginning then end this line
  235. // and start a new loop
  236. if ($outStringCol > ($citeLevel + 1)) {
  237. sqMakeNewLine ($outString, $citeLevel, $outStringCol);
  238. continue;
  239. } else {
  240. // just hard break here. most likely we are breaking
  241. // a really long URL. could also try searching
  242. // forward for a break point, which is what Mozilla
  243. // does. don't bother for now.
  244. $breakPoint = $eol;
  245. }
  246. }
  247. // special case: maybe we should have wrapped last
  248. // time. if the first breakpoint here makes the
  249. // current line too long and there is already text on
  250. // the current line, break and loop again if at
  251. // beginning of current line, don't force break
  252. $SLOP = 6;
  253. if ((($outStringCol + ($breakPoint - $pos)) > ($wrap + $SLOP)) && ($outStringCol > ($citeLevel + 1))) {
  254. sqMakeNewLine ($outString, $citeLevel, $outStringCol);
  255. continue;
  256. }
  257. // skip newlines or whitespace at the beginning of the string
  258. $substring = substr ($body, $pos, ($breakPoint - $pos));
  259. $substring = rtrim ($substring); // do rtrim and ctype_space have the same ideas about whitespace?
  260. $outString .= $substring;
  261. $outStringCol += strlen ($substring);
  262. // advance past the whitespace which caused the wrap
  263. $pos = $breakPoint;
  264. while (($pos < $length) && (ctype_space ($body{$pos}))) {
  265. $pos++;
  266. }
  267. if ($pos < $length) {
  268. sqMakeNewLine ($outString, $citeLevel, $outStringCol);
  269. }
  270. }
  271. }
  272. return $outString;
  273. }
  274. /**
  275. * Wraps text at $wrap characters
  276. *
  277. * Has a problem with special HTML characters, so call this before
  278. * you do character translation.
  279. *
  280. * Specifically, &#039 comes up as 5 characters instead of 1.
  281. * This should not add newlines to the end of lines.
  282. *
  283. * @param string line the line of text to wrap, by ref
  284. * @param int wrap the maximum line lenth
  285. * @return void
  286. */
  287. function sqWordWrap(&$line, $wrap) {
  288. global $languages, $squirrelmail_language;
  289. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  290. function_exists($languages[$squirrelmail_language]['XTRA_CODE'])) {
  291. if (mb_detect_encoding($line) != 'ASCII') {
  292. $line = $languages[$squirrelmail_language]['XTRA_CODE']('wordwrap', $line, $wrap);
  293. return;
  294. }
  295. }
  296. ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
  297. $beginning_spaces = $regs[1];
  298. if (isset($regs[2])) {
  299. $words = explode(' ', $regs[2]);
  300. } else {
  301. $words = '';
  302. }
  303. $i = 0;
  304. $line = $beginning_spaces;
  305. while ($i < count($words)) {
  306. /* Force one word to be on a line (minimum) */
  307. $line .= $words[$i];
  308. $line_len = strlen($beginning_spaces) + strlen($words[$i]) + 2;
  309. if (isset($words[$i + 1]))
  310. $line_len += strlen($words[$i + 1]);
  311. $i ++;
  312. /* Add more words (as long as they fit) */
  313. while ($line_len < $wrap && $i < count($words)) {
  314. $line .= ' ' . $words[$i];
  315. $i++;
  316. if (isset($words[$i]))
  317. $line_len += strlen($words[$i]) + 1;
  318. else
  319. $line_len += 1;
  320. }
  321. /* Skip spaces if they are the first thing on a continued line */
  322. while (!isset($words[$i]) && $i < count($words)) {
  323. $i ++;
  324. }
  325. /* Go to the next line if we have more to process */
  326. if ($i < count($words)) {
  327. $line .= "\n";
  328. }
  329. }
  330. }
  331. /**
  332. * Does the opposite of sqWordWrap()
  333. * @param string body the text to un-wordwrap
  334. * @return void
  335. */
  336. function sqUnWordWrap(&$body) {
  337. global $squirrelmail_language;
  338. if ($squirrelmail_language == 'ja_JP') {
  339. return;
  340. }
  341. $lines = explode("\n", $body);
  342. $body = '';
  343. $PreviousSpaces = '';
  344. $cnt = count($lines);
  345. for ($i = 0; $i < $cnt; $i ++) {
  346. preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
  347. $CurrentSpaces = $regs[1];
  348. if (isset($regs[2])) {
  349. $CurrentRest = $regs[2];
  350. } else {
  351. $CurrentRest = '';
  352. }
  353. if ($i == 0) {
  354. $PreviousSpaces = $CurrentSpaces;
  355. $body = $lines[$i];
  356. } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
  357. && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
  358. && strlen($CurrentRest)) { /* and there's a line to continue with */
  359. $body .= ' ' . $CurrentRest;
  360. } else {
  361. $body .= "\n" . $lines[$i];
  362. $PreviousSpaces = $CurrentSpaces;
  363. }
  364. }
  365. $body .= "\n";
  366. }
  367. /**
  368. * If $haystack is a full mailbox name and $needle is the mailbox
  369. * separator character, returns the last part of the mailbox name.
  370. *
  371. * @param string haystack full mailbox name to search
  372. * @param string needle the mailbox separator character
  373. * @return string the last part of the mailbox name
  374. */
  375. function readShortMailboxName($haystack, $needle) {
  376. if ($needle == '') {
  377. $elem = $haystack;
  378. } else {
  379. $parts = explode($needle, $haystack);
  380. $elem = array_pop($parts);
  381. while ($elem == '' && count($parts)) {
  382. $elem = array_pop($parts);
  383. }
  384. }
  385. return( $elem );
  386. }
  387. /**
  388. * php_self
  389. *
  390. * Creates an URL for the page calling this function, using either the PHP global
  391. * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added.
  392. *
  393. * @return string the complete url for this page
  394. */
  395. function php_self () {
  396. if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
  397. return $req_uri;
  398. }
  399. if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
  400. // need to add query string to end of PHP_SELF to match REQUEST_URI
  401. //
  402. if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER) && !empty($query_string) ) {
  403. $php_self .= '?' . $query_string;
  404. }
  405. return $php_self;
  406. }
  407. return '';
  408. }
  409. /**
  410. * get_location
  411. *
  412. * Determines the location to forward to, relative to your server.
  413. * This is used in HTTP Location: redirects.
  414. * If this doesnt work correctly for you (although it should), you can
  415. * remove all this code except the last two lines, and have it return
  416. * the right URL for your site, something like:
  417. *
  418. * http://www.example.com/squirrelmail/
  419. *
  420. * @return string the base url for this SquirrelMail installation
  421. */
  422. function get_location () {
  423. global $imap_server_type;
  424. /* Get the path, handle virtual directories */
  425. if(strpos(php_self(), '?')) {
  426. $path = substr(php_self(), 0, strpos(php_self(), '?'));
  427. } else {
  428. $path = php_self();
  429. }
  430. $path = substr($path, 0, strrpos($path, '/'));
  431. if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
  432. return $full_url . $path;
  433. }
  434. /* Check if this is a HTTPS or regular HTTP request. */
  435. $proto = 'http://';
  436. /*
  437. * If you have 'SSLOptions +StdEnvVars' in your apache config
  438. * OR if you have HTTPS=on in your HTTP_SERVER_VARS
  439. * OR if you are on port 443
  440. */
  441. $getEnvVar = getenv('HTTPS');
  442. if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
  443. (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && !strcasecmp($https_on, 'on')) ||
  444. (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
  445. $proto = 'https://';
  446. }
  447. /* Get the hostname from the Host header or server config. */
  448. if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
  449. if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
  450. $host = '';
  451. }
  452. }
  453. $port = '';
  454. if (! strstr($host, ':')) {
  455. if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
  456. if (($server_port != 80 && $proto == 'http://') ||
  457. ($server_port != 443 && $proto == 'https://')) {
  458. $port = sprintf(':%d', $server_port);
  459. }
  460. }
  461. }
  462. /* this is a workaround for the weird macosx caching that
  463. causes Apache to return 16080 as the port number, which causes
  464. SM to bail */
  465. if ($imap_server_type == 'macosx' && $port == ':16080') {
  466. $port = '';
  467. }
  468. /* Fallback is to omit the server name and use a relative */
  469. /* URI, although this is not RFC 2616 compliant. */
  470. $full_url = ($host ? $proto . $host . $port : '');
  471. sqsession_register($full_url, 'sq_base_url');
  472. return $full_url . $path;
  473. }
  474. /**
  475. * Encrypts password
  476. *
  477. * These functions are used to encrypt the password before it is
  478. * stored in a cookie. The encryption key is generated by
  479. * OneTimePadCreate();
  480. *
  481. * @param string string the (password)string to encrypt
  482. * @param string epad the encryption key
  483. * @return string the base64-encoded encrypted password
  484. */
  485. function OneTimePadEncrypt ($string, $epad) {
  486. $pad = base64_decode($epad);
  487. $encrypted = '';
  488. for ($i = 0; $i < strlen ($string); $i++) {
  489. $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
  490. }
  491. return base64_encode($encrypted);
  492. }
  493. /**
  494. * Decrypts a password from the cookie
  495. *
  496. * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
  497. * This uses the encryption key that is stored in the session.
  498. *
  499. * @param string string the string to decrypt
  500. * @param string epad the encryption key from the session
  501. * @return string the decrypted password
  502. */
  503. function OneTimePadDecrypt ($string, $epad) {
  504. $pad = base64_decode($epad);
  505. $encrypted = base64_decode ($string);
  506. $decrypted = '';
  507. for ($i = 0; $i < strlen ($encrypted); $i++) {
  508. $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
  509. }
  510. return $decrypted;
  511. }
  512. /**
  513. * Randomizes the mt_rand() function.
  514. *
  515. * Toss this in strings or integers and it will seed the generator
  516. * appropriately. With strings, it is better to get them long.
  517. * Use md5() to lengthen smaller strings.
  518. *
  519. * @param mixed val a value to seed the random number generator
  520. * @return void
  521. */
  522. function sq_mt_seed($Val) {
  523. /* if mt_getrandmax() does not return a 2^n - 1 number,
  524. this might not work well. This uses $Max as a bitmask. */
  525. $Max = mt_getrandmax();
  526. if (! is_int($Val)) {
  527. $Val = crc32($Val);
  528. }
  529. if ($Val < 0) {
  530. $Val *= -1;
  531. }
  532. if ($Val = 0) {
  533. return;
  534. }
  535. mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
  536. }
  537. /**
  538. * Init random number generator
  539. *
  540. * This function initializes the random number generator fairly well.
  541. * It also only initializes it once, so you don't accidentally get
  542. * the same 'random' numbers twice in one session.
  543. *
  544. * @return void
  545. */
  546. function sq_mt_randomize() {
  547. static $randomized;
  548. if ($randomized) {
  549. return;
  550. }
  551. /* Global. */
  552. sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
  553. sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
  554. sq_mt_seed((int)((double) microtime() * 1000000));
  555. sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
  556. /* getrusage */
  557. if (function_exists('getrusage')) {
  558. /* Avoid warnings with Win32 */
  559. $dat = @getrusage();
  560. if (isset($dat) && is_array($dat)) {
  561. $Str = '';
  562. foreach ($dat as $k => $v)
  563. {
  564. $Str .= $k . $v;
  565. }
  566. sq_mt_seed(md5($Str));
  567. }
  568. }
  569. if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
  570. sq_mt_seed(md5($unique_id));
  571. }
  572. $randomized = 1;
  573. }
  574. /**
  575. * Creates encryption key
  576. *
  577. * Creates an encryption key for encrypting the password stored in the cookie.
  578. * The encryption key itself is stored in the session.
  579. *
  580. * @param int length optional, length of the string to generate
  581. * @return string the encryption key
  582. */
  583. function OneTimePadCreate ($length=100) {
  584. sq_mt_randomize();
  585. $pad = '';
  586. for ($i = 0; $i < $length; $i++) {
  587. $pad .= chr(mt_rand(0,255));
  588. }
  589. return base64_encode($pad);
  590. }
  591. /**
  592. * Returns a string showing the size of the message/attachment.
  593. *
  594. * @param int bytes the filesize in bytes
  595. * @return string the filesize in human readable format
  596. */
  597. function show_readable_size($bytes) {
  598. $bytes /= 1024;
  599. $type = 'k';
  600. if ($bytes / 1024 > 1) {
  601. $bytes /= 1024;
  602. $type = 'M';
  603. }
  604. if ($bytes < 10) {
  605. $bytes *= 10;
  606. settype($bytes, 'integer');
  607. $bytes /= 10;
  608. } else {
  609. settype($bytes, 'integer');
  610. }
  611. return $bytes . '<small>&nbsp;' . $type . '</small>';
  612. }
  613. /**
  614. * Generates a random string from the caracter set you pass in
  615. *
  616. * @param int size the size of the string to generate
  617. * @param string chars a string containing the characters to use
  618. * @param int flags a flag to add a specific set to the characters to use:
  619. * Flags:
  620. * 1 = add lowercase a-z to $chars
  621. * 2 = add uppercase A-Z to $chars
  622. * 4 = add numbers 0-9 to $chars
  623. * @return string the random string
  624. */
  625. function GenerateRandomString($size, $chars, $flags = 0) {
  626. if ($flags & 0x1) {
  627. $chars .= 'abcdefghijklmnopqrstuvwxyz';
  628. }
  629. if ($flags & 0x2) {
  630. $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  631. }
  632. if ($flags & 0x4) {
  633. $chars .= '0123456789';
  634. }
  635. if (($size < 1) || (strlen($chars) < 1)) {
  636. return '';
  637. }
  638. sq_mt_randomize(); /* Initialize the random number generator */
  639. $String = '';
  640. $j = strlen( $chars ) - 1;
  641. while (strlen($String) < $size) {
  642. $String .= $chars{mt_rand(0, $j)};
  643. }
  644. return $String;
  645. }
  646. /**
  647. * Escapes special characters for use in IMAP commands.
  648. *
  649. * @param string the string to escape
  650. * @return string the escaped string
  651. */
  652. function quoteimap($str) {
  653. return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
  654. }
  655. /**
  656. * Trims array
  657. *
  658. * Trims every element in the array, ie. remove the first char of each element
  659. * @param array array the array to trim
  660. */
  661. function TrimArray(&$array) {
  662. foreach ($array as $k => $v) {
  663. global $$k;
  664. if (is_array($$k)) {
  665. foreach ($$k as $k2 => $v2) {
  666. $$k[$k2] = substr($v2, 1);
  667. }
  668. } else {
  669. $$k = substr($v, 1);
  670. }
  671. /* Re-assign back to array. */
  672. $array[$k] = $$k;
  673. }
  674. }
  675. /**
  676. * Create compose link
  677. *
  678. * Returns a link to the compose-page, taking in consideration
  679. * the compose_in_new and javascript settings.
  680. * @param string url the URL to the compose page
  681. * @param string text the link text, default "Compose"
  682. * @return string a link to the compose page
  683. */
  684. function makeComposeLink($url, $text = null, $target='')
  685. {
  686. global $compose_new_win,$javascript_on;
  687. if(!$text) {
  688. $text = _("Compose");
  689. }
  690. // if not using "compose in new window", make
  691. // regular link and be done with it
  692. if($compose_new_win != '1') {
  693. return makeInternalLink($url, $text, $target);
  694. }
  695. // build the compose in new window link...
  696. // if javascript is on, use onClick event to handle it
  697. if($javascript_on) {
  698. sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
  699. return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
  700. }
  701. // otherwise, just open new window using regular HTML
  702. return makeInternalLink($url, $text, '_blank');
  703. }
  704. /**
  705. * Print variable
  706. *
  707. * sm_print_r($some_variable, [$some_other_variable [, ...]]);
  708. *
  709. * Debugging function - does the same as print_r, but makes sure special
  710. * characters are converted to htmlentities first. This will allow
  711. * values like <some@email.address> to be displayed.
  712. * The output is wrapped in <<pre>> and <</pre>> tags.
  713. *
  714. * @return void
  715. */
  716. function sm_print_r() {
  717. ob_start(); // Buffer output
  718. foreach(func_get_args() as $var) {
  719. print_r($var);
  720. echo "\n";
  721. }
  722. $buffer = ob_get_contents(); // Grab the print_r output
  723. ob_end_clean(); // Silently discard the output & stop buffering
  724. print '<pre>';
  725. print htmlentities($buffer);
  726. print '</pre>';
  727. }
  728. /**
  729. * version of fwrite which checks for failure
  730. */
  731. function sq_fwrite($fp, $string) {
  732. // write to file
  733. $count = @fwrite($fp,$string);
  734. // the number of bytes written should be the length of the string
  735. if($count != strlen($string)) {
  736. return FALSE;
  737. }
  738. return $count;
  739. }
  740. /**
  741. * sq_get_html_translation_table
  742. *
  743. * Returns the translation table used by sq_htmlentities()
  744. *
  745. * @param integer $table html translation table. Possible values (without quotes):
  746. * <ul>
  747. * <li>HTML_ENTITIES - full html entities table defined by charset</li>
  748. * <li>HTML_SPECIALCHARS - html special characters table</li>
  749. * </ul>
  750. * @param integer $quote_style quote encoding style. Possible values (without quotes):
  751. * <ul>
  752. * <li>ENT_COMPAT - (default) encode double quotes</li>
  753. * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
  754. * <li>ENT_QUOTES - encode double and single quotes</li>
  755. * </ul>
  756. * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
  757. * @return array html translation array
  758. */
  759. function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT,$charset='us-ascii') {
  760. global $default_charset;
  761. if ($table == HTML_SPECIALCHARS) $charset='us-ascii';
  762. // Start array with ampersand
  763. $sq_html_ent_table = array( "&" => '&amp;' );
  764. // < and >
  765. $sq_html_ent_table = array_merge($sq_html_ent_table,
  766. array("<" => '&lt;',
  767. ">" => '&gt;')
  768. );
  769. // double quotes
  770. if ($quote_style == ENT_COMPAT)
  771. $sq_html_ent_table = array_merge($sq_html_ent_table,
  772. array("\"" => '&quot;')
  773. );
  774. // double and single quotes
  775. if ($quote_style == ENT_QUOTES)
  776. $sq_html_ent_table = array_merge($sq_html_ent_table,
  777. array("\"" => '&quot;',
  778. "'" => '&#39;')
  779. );
  780. if ($charset=='auto') $charset=$default_charset;
  781. // add entities that depend on charset
  782. switch($charset){
  783. case 'iso-8859-1':
  784. include_once(SM_PATH . 'functions/htmlentities/iso-8859-1.php');
  785. break;
  786. case 'utf-8':
  787. include_once(SM_PATH . 'functions/htmlentities/utf-8.php');
  788. break;
  789. case 'us-ascii':
  790. default:
  791. break;
  792. }
  793. // return table
  794. return $sq_html_ent_table;
  795. }
  796. /**
  797. * sq_htmlentities
  798. *
  799. * Convert all applicable characters to HTML entities.
  800. * Minimal php requirement - v.4.0.5
  801. *
  802. * @param string $string string that has to be sanitized
  803. * @param integer $quote_style quote encoding style. Possible values (without quotes):
  804. * <ul>
  805. * <li>ENT_COMPAT - (default) encode double quotes</li>
  806. * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
  807. * <li>ENT_QUOTES - encode double and single quotes</li>
  808. * </ul>
  809. * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
  810. * @return string sanitized string
  811. */
  812. function sq_htmlentities($string,$quote_style=ENT_COMPAT,$charset='us-ascii') {
  813. // get translation table
  814. $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES,$quote_style,$charset);
  815. // convert characters
  816. return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
  817. }
  818. $PHP_SELF = php_self();
  819. ?>