strings.php 30 KB

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