strings.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220
  1. <?php
  2. /**
  3. * strings.php
  4. *
  5. * Copyright (c) 1999-2005 The SquirrelMail Project Team
  6. * Licensed under the GNU GPL. For full terms see the file COPYING.
  7. *
  8. * This code provides various string manipulation functions that are
  9. * used by the rest of the SquirrelMail code.
  10. *
  11. * @version $Id$
  12. * @package squirrelmail
  13. */
  14. /**
  15. * SquirrelMail version number -- DO NOT CHANGE
  16. */
  17. global $version;
  18. $version = '1.5.1 [CVS]';
  19. /**
  20. * SquirrelMail internal version number -- DO NOT CHANGE
  21. * $sm_internal_version = array (release, major, minor)
  22. */
  23. global $SQM_INTERNAL_VERSION;
  24. $SQM_INTERNAL_VERSION = array(1,5,1);
  25. /**
  26. * There can be a circular issue with includes, where the $version string is
  27. * referenced by the include of global.php, etc. before it's defined.
  28. * For that reason, bring in global.php AFTER we define the version strings.
  29. */
  30. require_once(SM_PATH . 'functions/global.php');
  31. /**
  32. * Appends citation markers to the string.
  33. * Also appends a trailing space.
  34. *
  35. * @author Justus Pendleton
  36. *
  37. * @param string str The string to append to
  38. * @param int citeLevel the number of markers to append
  39. * @return null
  40. */
  41. function sqMakeCite (&$str, $citeLevel) {
  42. for ($i = 0; $i < $citeLevel; $i++) {
  43. $str .= '>';
  44. }
  45. if ($citeLevel != 0) {
  46. $str .= ' ';
  47. }
  48. }
  49. /**
  50. * Create a newline in the string, adding citation
  51. * markers to the newline as necessary.
  52. *
  53. * @author Justus Pendleton
  54. *
  55. * @param string str the string to make a newline in
  56. * @param int citeLevel the citation level the newline is at
  57. * @param int column starting column of the newline
  58. * @return null
  59. */
  60. function sqMakeNewLine (&$str, $citeLevel, &$column) {
  61. $str .= "\n";
  62. $column = 0;
  63. if ($citeLevel > 0) {
  64. sqMakeCite ($str, $citeLevel);
  65. $column = $citeLevel + 1;
  66. } else {
  67. $column = 0;
  68. }
  69. }
  70. /**
  71. * Checks for spaces in strings - only used if PHP doesn't have native ctype support
  72. *
  73. * @author Tomas Kuliavas
  74. *
  75. * You might be able to rewrite the function by adding short evaluation form.
  76. *
  77. * possible problems:
  78. * - iso-2022-xx charsets - hex 20 might be part of other symbol. I might
  79. * be wrong. 0x20 is not used in iso-2022-jp. I haven't checked iso-2022-kr
  80. * and iso-2022-cn mappings.
  81. *
  82. * - no-break space (&nbsp;) - it is 8bit symbol, that depends on charset.
  83. * there are at least three different charset groups that have nbsp in
  84. * different places.
  85. *
  86. * I don't see any charset/nbsp options in php ctype either.
  87. *
  88. * @param string $string tested string
  89. * @return bool true when only whitespace symbols are present in test string
  90. */
  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. *
  106. * @param string body the entire body of text
  107. * @param int wrap the maximum line length
  108. * @return string the wrapped text
  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 = 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) && ($body{$pos} == '>')) {
  132. $newCiteLevel++;
  133. $pos++;
  134. // skip over any spaces interleaved among the cite markers
  135. while (($pos < $length) && ($body{$pos} == ' ')) {
  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 (($body{$pos} == "\n" ) && (strlen($outString) != 0)) {
  146. $outStringLast = $outString{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 = 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 .= 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 ($body{$pos}))) {
  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) && ($body{$nextNewline} == "\n")) {
  209. $nextNewline++;
  210. }
  211. // trim trailing spaces
  212. $lastRealChar = $nextNewline;
  213. while (($lastRealChar > $pos && $lastRealChar < $length) && (ctype_space ($body{$lastRealChar}))) {
  214. $lastRealChar--;
  215. }
  216. // decide if appending the short string is what we want
  217. if (($nextNewline < $length && $body{$nextNewline} == "\n") &&
  218. isset($lastRealChar)) {
  219. $mypos = $pos;
  220. //check the first word:
  221. while (($mypos < $length) && ($body{$mypos} == '>')) {
  222. $mypos++;
  223. // skip over any spaces interleaved among the cite markers
  224. while (($mypos < $length) && ($body{$mypos} == ' ')) {
  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 = substr($body,$mypos,strpos($body,' ',$mypos) - $mypos);
  237. //if ($dowrap || $ldnspacecnt > 1 || ($firstword && (
  238. if (!$smartwrap || $firstword && (
  239. $firstword{0} == '-' ||
  240. $firstword{0} == '+' ||
  241. $firstword{0} == '*' ||
  242. $firstword{0} == strtoupper($firstword{0}) ||
  243. strpos($firstword,':'))) {
  244. $outString .= 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 .= 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 ($body{$breakPoint}))) {
  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 = 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 += strlen ($substring);
  304. // advance past the whitespace which caused the wrap
  305. $pos = $breakPoint;
  306. while (($pos < $length) && (ctype_space ($body{$pos}))) {
  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. */
  330. function sqWordWrap(&$line, $wrap, $charset='') {
  331. global $languages, $squirrelmail_language;
  332. // Use custom wrapping function, if translation provides it
  333. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  334. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap')) {
  335. if (mb_detect_encoding($line) != 'ASCII') {
  336. $line = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap', $line, $wrap);
  337. return;
  338. }
  339. }
  340. ereg("^([\t >]*)([^\t >].*)?$", $line, $regs);
  341. $beginning_spaces = $regs[1];
  342. if (isset($regs[2])) {
  343. $words = explode(' ', $regs[2]);
  344. } else {
  345. $words = '';
  346. }
  347. $i = 0;
  348. $line = $beginning_spaces;
  349. while ($i < count($words)) {
  350. /* Force one word to be on a line (minimum) */
  351. $line .= $words[$i];
  352. $line_len = strlen($beginning_spaces) + sq_strlen($words[$i],$charset) + 2;
  353. if (isset($words[$i + 1]))
  354. $line_len += sq_strlen($words[$i + 1],$charset);
  355. $i ++;
  356. /* Add more words (as long as they fit) */
  357. while ($line_len < $wrap && $i < count($words)) {
  358. $line .= ' ' . $words[$i];
  359. $i++;
  360. if (isset($words[$i]))
  361. $line_len += sq_strlen($words[$i],$charset) + 1;
  362. else
  363. $line_len += 1;
  364. }
  365. /* Skip spaces if they are the first thing on a continued line */
  366. while (!isset($words[$i]) && $i < count($words)) {
  367. $i ++;
  368. }
  369. /* Go to the next line if we have more to process */
  370. if ($i < count($words)) {
  371. $line .= "\n";
  372. }
  373. }
  374. }
  375. /**
  376. * Does the opposite of sqWordWrap()
  377. * @param string body the text to un-wordwrap
  378. * @return void
  379. */
  380. function sqUnWordWrap(&$body) {
  381. global $squirrelmail_language;
  382. if ($squirrelmail_language == 'ja_JP') {
  383. return;
  384. }
  385. $lines = explode("\n", $body);
  386. $body = '';
  387. $PreviousSpaces = '';
  388. $cnt = count($lines);
  389. for ($i = 0; $i < $cnt; $i ++) {
  390. preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
  391. $CurrentSpaces = $regs[1];
  392. if (isset($regs[2])) {
  393. $CurrentRest = $regs[2];
  394. } else {
  395. $CurrentRest = '';
  396. }
  397. if ($i == 0) {
  398. $PreviousSpaces = $CurrentSpaces;
  399. $body = $lines[$i];
  400. } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
  401. && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
  402. && strlen($CurrentRest)) { /* and there's a line to continue with */
  403. $body .= ' ' . $CurrentRest;
  404. } else {
  405. $body .= "\n" . $lines[$i];
  406. $PreviousSpaces = $CurrentSpaces;
  407. }
  408. }
  409. $body .= "\n";
  410. }
  411. /**
  412. * If $haystack is a full mailbox name and $needle is the mailbox
  413. * separator character, returns the last part of the mailbox name.
  414. *
  415. * @param string haystack full mailbox name to search
  416. * @param string needle the mailbox separator character
  417. * @return string the last part of the mailbox name
  418. */
  419. function readShortMailboxName($haystack, $needle) {
  420. if ($needle == '') {
  421. $elem = $haystack;
  422. } else {
  423. $parts = explode($needle, $haystack);
  424. $elem = array_pop($parts);
  425. while ($elem == '' && count($parts)) {
  426. $elem = array_pop($parts);
  427. }
  428. }
  429. return( $elem );
  430. }
  431. /**
  432. * php_self
  433. *
  434. * Creates an URL for the page calling this function, using either the PHP global
  435. * REQUEST_URI, or the PHP global PHP_SELF with QUERY_STRING added.
  436. *
  437. * @return string the complete url for this page
  438. */
  439. function php_self () {
  440. if ( sqgetGlobalVar('REQUEST_URI', $req_uri, SQ_SERVER) && !empty($req_uri) ) {
  441. return $req_uri;
  442. }
  443. if ( sqgetGlobalVar('PHP_SELF', $php_self, SQ_SERVER) && !empty($php_self) ) {
  444. // need to add query string to end of PHP_SELF to match REQUEST_URI
  445. //
  446. if ( sqgetGlobalVar('QUERY_STRING', $query_string, SQ_SERVER) && !empty($query_string) ) {
  447. $php_self .= '?' . $query_string;
  448. }
  449. return $php_self;
  450. }
  451. return '';
  452. }
  453. /**
  454. * get_location
  455. *
  456. * Determines the location to forward to, relative to your server.
  457. * This is used in HTTP Location: redirects.
  458. * If this doesnt work correctly for you (although it should), you can
  459. * remove all this code except the last two lines, and have it return
  460. * the right URL for your site, something like:
  461. *
  462. * http://www.example.com/squirrelmail/
  463. *
  464. * @return string the base url for this SquirrelMail installation
  465. */
  466. function get_location () {
  467. global $imap_server_type;
  468. /* Get the path, handle virtual directories */
  469. if(strpos(php_self(), '?')) {
  470. $path = substr(php_self(), 0, strpos(php_self(), '?'));
  471. } else {
  472. $path = php_self();
  473. }
  474. $path = substr($path, 0, strrpos($path, '/'));
  475. if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
  476. return $full_url . $path;
  477. }
  478. /* Check if this is a HTTPS or regular HTTP request. */
  479. $proto = 'http://';
  480. /*
  481. * If you have 'SSLOptions +StdEnvVars' in your apache config
  482. * OR if you have HTTPS=on in your HTTP_SERVER_VARS
  483. * OR if you are on port 443
  484. */
  485. $getEnvVar = getenv('HTTPS');
  486. if ((isset($getEnvVar) && !strcasecmp($getEnvVar, 'on')) ||
  487. (sqgetGlobalVar('HTTPS', $https_on, SQ_SERVER) && !strcasecmp($https_on, 'on')) ||
  488. (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER) && $server_port == 443)) {
  489. $proto = 'https://';
  490. }
  491. /* Get the hostname from the Host header or server config. */
  492. if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
  493. if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
  494. $host = '';
  495. }
  496. }
  497. $port = '';
  498. if (! strstr($host, ':')) {
  499. if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
  500. if (($server_port != 80 && $proto == 'http://') ||
  501. ($server_port != 443 && $proto == 'https://')) {
  502. $port = sprintf(':%d', $server_port);
  503. }
  504. }
  505. }
  506. /* this is a workaround for the weird macosx caching that
  507. causes Apache to return 16080 as the port number, which causes
  508. SM to bail */
  509. if ($imap_server_type == 'macosx' && $port == ':16080') {
  510. $port = '';
  511. }
  512. /* Fallback is to omit the server name and use a relative */
  513. /* URI, although this is not RFC 2616 compliant. */
  514. $full_url = ($host ? $proto . $host . $port : '');
  515. sqsession_register($full_url, 'sq_base_url');
  516. return $full_url . $path;
  517. }
  518. /**
  519. * Encrypts password
  520. *
  521. * These functions are used to encrypt the password before it is
  522. * stored in a cookie. The encryption key is generated by
  523. * OneTimePadCreate();
  524. *
  525. * @param string string the (password)string to encrypt
  526. * @param string epad the encryption key
  527. * @return string the base64-encoded encrypted password
  528. */
  529. function OneTimePadEncrypt ($string, $epad) {
  530. $pad = base64_decode($epad);
  531. $encrypted = '';
  532. for ($i = 0; $i < strlen ($string); $i++) {
  533. $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
  534. }
  535. return base64_encode($encrypted);
  536. }
  537. /**
  538. * Decrypts a password from the cookie
  539. *
  540. * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
  541. * This uses the encryption key that is stored in the session.
  542. *
  543. * @param string string the string to decrypt
  544. * @param string epad the encryption key from the session
  545. * @return string the decrypted password
  546. */
  547. function OneTimePadDecrypt ($string, $epad) {
  548. $pad = base64_decode($epad);
  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
  564. * @return void
  565. */
  566. function sq_mt_seed($Val) {
  567. /* if mt_getrandmax() does not return a 2^n - 1 number,
  568. this might not work well. This uses $Max as a bitmask. */
  569. $Max = mt_getrandmax();
  570. if (! is_int($Val)) {
  571. $Val = crc32($Val);
  572. }
  573. if ($Val < 0) {
  574. $Val *= -1;
  575. }
  576. if ($Val == 0) {
  577. return;
  578. }
  579. mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
  580. }
  581. /**
  582. * Init random number generator
  583. *
  584. * This function initializes the random number generator fairly well.
  585. * It also only initializes it once, so you don't accidentally get
  586. * the same 'random' numbers twice in one session.
  587. *
  588. * @return void
  589. */
  590. function sq_mt_randomize() {
  591. static $randomized;
  592. if ($randomized) {
  593. return;
  594. }
  595. /* Global. */
  596. sqgetGlobalVar('REMOTE_PORT', $remote_port, SQ_SERVER);
  597. sqgetGlobalVar('REMOTE_ADDR', $remote_addr, SQ_SERVER);
  598. sq_mt_seed((int)((double) microtime() * 1000000));
  599. sq_mt_seed(md5($remote_port . $remote_addr . getmypid()));
  600. /* getrusage */
  601. if (function_exists('getrusage')) {
  602. /* Avoid warnings with Win32 */
  603. $dat = @getrusage();
  604. if (isset($dat) && is_array($dat)) {
  605. $Str = '';
  606. foreach ($dat as $k => $v)
  607. {
  608. $Str .= $k . $v;
  609. }
  610. sq_mt_seed(md5($Str));
  611. }
  612. }
  613. if(sqgetGlobalVar('UNIQUE_ID', $unique_id, SQ_SERVER)) {
  614. sq_mt_seed(md5($unique_id));
  615. }
  616. $randomized = 1;
  617. }
  618. /**
  619. * Creates encryption key
  620. *
  621. * Creates an encryption key for encrypting the password stored in the cookie.
  622. * The encryption key itself is stored in the session.
  623. *
  624. * @param int length optional, length of the string to generate
  625. * @return string the encryption key
  626. */
  627. function OneTimePadCreate ($length=100) {
  628. sq_mt_randomize();
  629. $pad = '';
  630. for ($i = 0; $i < $length; $i++) {
  631. $pad .= chr(mt_rand(0,255));
  632. }
  633. return base64_encode($pad);
  634. }
  635. /**
  636. * Returns a string showing the size of the message/attachment.
  637. *
  638. * @param int bytes the filesize in bytes
  639. * @return string the filesize in human readable format
  640. */
  641. function show_readable_size($bytes) {
  642. $bytes /= 1024;
  643. $type = 'k';
  644. if ($bytes / 1024 > 1) {
  645. $bytes /= 1024;
  646. $type = 'M';
  647. }
  648. if ($bytes < 10) {
  649. $bytes *= 10;
  650. settype($bytes, 'integer');
  651. $bytes /= 10;
  652. } else {
  653. settype($bytes, 'integer');
  654. }
  655. return $bytes . '<small>&nbsp;' . $type . '</small>';
  656. }
  657. /**
  658. * Generates a random string from the character set you pass in
  659. *
  660. * @param int size the size of the string to generate
  661. * @param string chars a string containing the characters to use
  662. * @param int flags a flag to add a specific set to the characters to use:
  663. * Flags:
  664. * 1 = add lowercase a-z to $chars
  665. * 2 = add uppercase A-Z to $chars
  666. * 4 = add numbers 0-9 to $chars
  667. * @return string the random string
  668. */
  669. function GenerateRandomString($size, $chars, $flags = 0) {
  670. if ($flags & 0x1) {
  671. $chars .= 'abcdefghijklmnopqrstuvwxyz';
  672. }
  673. if ($flags & 0x2) {
  674. $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  675. }
  676. if ($flags & 0x4) {
  677. $chars .= '0123456789';
  678. }
  679. if (($size < 1) || (strlen($chars) < 1)) {
  680. return '';
  681. }
  682. sq_mt_randomize(); /* Initialize the random number generator */
  683. $String = '';
  684. $j = strlen( $chars ) - 1;
  685. while (strlen($String) < $size) {
  686. $String .= $chars{mt_rand(0, $j)};
  687. }
  688. return $String;
  689. }
  690. /**
  691. * Escapes special characters for use in IMAP commands.
  692. *
  693. * @param string the string to escape
  694. * @return string the escaped string
  695. */
  696. function quoteimap($str) {
  697. return preg_replace("/([\"\\\\])/", "\\\\$1", $str);
  698. }
  699. /**
  700. * Trims array
  701. *
  702. * Trims every element in the array, ie. remove the first char of each element
  703. * @param array array the array to trim
  704. */
  705. function TrimArray(&$array) {
  706. foreach ($array as $k => $v) {
  707. global $$k;
  708. if (is_array($$k)) {
  709. foreach ($$k as $k2 => $v2) {
  710. $$k[$k2] = substr($v2, 1);
  711. }
  712. } else {
  713. $$k = substr($v, 1);
  714. }
  715. /* Re-assign back to array. */
  716. $array[$k] = $$k;
  717. }
  718. }
  719. /**
  720. * Create compose link
  721. *
  722. * Returns a link to the compose-page, taking in consideration
  723. * the compose_in_new and javascript settings.
  724. * @param string url the URL to the compose page
  725. * @param string text the link text, default "Compose"
  726. * @return string a link to the compose page
  727. */
  728. function makeComposeLink($url, $text = null, $target='')
  729. {
  730. global $compose_new_win,$javascript_on;
  731. if(!$text) {
  732. $text = _("Compose");
  733. }
  734. // if not using "compose in new window", make
  735. // regular link and be done with it
  736. if($compose_new_win != '1') {
  737. return makeInternalLink($url, $text, $target);
  738. }
  739. // build the compose in new window link...
  740. // if javascript is on, use onclick event to handle it
  741. if($javascript_on) {
  742. sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
  743. return '<a href="javascript:void(0)" onclick="comp_in_new(\''.$base_uri.$url.'\')">'. $text.'</a>';
  744. }
  745. // otherwise, just open new window using regular HTML
  746. return makeInternalLink($url, $text, '_blank');
  747. }
  748. /**
  749. * Print variable
  750. *
  751. * sm_print_r($some_variable, [$some_other_variable [, ...]]);
  752. *
  753. * Debugging function - does the same as print_r, but makes sure special
  754. * characters are converted to htmlentities first. This will allow
  755. * values like <some@email.address> to be displayed.
  756. * The output is wrapped in <<pre>> and <</pre>> tags.
  757. *
  758. * @return void
  759. */
  760. function sm_print_r() {
  761. ob_start(); // Buffer output
  762. foreach(func_get_args() as $var) {
  763. print_r($var);
  764. echo "\n";
  765. }
  766. $buffer = ob_get_contents(); // Grab the print_r output
  767. ob_end_clean(); // Silently discard the output & stop buffering
  768. print '<pre>';
  769. print htmlentities($buffer);
  770. print '</pre>';
  771. }
  772. /**
  773. * version of fwrite which checks for failure
  774. */
  775. function sq_fwrite($fp, $string) {
  776. // write to file
  777. $count = @fwrite($fp,$string);
  778. // the number of bytes written should be the length of the string
  779. if($count != strlen($string)) {
  780. return FALSE;
  781. }
  782. return $count;
  783. }
  784. /**
  785. * sq_get_html_translation_table
  786. *
  787. * Returns the translation table used by sq_htmlentities()
  788. *
  789. * @param integer $table html translation table. Possible values (without quotes):
  790. * <ul>
  791. * <li>HTML_ENTITIES - full html entities table defined by charset</li>
  792. * <li>HTML_SPECIALCHARS - html special characters table</li>
  793. * </ul>
  794. * @param integer $quote_style quote encoding style. Possible values (without quotes):
  795. * <ul>
  796. * <li>ENT_COMPAT - (default) encode double quotes</li>
  797. * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
  798. * <li>ENT_QUOTES - encode double and single quotes</li>
  799. * </ul>
  800. * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
  801. * @return array html translation array
  802. */
  803. function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT,$charset='us-ascii') {
  804. global $default_charset;
  805. if ($table == HTML_SPECIALCHARS) $charset='us-ascii';
  806. // Start array with ampersand
  807. $sq_html_ent_table = array( "&" => '&amp;' );
  808. // < and >
  809. $sq_html_ent_table = array_merge($sq_html_ent_table,
  810. array("<" => '&lt;',
  811. ">" => '&gt;')
  812. );
  813. // double quotes
  814. if ($quote_style == ENT_COMPAT)
  815. $sq_html_ent_table = array_merge($sq_html_ent_table,
  816. array("\"" => '&quot;')
  817. );
  818. // double and single quotes
  819. if ($quote_style == ENT_QUOTES)
  820. $sq_html_ent_table = array_merge($sq_html_ent_table,
  821. array("\"" => '&quot;',
  822. "'" => '&#39;')
  823. );
  824. if ($charset=='auto') $charset=$default_charset;
  825. // add entities that depend on charset
  826. switch($charset){
  827. case 'iso-8859-1':
  828. include_once(SM_PATH . 'functions/htmlentities/iso-8859-1.php');
  829. break;
  830. case 'utf-8':
  831. include_once(SM_PATH . 'functions/htmlentities/utf-8.php');
  832. break;
  833. case 'us-ascii':
  834. default:
  835. break;
  836. }
  837. // return table
  838. return $sq_html_ent_table;
  839. }
  840. /**
  841. * sq_htmlentities
  842. *
  843. * Convert all applicable characters to HTML entities.
  844. * Minimal php requirement - v.4.0.5.
  845. *
  846. * Function is designed for people that want to use full power of htmlentities() in
  847. * i18n environment.
  848. *
  849. * @param string $string string that has to be sanitized
  850. * @param integer $quote_style quote encoding style. Possible values (without quotes):
  851. * <ul>
  852. * <li>ENT_COMPAT - (default) encode double quotes</li>
  853. * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
  854. * <li>ENT_QUOTES - encode double and single quotes</li>
  855. * </ul>
  856. * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
  857. * @return string sanitized string
  858. */
  859. function sq_htmlentities($string,$quote_style=ENT_COMPAT,$charset='us-ascii') {
  860. // get translation table
  861. $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES,$quote_style,$charset);
  862. // convert characters
  863. return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
  864. }
  865. /**
  866. * Tests if string contains 8bit symbols.
  867. *
  868. * If charset is not set, function defaults to default_charset.
  869. * $default_charset global must be set correctly if $charset is
  870. * not used.
  871. * @param string $string tested string
  872. * @param string $charset charset used in a string
  873. * @return bool true if 8bit symbols are detected
  874. * @since 1.5.1 and 1.4.4
  875. */
  876. function sq_is8bit($string,$charset='') {
  877. global $default_charset;
  878. if ($charset=='') $charset=$default_charset;
  879. /**
  880. * Don't use \240 in ranges. Sometimes RH 7.2 doesn't like it.
  881. * Don't use \200-\237 for iso-8859-x charsets. This range
  882. * stores control symbols in those charsets.
  883. * Use preg_match instead of ereg in order to avoid problems
  884. * with mbstring overloading
  885. */
  886. if (preg_match("/^iso-8859/i",$charset)) {
  887. $needle='/\240|[\241-\377]/';
  888. } else {
  889. $needle='/[\200-\237]|\240|[\241-\377]/';
  890. }
  891. return preg_match("$needle",$string);
  892. }
  893. /**
  894. * Replacement of mb_list_encodings function
  895. *
  896. * This function provides replacement for function that is available only
  897. * in php 5.x. Function does not test all mbstring encodings. Only the ones
  898. * that might be used in SM translations.
  899. *
  900. * Supported strings are stored in session in order to reduce number of
  901. * mb_internal_encoding function calls.
  902. *
  903. * If you want to test all mbstring encodings - fill $list_of_encodings
  904. * array.
  905. * @return array list of encodings supported by php mbstring extension
  906. * @since 1.5.1
  907. */
  908. function sq_mb_list_encodings() {
  909. if (! function_exists('mb_internal_encoding'))
  910. return array();
  911. // don't try to test encodings, if they are already stored in session
  912. if (sqgetGlobalVar('mb_supported_encodings',$mb_supported_encodings,SQ_SESSION))
  913. return $mb_supported_encodings;
  914. // save original encoding
  915. $orig_encoding=mb_internal_encoding();
  916. $list_of_encoding=array(
  917. 'pass',
  918. 'auto',
  919. 'ascii',
  920. 'jis',
  921. 'utf-8',
  922. 'sjis',
  923. 'euc-jp',
  924. 'iso-8859-1',
  925. 'iso-8859-2',
  926. 'iso-8859-7',
  927. 'iso-8859-9',
  928. 'iso-8859-15',
  929. 'koi8-r',
  930. 'koi8-u',
  931. 'big5',
  932. 'gb2312',
  933. 'windows-1251',
  934. 'windows-1255',
  935. 'windows-1256',
  936. 'tis-620',
  937. 'iso-2022-jp',
  938. 'euc-kr',
  939. 'utf7-imap');
  940. $supported_encodings=array();
  941. foreach ($list_of_encoding as $encoding) {
  942. // try setting encodings. suppress warning messages
  943. if (@mb_internal_encoding($encoding))
  944. $supported_encodings[]=$encoding;
  945. }
  946. // restore original encoding
  947. mb_internal_encoding($orig_encoding);
  948. // register list in session
  949. sqsession_register($supported_encodings,'mb_supported_encodings');
  950. return $supported_encodings;
  951. }
  952. /**
  953. * Function returns number of characters in string.
  954. *
  955. * Returned number might be different from number of bytes in string,
  956. * if $charset is multibyte charset. Currently only utf-8 charset is
  957. * supported.
  958. * @param string $str string
  959. * @param string $charset charset
  960. * @since 1.5.1
  961. * @return integer number of characters in string
  962. */
  963. function sq_strlen($str, $charset=''){
  964. // default option
  965. if ($charset=='') return strlen($str);
  966. // use automatic charset detection, if function call asks for it
  967. if ($charset=='auto') {
  968. global $default_charset;
  969. set_my_charset();
  970. $charset=$default_charset;
  971. }
  972. // lowercase charset name
  973. $charset=strtolower($charset);
  974. // set initial returned length number
  975. $real_length=0;
  976. // calculate string length according to charset
  977. // function can be modulized same way we modulize decode/encode/htmlentities
  978. if ($charset=='utf-8') {
  979. if (function_exists('mb_strlen')) {
  980. $real_length = mb_strlen($str,'utf-8');
  981. } else {
  982. // function needs length of string in bytes.
  983. // mbstring overloading might break it
  984. $str_length=strlen($str);
  985. $str_index=0;
  986. while ($str_index < $str_length) {
  987. // start of internal utf-8 multibyte character detection
  988. if (preg_match("/[\xC0-\xDF]/",$str[$str_index]) &&
  989. isset($str[$str_index+1]) &&
  990. preg_match("/[\x80-\xBF]/",$str[$str_index+1])) {
  991. // two byte utf-8
  992. $str_index=$str_index+2;
  993. $real_length++;
  994. } elseif (preg_match("/[\xE0-\xEF]/",$str[$str_index]) &&
  995. isset($str[$str_index+2]) &&
  996. preg_match("/[\x80-\xBF][\x80-\xBF]/",$str[$str_index+1].$str[$str_index+2])) {
  997. // three byte utf-8
  998. $str_index=$str_index+3;
  999. $real_length++;
  1000. } elseif (preg_match("/[\xF0-\xF7]/",$str[$str_index]) &&
  1001. isset($str[$str_index+3]) &&
  1002. preg_match("/[\x80-\xBF][\x80-\xBF][\x80-\xBF]/",$str[$str_index+1].$str[$str_index+2].$str[$str_index+3])) {
  1003. // four byte utf-8
  1004. $str_index=$str_index+4;
  1005. $real_length++;
  1006. } elseif (preg_match("/[\xF8-\xFB]/",$str[$str_index]) &&
  1007. isset($str[$str_index+4]) &&
  1008. preg_match("/[\x80-\xBF][\x80-\xBF][\x80-\xBF][\x80-\xBF]/",
  1009. $str[$str_index+1].$str[$str_index+2].$str[$str_index+3].$str[$str_index+4])) {
  1010. // five byte utf-8
  1011. $str_index=$str_index+5;
  1012. $real_length++;
  1013. } elseif (preg_match("/[\xFC-\xFD]/",$str[$str_index]) &&
  1014. isset($str[$str_index+5]) &&
  1015. preg_match("/[\x80-\xBF][\x80-\xBF][\x80-\xBF][\x80-\xBF]/",
  1016. $str[$str_index+1].$str[$str_index+2].$str[$str_index+3].$str[$str_index+4].$str[$str_index+5])) {
  1017. // six byte utf-8
  1018. $str_index=$str_index+6;
  1019. $real_length++;
  1020. } else {
  1021. $str_index++;
  1022. $real_length++;
  1023. }
  1024. // end of internal utf-8 multibyte character detection
  1025. }
  1026. }
  1027. // end of utf-8 length detection
  1028. } elseif ($charset=='big5') {
  1029. // TODO: add big5 string length detection
  1030. $real_length=strlen($str);
  1031. } elseif ($charset=='gb2312') {
  1032. // TODO: add gb2312 string length detection
  1033. $real_length=strlen($str);
  1034. } elseif ($charset=='gb18030') {
  1035. // TODO: add gb18030 string length detection
  1036. $real_length=strlen($str);
  1037. } elseif ($charset=='euc-jp') {
  1038. // TODO: add euc-jp string length detection
  1039. $real_length=strlen($str);
  1040. } elseif ($charset=='euc-cn') {
  1041. // TODO: add euc-cn string length detection
  1042. $real_length=strlen($str);
  1043. } elseif ($charset=='euc-tw') {
  1044. // TODO: add euc-tw string length detection
  1045. $real_length=strlen($str);
  1046. } elseif ($charset=='euc-kr') {
  1047. // TODO: add euc-kr string length detection
  1048. $real_length=strlen($str);
  1049. } else {
  1050. $real_length=strlen($str);
  1051. }
  1052. return $real_length;
  1053. }
  1054. /**
  1055. * string padding with multibyte support
  1056. *
  1057. * @link http://www.php.net/str_pad
  1058. * @param string $string original string
  1059. * @param integer $width padded string width
  1060. * @param string $pad padding symbols
  1061. * @param integer $padtype padding type
  1062. * (internal php defines, see str_pad() description)
  1063. * @param string $charset charset used in original string
  1064. * @return string padded string
  1065. */
  1066. function sq_str_pad($string, $width, $pad, $padtype, $charset='') {
  1067. $charset = strtolower($charset);
  1068. $padded_string = '';
  1069. switch ($charset) {
  1070. case 'utf-8':
  1071. case 'big5':
  1072. case 'gb2312':
  1073. case 'euc-kr':
  1074. /*
  1075. * all multibyte charsets try to increase width value by
  1076. * adding difference between number of bytes and real length
  1077. */
  1078. $width = $width - sq_strlen($string,$charset) + strlen($string);
  1079. default:
  1080. $padded_string=str_pad($string,$width,$pad,$padtype);
  1081. }
  1082. return $padded_string;
  1083. }
  1084. $PHP_SELF = php_self();
  1085. ?>