strings.php 39 KB

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