strings.php 40 KB

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