strings.php 39 KB

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