strings.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301
  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. * get_location
  436. *
  437. * Determines the location to forward to, relative to your server.
  438. * This is used in HTTP Location: redirects.
  439. * If this doesnt work correctly for you (although it should), you can
  440. * remove all this code except the last two lines, and have it return
  441. * the right URL for your site, something like:
  442. *
  443. * http://www.example.com/squirrelmail/
  444. *
  445. * @return string the base url for this SquirrelMail installation
  446. * @since 1.0
  447. */
  448. function get_location () {
  449. global $imap_server_type;
  450. /* Get the path, handle virtual directories */
  451. if(strpos(php_self(), '?')) {
  452. $path = substr(php_self(), 0, strpos(php_self(), '?'));
  453. } else {
  454. $path = php_self();
  455. }
  456. $path = substr($path, 0, strrpos($path, '/'));
  457. if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
  458. return $full_url . $path;
  459. }
  460. /* Check if this is a HTTPS or regular HTTP request. */
  461. $proto = 'http://';
  462. /*
  463. * If you have 'SSLOptions +StdEnvVars' in your apache config
  464. * OR if you have HTTPS=on in your HTTP_SERVER_VARS
  465. * OR if you are on port 443
  466. */
  467. $getEnvVar = getenv('HTTPS');
  468. if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
  469. (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && !strcasecmp($https_on, 'on')) ||
  470. (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
  471. $proto = 'https://';
  472. }
  473. /* Get the hostname from the Host header or server config. */
  474. if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
  475. if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
  476. $host = '';
  477. }
  478. }
  479. $port = '';
  480. if (! strstr($host, ':')) {
  481. if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
  482. if (($server_port != 80 && $proto == 'http://') ||
  483. ($server_port != 443 && $proto == 'https://')) {
  484. $port = sprintf(':%d', $server_port);
  485. }
  486. }
  487. }
  488. /* this is a workaround for the weird macosx caching that
  489. causes Apache to return 16080 as the port number, which causes
  490. SM to bail */
  491. if ($imap_server_type == 'macosx' && $port == ':16080') {
  492. $port = '';
  493. }
  494. /* Fallback is to omit the server name and use a relative */
  495. /* URI, although this is not RFC 2616 compliant. */
  496. $full_url = ($host ? $proto . $host . $port : '');
  497. sqsession_register($full_url, 'sq_base_url');
  498. return $full_url . $path;
  499. }
  500. /**
  501. * Encrypts password
  502. *
  503. * These functions are used to encrypt the password before it is
  504. * stored in a cookie. The encryption key is generated by
  505. * OneTimePadCreate();
  506. *
  507. * @param string $string the (password)string to encrypt
  508. * @param string $epad the encryption key
  509. * @return string the base64-encoded encrypted password
  510. * @since 1.0
  511. */
  512. function OneTimePadEncrypt ($string, $epad) {
  513. $pad = base64_decode($epad);
  514. if (strlen($pad)>0) {
  515. // make sure that pad is longer than string
  516. while (strlen($string)>strlen($pad)) {
  517. $pad.=$pad;
  518. }
  519. } else {
  520. // FIXME: what should we do when $epad is not base64 encoded or empty.
  521. }
  522. $encrypted = '';
  523. for ($i = 0; $i < strlen ($string); $i++) {
  524. $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
  525. }
  526. return base64_encode($encrypted);
  527. }
  528. /**
  529. * Decrypts a password from the cookie
  530. *
  531. * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
  532. * This uses the encryption key that is stored in the session.
  533. *
  534. * @param string $string the string to decrypt
  535. * @param string $epad the encryption key from the session
  536. * @return string the decrypted password
  537. * @since 1.0
  538. */
  539. function OneTimePadDecrypt ($string, $epad) {
  540. $pad = base64_decode($epad);
  541. if (strlen($pad)>0) {
  542. // make sure that pad is longer than string
  543. while (strlen($string)>strlen($pad)) {
  544. $pad.=$pad;
  545. }
  546. } else {
  547. // FIXME: what should we do when $epad is not base64 encoded or empty.
  548. }
  549. $encrypted = base64_decode ($string);
  550. $decrypted = '';
  551. for ($i = 0; $i < strlen ($encrypted); $i++) {
  552. $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
  553. }
  554. return $decrypted;
  555. }
  556. /**
  557. * Randomizes the mt_rand() function.
  558. *
  559. * Toss this in strings or integers and it will seed the generator
  560. * appropriately. With strings, it is better to get them long.
  561. * Use md5() to lengthen smaller strings.
  562. *
  563. * @param mixed $val a value to seed the random number generator. mixed = integer or string.
  564. * @return void
  565. * @since 1.0
  566. */
  567. function sq_mt_seed($Val) {
  568. /* if mt_getrandmax() does not return a 2^n - 1 number,
  569. this might not work well. This uses $Max as a bitmask. */
  570. $Max = mt_getrandmax();
  571. if (! is_int($Val)) {
  572. $Val = crc32($Val);
  573. }
  574. if ($Val < 0) {
  575. $Val *= -1;
  576. }
  577. if ($Val == 0) {
  578. return;
  579. }
  580. mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
  581. }
  582. /**
  583. * Init random number generator
  584. *
  585. * This function initializes the random number generator fairly well.
  586. * It also only initializes it once, so you don't accidentally get
  587. * the same 'random' numbers twice in one session.
  588. *
  589. * @return void
  590. * @since 1.0
  591. */
  592. function sq_mt_randomize() {
  593. static $randomized;
  594. if ($randomized) {
  595. return;
  596. }
  597. /* Global. */
  598. sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
  599. sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
  600. sq_mt_seed((int)((double) microtime() * 1000000));
  601. sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
  602. /* getrusage */
  603. if (function_exists('getrusage')) {
  604. /* Avoid warnings with Win32 */
  605. $dat = @getrusage();
  606. if (isset($dat) && is_array($dat)) {
  607. $Str = '';
  608. foreach ($dat as $k => $v)
  609. {
  610. $Str .= $k . $v;
  611. }
  612. sq_mt_seed(md5($Str));
  613. }
  614. }
  615. if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
  616. sq_mt_seed(md5($unique_id));
  617. }
  618. $randomized = 1;
  619. }
  620. /**
  621. * Creates encryption key
  622. *
  623. * Creates an encryption key for encrypting the password stored in the cookie.
  624. * The encryption key itself is stored in the session.
  625. *
  626. * Pad must be longer or equal to encoded string length in 1.4.4/1.5.0 and older.
  627. * @param int $length optional, length of the string to generate
  628. * @return string the encryption key
  629. * @since 1.0
  630. */
  631. function OneTimePadCreate ($length=100) {
  632. sq_mt_randomize();
  633. $pad = '';
  634. for ($i = 0; $i < $length; $i++) {
  635. $pad .= chr(mt_rand(0,255));
  636. }
  637. return base64_encode($pad);
  638. }
  639. /**
  640. * Returns a string showing the size of the message/attachment.
  641. *
  642. * @param int $bytes the filesize in bytes
  643. * @return string the filesize in human readable format
  644. * @since 1.0
  645. */
  646. function show_readable_size($bytes) {
  647. $bytes /= 1024;
  648. $type = 'k';
  649. if ($bytes / 1024 > 1) {
  650. $bytes /= 1024;
  651. $type = 'M';
  652. }
  653. if ($bytes < 10) {
  654. $bytes *= 10;
  655. settype($bytes, 'integer');
  656. $bytes /= 10;
  657. } else {
  658. settype($bytes, 'integer');
  659. }
  660. return $bytes . '&nbsp;' . $type;
  661. }
  662. /**
  663. * Generates a random string from the character set you pass in
  664. *
  665. * @param int $size the length of the string to generate
  666. * @param string $chars a string containing the characters to use
  667. * @param int $flags a flag to add a specific set to the characters to use:
  668. * Flags:
  669. * 1 = add lowercase a-z to $chars
  670. * 2 = add uppercase A-Z to $chars
  671. * 4 = add numbers 0-9 to $chars
  672. * @return string the random string
  673. * @since 1.0
  674. */
  675. function GenerateRandomString($size, $chars, $flags = 0) {
  676. if ($flags & 0x1) {
  677. $chars .= 'abcdefghijklmnopqrstuvwxyz';
  678. }
  679. if ($flags & 0x2) {
  680. $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  681. }
  682. if ($flags & 0x4) {
  683. $chars .= '0123456789';
  684. }
  685. if (($size < 1) || (strlen($chars) < 1)) {
  686. return '';
  687. }
  688. sq_mt_randomize(); /* Initialize the random number generator */
  689. $String = '';
  690. $j = strlen( $chars ) - 1;
  691. while (strlen($String) < $size) {
  692. $String .= $chars{mt_rand(0, $j)};
  693. }
  694. return $String;
  695. }
  696. /**
  697. * Escapes special characters for use in IMAP commands.
  698. *
  699. * @param string $str the string to escape
  700. * @return string the escaped string
  701. * @since 1.0.3
  702. */
  703. function quoteimap($str) {
  704. return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
  705. }
  706. /**
  707. * Trims array
  708. *
  709. * Trims every element in the array, ie. remove the first char of each element
  710. * @param array $array the array to trim
  711. * @since 1.2.0
  712. */
  713. function TrimArray(&$array) {
  714. foreach ($array as $k => $v) {
  715. global $$k;
  716. if (is_array($$k)) {
  717. foreach ($$k as $k2 => $v2) {
  718. $$k[$k2] = substr($v2, 1);
  719. }
  720. } else {
  721. $$k = substr($v, 1);
  722. }
  723. /* Re-assign back to array. */
  724. $array[$k] = $$k;
  725. }
  726. }
  727. /**
  728. * Create compose link
  729. *
  730. * Returns a link to the compose-page, taking in consideration
  731. * the compose_in_new and javascript settings.
  732. * @param string $url the URL to the compose page
  733. * @param string $text the link text, default "Compose"
  734. * @param string $target (since 1.4.3) url target
  735. * @return string a link to the compose page
  736. * @since 1.4.2
  737. */
  738. function makeComposeLink($url, $text = null, $target='') {
  739. global $compose_new_win,$javascript_on, $compose_width, $compose_height;
  740. if(!$text) {
  741. $text = _("Compose");
  742. }
  743. // if not using "compose in new window", make
  744. // regular link and be done with it
  745. if($compose_new_win != '1') {
  746. return makeInternalLink($url, $text, $target);
  747. }
  748. // build the compose in new window link...
  749. // if javascript is on, use onclick event to handle it
  750. if($javascript_on) {
  751. sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
  752. $compuri = $base_uri.$url;
  753. return "<a href=\"javascript:void(0)\" onclick=\"comp_in_new('$compuri','$compose_width','$compose_height')\">$text</a>";
  754. }
  755. // otherwise, just open new window using regular HTML
  756. return makeInternalLink($url, $text, '_blank');
  757. }
  758. /**
  759. * Print variable
  760. *
  761. * sm_print_r($some_variable, [$some_other_variable [, ...]]);
  762. *
  763. * Debugging function - does the same as print_r, but makes sure special
  764. * characters are converted to htmlentities first. This will allow
  765. * values like <some@email.address> to be displayed.
  766. * The output is wrapped in <<pre>> and <</pre>> tags.
  767. * Since 1.4.2 accepts unlimited number of arguments.
  768. * @since 1.4.1
  769. * @return void
  770. */
  771. function sm_print_r() {
  772. ob_start(); // Buffer output
  773. foreach(func_get_args() as $var) {
  774. print_r($var);
  775. echo "\n";
  776. // php has get_class_methods function that can print class methods
  777. if (is_object($var)) {
  778. // get class methods if $var is object
  779. $aMethods=get_class_methods(get_class($var));
  780. // make sure that $aMethods is array and array is not empty
  781. if (is_array($aMethods) && $aMethods!=array()) {
  782. echo "Object methods:\n";
  783. foreach($aMethods as $method) {
  784. echo '* ' . $method . "\n";
  785. }
  786. }
  787. echo "\n";
  788. }
  789. }
  790. $buffer = ob_get_contents(); // Grab the print_r output
  791. ob_end_clean(); // Silently discard the output & stop buffering
  792. print '<div align="left"><pre>';
  793. print htmlentities($buffer);
  794. print '</pre></div>';
  795. }
  796. /**
  797. * version of fwrite which checks for failure
  798. * @param resource $fp
  799. * @param string $string
  800. * @return number of written bytes. false on failure
  801. * @since 1.4.3
  802. */
  803. function sq_fwrite($fp, $string) {
  804. // write to file
  805. $count = @fwrite($fp,$string);
  806. // the number of bytes written should be the length of the string
  807. if($count != strlen($string)) {
  808. return FALSE;
  809. }
  810. return $count;
  811. }
  812. /**
  813. * sq_get_html_translation_table
  814. *
  815. * Returns the translation table used by sq_htmlentities()
  816. *
  817. * @param integer $table html translation table. Possible values (without quotes):
  818. * <ul>
  819. * <li>HTML_ENTITIES - full html entities table defined by charset</li>
  820. * <li>HTML_SPECIALCHARS - html special characters table</li>
  821. * </ul>
  822. * @param integer $quote_style quote encoding style. Possible values (without quotes):
  823. * <ul>
  824. * <li>ENT_COMPAT - (default) encode double quotes</li>
  825. * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
  826. * <li>ENT_QUOTES - encode double and single quotes</li>
  827. * </ul>
  828. * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
  829. * @return array html translation array
  830. * @since 1.5.1
  831. */
  832. function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT,$charset='us-ascii') {
  833. global $default_charset;
  834. if ($table == HTML_SPECIALCHARS) $charset='us-ascii';
  835. // Start array with ampersand
  836. $sq_html_ent_table = array( "&" => '&amp;' );
  837. // < and >
  838. $sq_html_ent_table = array_merge($sq_html_ent_table,
  839. array("<" => '&lt;',
  840. ">" => '&gt;')
  841. );
  842. // double quotes
  843. if ($quote_style == ENT_COMPAT)
  844. $sq_html_ent_table = array_merge($sq_html_ent_table,
  845. array("\"" => '&quot;')
  846. );
  847. // double and single quotes
  848. if ($quote_style == ENT_QUOTES)
  849. $sq_html_ent_table = array_merge($sq_html_ent_table,
  850. array("\"" => '&quot;',
  851. "'" => '&#39;')
  852. );
  853. if ($charset=='auto') $charset=$default_charset;
  854. // add entities that depend on charset
  855. switch($charset){
  856. case 'iso-8859-1':
  857. include_once(SM_PATH . 'functions/htmlentities/iso-8859-1.php');
  858. break;
  859. case 'utf-8':
  860. include_once(SM_PATH . 'functions/htmlentities/utf-8.php');
  861. break;
  862. case 'us-ascii':
  863. default:
  864. break;
  865. }
  866. // return table
  867. return $sq_html_ent_table;
  868. }
  869. /**
  870. * sq_htmlentities
  871. *
  872. * Convert all applicable characters to HTML entities.
  873. * Minimal php requirement - v.4.0.5.
  874. *
  875. * Function is designed for people that want to use full power of htmlentities() in
  876. * i18n environment.
  877. *
  878. * @param string $string string that has to be sanitized
  879. * @param integer $quote_style quote encoding style. Possible values (without quotes):
  880. * <ul>
  881. * <li>ENT_COMPAT - (default) encode double quotes</li>
  882. * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
  883. * <li>ENT_QUOTES - encode double and single quotes</li>
  884. * </ul>
  885. * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
  886. * @return string sanitized string
  887. * @since 1.5.1
  888. */
  889. function sq_htmlentities($string,$quote_style=ENT_COMPAT,$charset='us-ascii') {
  890. // get translation table
  891. $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES,$quote_style,$charset);
  892. // convert characters
  893. return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
  894. }
  895. /**
  896. * Tests if string contains 8bit symbols.
  897. *
  898. * If charset is not set, function defaults to default_charset.
  899. * $default_charset global must be set correctly if $charset is
  900. * not used.
  901. * @param string $string tested string
  902. * @param string $charset charset used in a string
  903. * @return bool true if 8bit symbols are detected
  904. * @since 1.5.1 and 1.4.4
  905. */
  906. function sq_is8bit($string,$charset='') {
  907. global $default_charset;
  908. if ($charset=='') $charset=$default_charset;
  909. /**
  910. * Don't use \240 in ranges. Sometimes RH 7.2 doesn't like it.
  911. * Don't use \200-\237 for iso-8859-x charsets. This range
  912. * stores control symbols in those charsets.
  913. * Use preg_match instead of ereg in order to avoid problems
  914. * with mbstring overloading
  915. */
  916. if (preg_match("/^iso-8859/i",$charset)) {
  917. $needle='/\240|[\241-\377]/';
  918. } else {
  919. $needle='/[\200-\237]|\240|[\241-\377]/';
  920. }
  921. return preg_match("$needle",$string);
  922. }
  923. /**
  924. * Replacement of mb_list_encodings function
  925. *
  926. * This function provides replacement for function that is available only
  927. * in php 5.x. Function does not test all mbstring encodings. Only the ones
  928. * that might be used in SM translations.
  929. *
  930. * Supported strings are stored in session in order to reduce number of
  931. * mb_internal_encoding function calls.
  932. *
  933. * If you want to test all mbstring encodings - fill $list_of_encodings
  934. * array.
  935. * @return array list of encodings supported by php mbstring extension
  936. * @since 1.5.1
  937. */
  938. function sq_mb_list_encodings() {
  939. if (! function_exists('mb_internal_encoding'))
  940. return array();
  941. // php 5+ function
  942. if (function_exists('mb_list_encodings')) {
  943. $ret = mb_list_encodings();
  944. array_walk($ret,'sq_lowercase_array_vals');
  945. return $ret;
  946. }
  947. // don't try to test encodings, if they are already stored in session
  948. if (sqgetGlobalVar('mb_supported_encodings',$mb_supported_encodings,SQ_SESSION))
  949. return $mb_supported_encodings;
  950. // save original encoding
  951. $orig_encoding=mb_internal_encoding();
  952. $list_of_encoding=array(
  953. 'pass',
  954. 'auto',
  955. 'ascii',
  956. 'jis',
  957. 'utf-8',
  958. 'sjis',
  959. 'euc-jp',
  960. 'iso-8859-1',
  961. 'iso-8859-2',
  962. 'iso-8859-7',
  963. 'iso-8859-9',
  964. 'iso-8859-15',
  965. 'koi8-r',
  966. 'koi8-u',
  967. 'big5',
  968. 'gb2312',
  969. 'gb18030',
  970. 'windows-1251',
  971. 'windows-1255',
  972. 'windows-1256',
  973. 'tis-620',
  974. 'iso-2022-jp',
  975. 'euc-cn',
  976. 'euc-kr',
  977. 'euc-tw',
  978. 'uhc',
  979. 'utf7-imap');
  980. $supported_encodings=array();
  981. foreach ($list_of_encoding as $encoding) {
  982. // try setting encodings. suppress warning messages
  983. if (@mb_internal_encoding($encoding))
  984. $supported_encodings[]=$encoding;
  985. }
  986. // restore original encoding
  987. mb_internal_encoding($orig_encoding);
  988. // register list in session
  989. sqsession_register($supported_encodings,'mb_supported_encodings');
  990. return $supported_encodings;
  991. }
  992. /**
  993. * Callback function used to lowercase array values.
  994. * @param string $val array value
  995. * @param mixed $key array key
  996. * @since 1.5.1
  997. */
  998. function sq_lowercase_array_vals(&$val,$key) {
  999. $val = strtolower($val);
  1000. }
  1001. /**
  1002. * Function returns number of characters in string.
  1003. *
  1004. * Returned number might be different from number of bytes in string,
  1005. * if $charset is multibyte charset. Detection depends on mbstring
  1006. * functions. If mbstring does not support tested multibyte charset,
  1007. * vanilla string length function is used.
  1008. * @param string $str string
  1009. * @param string $charset charset
  1010. * @since 1.5.1
  1011. * @return integer number of characters in string
  1012. */
  1013. function sq_strlen($str, $charset=null){
  1014. // default option
  1015. if (is_null($charset)) return strlen($str);
  1016. // lowercase charset name
  1017. $charset=strtolower($charset);
  1018. // use automatic charset detection, if function call asks for it
  1019. if ($charset=='auto') {
  1020. global $default_charset;
  1021. set_my_charset();
  1022. $charset=$default_charset;
  1023. }
  1024. // Use mbstring only with listed charsets
  1025. $aList_of_mb_charsets=array('utf-8','big5','gb2312','gb18030','euc-jp','euc-cn','euc-tw','euc-kr');
  1026. // calculate string length according to charset
  1027. if (in_array($charset,$aList_of_mb_charsets) && in_array($charset,sq_mb_list_encodings())) {
  1028. $real_length = mb_strlen($str,$charset);
  1029. } else {
  1030. // own strlen detection code is removed because missing strpos,
  1031. // strtoupper and substr implementations break string wrapping.
  1032. $real_length=strlen($str);
  1033. }
  1034. return $real_length;
  1035. }
  1036. /**
  1037. * string padding with multibyte support
  1038. *
  1039. * @link http://www.php.net/str_pad
  1040. * @param string $string original string
  1041. * @param integer $width padded string width
  1042. * @param string $pad padding symbols
  1043. * @param integer $padtype padding type
  1044. * (internal php defines, see str_pad() description)
  1045. * @param string $charset charset used in original string
  1046. * @return string padded string
  1047. */
  1048. function sq_str_pad($string, $width, $pad, $padtype, $charset='') {
  1049. $charset = strtolower($charset);
  1050. $padded_string = '';
  1051. switch ($charset) {
  1052. case 'utf-8':
  1053. case 'big5':
  1054. case 'gb2312':
  1055. case 'euc-kr':
  1056. /*
  1057. * all multibyte charsets try to increase width value by
  1058. * adding difference between number of bytes and real length
  1059. */
  1060. $width = $width - sq_strlen($string,$charset) + strlen($string);
  1061. default:
  1062. $padded_string=str_pad($string,$width,$pad,$padtype);
  1063. }
  1064. return $padded_string;
  1065. }
  1066. /**
  1067. * Wrapper that is used to switch between vanilla and multibyte substr
  1068. * functions.
  1069. * @param string $string
  1070. * @param integer $start
  1071. * @param integer $length
  1072. * @param string $charset
  1073. * @return string
  1074. * @since 1.5.1
  1075. * @link http://www.php.net/substr
  1076. * @link http://www.php.net/mb_substr
  1077. */
  1078. function sq_substr($string,$start,$length,$charset='auto') {
  1079. // use automatic charset detection, if function call asks for it
  1080. if ($charset=='auto') {
  1081. global $default_charset;
  1082. set_my_charset();
  1083. $charset=$default_charset;
  1084. }
  1085. $charset = strtolower($charset);
  1086. if (function_exists('mb_internal_encoding') &&
  1087. in_array($charset,sq_mb_list_encodings())) {
  1088. return mb_substr($string,$start,$length,$charset);
  1089. }
  1090. // TODO: add mbstring independent code
  1091. // use vanilla string functions as last option
  1092. return substr($string,$start,$length);
  1093. }
  1094. /**
  1095. * Wrapper that is used to switch between vanilla and multibyte strpos
  1096. * functions.
  1097. * @param string $haystack
  1098. * @param mixed $needle
  1099. * @param integer $offset
  1100. * @param string $charset
  1101. * @return string
  1102. * @since 1.5.1
  1103. * @link http://www.php.net/strpos
  1104. * @link http://www.php.net/mb_strpos
  1105. */
  1106. function sq_strpos($haystack,$needle,$offset,$charset='auto') {
  1107. // use automatic charset detection, if function call asks for it
  1108. if ($charset=='auto') {
  1109. global $default_charset;
  1110. set_my_charset();
  1111. $charset=$default_charset;
  1112. }
  1113. $charset = strtolower($charset);
  1114. if (function_exists('mb_internal_encoding') &&
  1115. in_array($charset,sq_mb_list_encodings())) {
  1116. return mb_strpos($haystack,$needle,$offset,$charset);
  1117. }
  1118. // TODO: add mbstring independent code
  1119. // use vanilla string functions as last option
  1120. return strpos($haystack,$needle,$offset);
  1121. }
  1122. /**
  1123. * Wrapper that is used to switch between vanilla and multibyte strtoupper
  1124. * functions.
  1125. * @param string $string
  1126. * @param string $charset
  1127. * @return string
  1128. * @since 1.5.1
  1129. * @link http://www.php.net/strtoupper
  1130. * @link http://www.php.net/mb_strtoupper
  1131. */
  1132. function sq_strtoupper($string,$charset='auto') {
  1133. // use automatic charset detection, if function call asks for it
  1134. if ($charset=='auto') {
  1135. global $default_charset;
  1136. set_my_charset();
  1137. $charset=$default_charset;
  1138. }
  1139. $charset = strtolower($charset);
  1140. if (function_exists('mb_strtoupper') &&
  1141. in_array($charset,sq_mb_list_encodings())) {
  1142. return mb_strtoupper($string,$charset);
  1143. }
  1144. // TODO: add mbstring independent code
  1145. // use vanilla string functions as last option
  1146. return strtoupper($string);
  1147. }
  1148. /**
  1149. * Counts 8bit bytes in string
  1150. * @param string $string tested string
  1151. * @return integer number of 8bit bytes
  1152. */
  1153. function sq_count8bit($string) {
  1154. $count=0;
  1155. for ($i=0; $i<strlen($string); $i++) {
  1156. if (ord($string[$i]) > 127) $count++;
  1157. }
  1158. return $count;
  1159. }
  1160. ?>