strings.php 41 KB

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