strings.php 40 KB

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