strings.php 39 KB

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