strings.php 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676
  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 1999-2012 The SquirrelMail Project Team
  9. * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  10. * @version $Id$
  11. * @package squirrelmail
  12. */
  13. /**
  14. * Appends citation markers to the string.
  15. * Also appends a trailing space.
  16. *
  17. * @author Justus Pendleton
  18. * @param string $str The string to append to
  19. * @param int $citeLevel the number of markers to append
  20. * @return null
  21. * @since 1.5.1
  22. */
  23. function sqMakeCite (&$str, $citeLevel) {
  24. for ($i = 0; $i < $citeLevel; $i++) {
  25. $str .= '>';
  26. }
  27. if ($citeLevel != 0) {
  28. $str .= ' ';
  29. }
  30. }
  31. /**
  32. * Create a newline in the string, adding citation
  33. * markers to the newline as necessary.
  34. *
  35. * @author Justus Pendleton
  36. * @param string $str the string to make a newline in
  37. * @param int $citeLevel the citation level the newline is at
  38. * @param int $column starting column of the newline
  39. * @return null
  40. * @since 1.5.1
  41. */
  42. function sqMakeNewLine (&$str, $citeLevel, &$column) {
  43. $str .= "\n";
  44. $column = 0;
  45. if ($citeLevel > 0) {
  46. sqMakeCite ($str, $citeLevel);
  47. $column = $citeLevel + 1;
  48. } else {
  49. $column = 0;
  50. }
  51. }
  52. /**
  53. * Checks for spaces in strings - only used if PHP doesn't have native ctype support
  54. *
  55. * You might be able to rewrite the function by adding short evaluation form.
  56. *
  57. * possible problems:
  58. * - iso-2022-xx charsets - hex 20 might be part of other symbol. I might
  59. * be wrong. 0x20 is not used in iso-2022-jp. I haven't checked iso-2022-kr
  60. * and iso-2022-cn mappings.
  61. *
  62. * - no-break space (&nbsp;) - it is 8bit symbol, that depends on charset.
  63. * there are at least three different charset groups that have nbsp in
  64. * different places.
  65. *
  66. * I don't see any charset/nbsp options in php ctype either.
  67. *
  68. * @param string $string tested string
  69. * @return bool true when only whitespace symbols are present in test string
  70. * @since 1.5.1
  71. */
  72. function sm_ctype_space($string) {
  73. if ( preg_match('/^[\x09-\x0D]|^\x20/', $string) || $string=='') {
  74. return true;
  75. } else {
  76. return false;
  77. }
  78. }
  79. /**
  80. * Wraps text at $wrap characters. While sqWordWrap takes
  81. * a single line of text and wraps it, this function works
  82. * on the entire corpus at once, this allows it to be a little
  83. * bit smarter and when and how to wrap.
  84. *
  85. * @author Justus Pendleton
  86. * @param string $body the entire body of text
  87. * @param int $wrap the maximum line length
  88. * @return string the wrapped text
  89. * @since 1.5.1
  90. */
  91. function &sqBodyWrap (&$body, $wrap) {
  92. //check for ctype support, and fake it if it doesn't exist
  93. if (!function_exists('ctype_space')) {
  94. function ctype_space ($string) {
  95. return sm_ctype_space($string);
  96. }
  97. }
  98. // the newly wrapped text
  99. $outString = '';
  100. // current column since the last newline in the outstring
  101. $outStringCol = 0;
  102. $length = sq_strlen($body);
  103. // where we are in the original string
  104. $pos = 0;
  105. // the number of >>> citation markers we are currently at
  106. $citeLevel = 0;
  107. // the main loop, whenever we start a newline of input text
  108. // we start from here
  109. while ($pos < $length) {
  110. // we're at the beginning of a line, get the new cite level
  111. $newCiteLevel = 0;
  112. while (($pos < $length) && (sq_substr($body,$pos,1) == '>')) {
  113. $newCiteLevel++;
  114. $pos++;
  115. // skip over any spaces interleaved among the cite markers
  116. while (($pos < $length) && (sq_substr($body,$pos,1) == ' ')) {
  117. $pos++;
  118. }
  119. if ($pos >= $length) {
  120. break;
  121. }
  122. }
  123. // special case: if this is a blank line then maintain it
  124. // (i.e. try to preserve original paragraph breaks)
  125. // unless they occur at the very beginning of the text
  126. if ((sq_substr($body,$pos,1) == "\n" ) && (sq_strlen($outString) != 0)) {
  127. $outStringLast = $outString{sq_strlen($outString) - 1};
  128. if ($outStringLast != "\n") {
  129. $outString .= "\n";
  130. }
  131. sqMakeCite ($outString, $newCiteLevel);
  132. $outString .= "\n";
  133. $pos++;
  134. $outStringCol = 0;
  135. continue;
  136. }
  137. // if the cite level has changed, then start a new line
  138. // with the new cite level.
  139. if (($citeLevel != $newCiteLevel) && ($pos > ($newCiteLevel + 1)) && ($outStringCol != 0)) {
  140. sqMakeNewLine ($outString, 0, $outStringCol);
  141. }
  142. $citeLevel = $newCiteLevel;
  143. // prepend the quote level if necessary
  144. if ($outStringCol == 0) {
  145. sqMakeCite ($outString, $citeLevel);
  146. // if we added a citation then move the column
  147. // out by citelevel + 1 (the cite markers + the space)
  148. $outStringCol = $citeLevel + ($citeLevel ? 1 : 0);
  149. } else if ($outStringCol > $citeLevel) {
  150. // not a cite and we're not at the beginning of a line
  151. // in the output. add a space to separate the new text
  152. // from previous text.
  153. $outString .= ' ';
  154. $outStringCol++;
  155. }
  156. // find the next newline -- we don't want to go further than that
  157. $nextNewline = sq_strpos ($body, "\n", $pos);
  158. if ($nextNewline === FALSE) {
  159. $nextNewline = $length;
  160. }
  161. // Don't wrap unquoted lines at all. For now the textarea
  162. // will work fine for this. Maybe revisit this later though
  163. // (for completeness more than anything else, I think)
  164. if ($citeLevel == 0) {
  165. $outString .= sq_substr ($body, $pos, ($nextNewline - $pos));
  166. $outStringCol = $nextNewline - $pos;
  167. if ($nextNewline != $length) {
  168. sqMakeNewLine ($outString, 0, $outStringCol);
  169. }
  170. $pos = $nextNewline + 1;
  171. continue;
  172. }
  173. /**
  174. * Set this to false to stop appending short strings to previous lines
  175. */
  176. $smartwrap = true;
  177. // inner loop, (obviously) handles wrapping up to
  178. // the next newline
  179. while ($pos < $nextNewline) {
  180. // skip over initial spaces
  181. while (($pos < $nextNewline) && (ctype_space (sq_substr($body,$pos,1)))) {
  182. $pos++;
  183. }
  184. // if this is a short line then just append it and continue outer loop
  185. if (($outStringCol + $nextNewline - $pos) <= ($wrap - $citeLevel - 1) ) {
  186. // if this is the final line in the input string then include
  187. // any trailing newlines
  188. // echo substr($body,$pos,$wrap). "<br />";
  189. if (($nextNewline + 1 == $length) && (sq_substr($body,$nextNewline,1) == "\n")) {
  190. $nextNewline++;
  191. }
  192. // trim trailing spaces
  193. $lastRealChar = $nextNewline;
  194. while (($lastRealChar > $pos && $lastRealChar < $length) && (ctype_space (sq_substr($body,$lastRealChar,1)))) {
  195. $lastRealChar--;
  196. }
  197. // decide if appending the short string is what we want
  198. if (($nextNewline < $length && sq_substr($body,$nextNewline,1) == "\n") &&
  199. isset($lastRealChar)) {
  200. $mypos = $pos;
  201. //check the first word:
  202. while (($mypos < $length) && (sq_substr($body,$mypos,1) == '>')) {
  203. $mypos++;
  204. // skip over any spaces interleaved among the cite markers
  205. while (($mypos < $length) && (sq_substr($body,$mypos,1) == ' ')) {
  206. $mypos++;
  207. }
  208. }
  209. /*
  210. $ldnspacecnt = 0;
  211. if ($mypos == $nextNewline+1) {
  212. while (($mypos < $length) && ($body{$mypos} == ' ')) {
  213. $ldnspacecnt++;
  214. }
  215. }
  216. */
  217. $firstword = sq_substr($body,$mypos,sq_strpos($body,' ',$mypos) - $mypos);
  218. //if ($dowrap || $ldnspacecnt > 1 || ($firstword && (
  219. if (!$smartwrap || $firstword && (
  220. $firstword{0} == '-' ||
  221. $firstword{0} == '+' ||
  222. $firstword{0} == '*' ||
  223. sq_substr($firstword,0,1) == sq_strtoupper(sq_substr($firstword,0,1)) ||
  224. strpos($firstword,':'))) {
  225. $outString .= sq_substr($body,$pos,($lastRealChar - $pos+1));
  226. $outStringCol += ($lastRealChar - $pos);
  227. sqMakeNewLine($outString,$citeLevel,$outStringCol);
  228. $nextNewline++;
  229. $pos = $nextNewline;
  230. $outStringCol--;
  231. continue;
  232. }
  233. }
  234. $outString .= sq_substr ($body, $pos, ($lastRealChar - $pos + 1));
  235. $outStringCol += ($lastRealChar - $pos);
  236. $pos = $nextNewline + 1;
  237. continue;
  238. }
  239. $eol = $pos + $wrap - $citeLevel - $outStringCol;
  240. // eol is the tentative end of line.
  241. // look backwards for there for a whitespace to break at.
  242. // if it's already less than our current position then
  243. // our current line is already too long, break immediately
  244. // and restart outer loop
  245. if ($eol <= $pos) {
  246. sqMakeNewLine ($outString, $citeLevel, $outStringCol);
  247. continue;
  248. }
  249. // start looking backwards for whitespace to break at.
  250. $breakPoint = $eol;
  251. while (($breakPoint > $pos) && (! ctype_space (sq_substr($body,$breakPoint,1)))) {
  252. $breakPoint--;
  253. }
  254. // if we didn't find a breakpoint by looking backward then we
  255. // need to figure out what to do about that
  256. if ($breakPoint == $pos) {
  257. // if we are not at the beginning then end this line
  258. // and start a new loop
  259. if ($outStringCol > ($citeLevel + 1)) {
  260. sqMakeNewLine ($outString, $citeLevel, $outStringCol);
  261. continue;
  262. } else {
  263. // just hard break here. most likely we are breaking
  264. // a really long URL. could also try searching
  265. // forward for a break point, which is what Mozilla
  266. // does. don't bother for now.
  267. $breakPoint = $eol;
  268. }
  269. }
  270. // special case: maybe we should have wrapped last
  271. // time. if the first breakpoint here makes the
  272. // current line too long and there is already text on
  273. // the current line, break and loop again if at
  274. // beginning of current line, don't force break
  275. $SLOP = 6;
  276. if ((($outStringCol + ($breakPoint - $pos)) > ($wrap + $SLOP)) && ($outStringCol > ($citeLevel + 1))) {
  277. sqMakeNewLine ($outString, $citeLevel, $outStringCol);
  278. continue;
  279. }
  280. // skip newlines or whitespace at the beginning of the string
  281. $substring = sq_substr ($body, $pos, ($breakPoint - $pos));
  282. $substring = rtrim ($substring); // do rtrim and ctype_space have the same ideas about whitespace?
  283. $outString .= $substring;
  284. $outStringCol += sq_strlen ($substring);
  285. // advance past the whitespace which caused the wrap
  286. $pos = $breakPoint;
  287. while (($pos < $length) && (ctype_space (sq_substr($body,$pos,1)))) {
  288. $pos++;
  289. }
  290. if ($pos < $length) {
  291. sqMakeNewLine ($outString, $citeLevel, $outStringCol);
  292. }
  293. }
  294. }
  295. return $outString;
  296. }
  297. /**
  298. * Wraps text at $wrap characters
  299. *
  300. * Has a problem with special HTML characters, so call this before
  301. * you do character translation.
  302. *
  303. * Specifically, &amp;#039; comes up as 5 characters instead of 1.
  304. * This should not add newlines to the end of lines.
  305. *
  306. * @param string $line the line of text to wrap, by ref
  307. * @param int $wrap the maximum line lenth
  308. * @param string $charset name of charset used in $line string. Available since v.1.5.1.
  309. * @return void
  310. * @since 1.0
  311. */
  312. function sqWordWrap(&$line, $wrap, $charset='') {
  313. global $languages, $squirrelmail_language;
  314. // Use custom wrapping function, if translation provides it
  315. if (isset($languages[$squirrelmail_language]['XTRA_CODE']) &&
  316. function_exists($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap')) {
  317. if (mb_detect_encoding($line) != 'ASCII') {
  318. $line = call_user_func($languages[$squirrelmail_language]['XTRA_CODE'] . '_wordwrap', $line, $wrap);
  319. return;
  320. }
  321. }
  322. preg_match('/^([\t >]*)([^\t >].*)?$/', $line, $regs);
  323. $beginning_spaces = $regs[1];
  324. if (isset($regs[2])) {
  325. $words = explode(' ', $regs[2]);
  326. } else {
  327. $words = array();
  328. }
  329. $i = 0;
  330. $line = $beginning_spaces;
  331. while ($i < count($words)) {
  332. /* Force one word to be on a line (minimum) */
  333. $line .= $words[$i];
  334. $line_len = strlen($beginning_spaces) + sq_strlen($words[$i],$charset) + 2;
  335. if (isset($words[$i + 1]))
  336. $line_len += sq_strlen($words[$i + 1],$charset);
  337. $i ++;
  338. /* Add more words (as long as they fit) */
  339. while ($line_len < $wrap && $i < count($words)) {
  340. $line .= ' ' . $words[$i];
  341. $i++;
  342. if (isset($words[$i]))
  343. $line_len += sq_strlen($words[$i],$charset) + 1;
  344. else
  345. $line_len += 1;
  346. }
  347. /* Skip spaces if they are the first thing on a continued line */
  348. while (!isset($words[$i]) && $i < count($words)) {
  349. $i ++;
  350. }
  351. /* Go to the next line if we have more to process */
  352. if ($i < count($words)) {
  353. $line .= "\n";
  354. }
  355. }
  356. }
  357. /**
  358. * Does the opposite of sqWordWrap()
  359. * @param string $body the text to un-wordwrap
  360. * @return void
  361. * @since 1.0
  362. */
  363. function sqUnWordWrap(&$body) {
  364. global $squirrelmail_language;
  365. if ($squirrelmail_language == 'ja_JP') {
  366. return;
  367. }
  368. $lines = explode("\n", $body);
  369. $body = '';
  370. $PreviousSpaces = '';
  371. $cnt = count($lines);
  372. for ($i = 0; $i < $cnt; $i ++) {
  373. preg_match("/^([\t >]*)([^\t >].*)?$/", $lines[$i], $regs);
  374. $CurrentSpaces = $regs[1];
  375. if (isset($regs[2])) {
  376. $CurrentRest = $regs[2];
  377. } else {
  378. $CurrentRest = '';
  379. }
  380. if ($i == 0) {
  381. $PreviousSpaces = $CurrentSpaces;
  382. $body = $lines[$i];
  383. } else if (($PreviousSpaces == $CurrentSpaces) /* Do the beginnings match */
  384. && (strlen($lines[$i - 1]) > 65) /* Over 65 characters long */
  385. && strlen($CurrentRest)) { /* and there's a line to continue with */
  386. $body .= ' ' . $CurrentRest;
  387. } else {
  388. $body .= "\n" . $lines[$i];
  389. $PreviousSpaces = $CurrentSpaces;
  390. }
  391. }
  392. $body .= "\n";
  393. }
  394. /**
  395. * If $haystack is a full mailbox name and $needle is the mailbox
  396. * separator character, returns the last part of the mailbox name.
  397. *
  398. * @param string haystack full mailbox name to search
  399. * @param string needle the mailbox separator character
  400. * @return string the last part of the mailbox name
  401. * @since 1.0
  402. */
  403. function readShortMailboxName($haystack, $needle) {
  404. if ($needle == '') {
  405. $elem = $haystack;
  406. } else {
  407. $parts = explode($needle, $haystack);
  408. $elem = array_pop($parts);
  409. while ($elem == '' && count($parts)) {
  410. $elem = array_pop($parts);
  411. }
  412. }
  413. return( $elem );
  414. }
  415. /**
  416. * get_location
  417. *
  418. * Determines the location to forward to, relative to your server.
  419. * This is used in HTTP Location: redirects.
  420. *
  421. * If set, it uses $config_location_base as the first part of the URL,
  422. * specifically, the protocol, hostname and port parts. The path is
  423. * always autodetected.
  424. *
  425. * @return string the base url for this SquirrelMail installation
  426. * @since 1.0
  427. */
  428. function get_location () {
  429. global $imap_server_type, $config_location_base,
  430. $is_secure_connection, $sq_ignore_http_x_forwarded_headers;
  431. /* Get the path, handle virtual directories */
  432. if(strpos(php_self(), '?')) {
  433. $path = substr(php_self(), 0, strpos(php_self(), '?'));
  434. } else {
  435. $path = php_self();
  436. }
  437. $path = substr($path, 0, strrpos($path, '/'));
  438. // proto+host+port are already set in config:
  439. if ( !empty($config_location_base) ) {
  440. return $config_location_base . $path ;
  441. }
  442. // we computed it before, get it from the session:
  443. if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
  444. return $full_url . $path;
  445. }
  446. // else: autodetect
  447. /* Check if this is a HTTPS or regular HTTP request. */
  448. $proto = 'http://';
  449. if ($is_secure_connection)
  450. $proto = 'https://';
  451. /* Get the hostname from the Host header or server config. */
  452. if ($sq_ignore_http_x_forwarded_headers
  453. || !sqgetGlobalVar('HTTP_X_FORWARDED_HOST', $host, SQ_SERVER)
  454. || empty($host)) {
  455. if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
  456. if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
  457. $host = '';
  458. }
  459. }
  460. }
  461. $port = '';
  462. if (! strstr($host, ':')) {
  463. // Note: HTTP_X_FORWARDED_PROTO could be sent from the client and
  464. // therefore possibly spoofed/hackable. Thus, SquirrelMail
  465. // ignores such headers by default. The administrator
  466. // can tell SM to use such header values by setting
  467. // $sq_ignore_http_x_forwarded_headers to boolean FALSE
  468. // in config/config.php or by using config/conf.pl.
  469. global $sq_ignore_http_x_forwarded_headers;
  470. if ($sq_ignore_http_x_forwarded_headers
  471. || !sqgetGlobalVar('HTTP_X_FORWARDED_PROTO', $forwarded_proto, SQ_SERVER))
  472. $forwarded_proto = '';
  473. if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
  474. if (($server_port != 80 && $proto == 'http://') ||
  475. ($server_port != 443 && $proto == 'https://' &&
  476. strcasecmp($forwarded_proto, 'https') !== 0)) {
  477. $port = sprintf(':%d', $server_port);
  478. }
  479. }
  480. }
  481. /* this is a workaround for the weird macosx caching that
  482. * causes Apache to return 16080 as the port number, which causes
  483. * SM to bail */
  484. if ($imap_server_type == 'macosx' && $port == ':16080') {
  485. $port = '';
  486. }
  487. /* Fallback is to omit the server name and use a relative */
  488. /* URI, although this is not RFC 2616 compliant. */
  489. $full_url = ($host ? $proto . $host . $port : '');
  490. sqsession_register($full_url, 'sq_base_url');
  491. return $full_url . $path;
  492. }
  493. /**
  494. * Get Message List URI
  495. *
  496. * @param string $mailbox Current mailbox name (unencoded/raw)
  497. * @param string $startMessage The mailbox page offset
  498. * @param string $what Any current search parameters (OPTIONAL;
  499. * default empty string)
  500. *
  501. * @return string The message list URI
  502. *
  503. * @since 1.5.2
  504. *
  505. */
  506. function get_message_list_uri($mailbox, $startMessage, $what='') {
  507. global $base_uri;
  508. $urlMailbox = urlencode($mailbox);
  509. $list_xtra = "?where=read_body.php&what=$what&mailbox=" . $urlMailbox.
  510. "&startMessage=$startMessage";
  511. return $base_uri .'src/right_main.php'. $list_xtra;
  512. }
  513. /**
  514. * Encrypts password
  515. *
  516. * These functions are used to encrypt the password before it is
  517. * stored in a cookie. The encryption key is generated by
  518. * OneTimePadCreate();
  519. *
  520. * @param string $string the (password)string to encrypt
  521. * @param string $epad the encryption key
  522. * @return string the base64-encoded encrypted password
  523. * @since 1.0
  524. */
  525. function OneTimePadEncrypt ($string, $epad) {
  526. $pad = base64_decode($epad);
  527. if (strlen($pad)>0) {
  528. // make sure that pad is longer than string
  529. while (strlen($string)>strlen($pad)) {
  530. $pad.=$pad;
  531. }
  532. } else {
  533. // FIXME: what should we do when $epad is not base64 encoded or empty.
  534. }
  535. $encrypted = '';
  536. for ($i = 0; $i < strlen ($string); $i++) {
  537. $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
  538. }
  539. return base64_encode($encrypted);
  540. }
  541. /**
  542. * Decrypts a password from the cookie
  543. *
  544. * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
  545. * This uses the encryption key that is stored in the session.
  546. *
  547. * @param string $string the string to decrypt
  548. * @param string $epad the encryption key from the session
  549. * @return string the decrypted password
  550. * @since 1.0
  551. */
  552. function OneTimePadDecrypt ($string, $epad) {
  553. $pad = base64_decode($epad);
  554. if (strlen($pad)>0) {
  555. // make sure that pad is longer than string
  556. while (strlen($string)>strlen($pad)) {
  557. $pad.=$pad;
  558. }
  559. } else {
  560. // FIXME: what should we do when $epad is not base64 encoded or empty.
  561. }
  562. $encrypted = base64_decode ($string);
  563. $decrypted = '';
  564. for ($i = 0; $i < strlen ($encrypted); $i++) {
  565. $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
  566. }
  567. return $decrypted;
  568. }
  569. /**
  570. * Creates encryption key
  571. *
  572. * Creates an encryption key for encrypting the password stored in the cookie.
  573. * The encryption key itself is stored in the session.
  574. *
  575. * Pad must be longer or equal to encoded string length in 1.4.4/1.5.0 and older.
  576. * @param int $length optional, length of the string to generate
  577. * @return string the encryption key
  578. * @since 1.0
  579. */
  580. function OneTimePadCreate ($length=100) {
  581. $pad = '';
  582. for ($i = 0; $i < $length; $i++) {
  583. $pad .= chr(mt_rand(0,255));
  584. }
  585. return base64_encode($pad);
  586. }
  587. /**
  588. * Returns a string showing a byte size figure in
  589. * a more easily digested (readable) format
  590. *
  591. * @param int $bytes the size in bytes
  592. *
  593. * @return string The size in human readable format
  594. *
  595. * @since 1.0
  596. *
  597. */
  598. function show_readable_size($bytes) {
  599. $bytes /= 1024;
  600. $type = _("KiB");
  601. if ($bytes / 1024 > 1) {
  602. $bytes /= 1024;
  603. $type = _("MiB");
  604. }
  605. if ($bytes < 10) {
  606. $bytes *= 10;
  607. settype($bytes, 'integer');
  608. $bytes /= 10;
  609. } else {
  610. settype($bytes, 'integer');
  611. }
  612. global $nbsp;
  613. return $bytes . $nbsp . $type;
  614. }
  615. /**
  616. * Generates a random string from the character set you pass in
  617. *
  618. * @param int $size the length of the string to generate
  619. * @param string $chars a string containing the characters to use
  620. * @param int $flags a flag to add a specific set to the characters to use:
  621. * Flags:
  622. * 1 = add lowercase a-z to $chars
  623. * 2 = add uppercase A-Z to $chars
  624. * 4 = add numbers 0-9 to $chars
  625. * @return string the random string
  626. * @since 1.0
  627. */
  628. function GenerateRandomString($size, $chars, $flags = 0) {
  629. if ($flags & 0x1) {
  630. $chars .= 'abcdefghijklmnopqrstuvwxyz';
  631. }
  632. if ($flags & 0x2) {
  633. $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  634. }
  635. if ($flags & 0x4) {
  636. $chars .= '0123456789';
  637. }
  638. if (($size < 1) || (strlen($chars) < 1)) {
  639. return '';
  640. }
  641. $String = '';
  642. $j = strlen( $chars ) - 1;
  643. while (strlen($String) < $size) {
  644. $String .= $chars{mt_rand(0, $j)};
  645. }
  646. return $String;
  647. }
  648. /**
  649. * Escapes special characters for use in IMAP commands.
  650. *
  651. * @param string $str the string to escape
  652. * @return string the escaped string
  653. * @since 1.0.3
  654. */
  655. function quoteimap($str) {
  656. return str_replace(array('\\', '"'), array('\\\\', '\\"'), $str);
  657. }
  658. /**
  659. * Create compose link
  660. *
  661. * Returns a link to the compose-page, taking in consideration
  662. * the compose_in_new and javascript settings.
  663. *
  664. * @param string $url The URL to the compose page
  665. * @param string $text The link text, default "Compose"
  666. * @param string $target URL target, if any (since 1.4.3)
  667. * @param string $accesskey The access key to be used, if any
  668. *
  669. * @return string a link to the compose page
  670. *
  671. * @since 1.4.2
  672. */
  673. function makeComposeLink($url, $text = null, $target='', $accesskey='NONE') {
  674. global $compose_new_win, $compose_width,
  675. $compose_height, $oTemplate;
  676. if(!$text) {
  677. $text = _("Compose");
  678. }
  679. // if not using "compose in new window", make
  680. // regular link and be done with it
  681. if($compose_new_win != '1') {
  682. return makeInternalLink($url, $text, $target, $accesskey);
  683. }
  684. // build the compose in new window link...
  685. // if javascript is on, use onclick event to handle it
  686. if(checkForJavascript()) {
  687. sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
  688. $compuri = SM_BASE_URI.$url;
  689. return create_hyperlink('javascript:void(0)', $text, '',
  690. "comp_in_new('$compuri','$compose_width','$compose_height')",
  691. '', '', '',
  692. ($accesskey == 'NONE'
  693. ? array()
  694. : array('accesskey' => $accesskey)));
  695. }
  696. // otherwise, just open new window using regular HTML
  697. return makeInternalLink($url, $text, '_blank', $accesskey);
  698. }
  699. /**
  700. * version of fwrite which checks for failure
  701. * @param resource $fp
  702. * @param string $string
  703. * @return number of written bytes. false on failure
  704. * @since 1.4.3
  705. */
  706. function sq_fwrite($fp, $string) {
  707. // write to file
  708. $count = @fwrite($fp,$string);
  709. // the number of bytes written should be the length of the string
  710. if($count != strlen($string)) {
  711. return FALSE;
  712. }
  713. return $count;
  714. }
  715. /**
  716. * sq_get_html_translation_table
  717. *
  718. * Returns the translation table used by sq_htmlentities()
  719. *
  720. * @param integer $table html translation table. Possible values (without quotes):
  721. * <ul>
  722. * <li>HTML_ENTITIES - full html entities table defined by charset</li>
  723. * <li>HTML_SPECIALCHARS - html special characters table</li>
  724. * </ul>
  725. * @param integer $quote_style quote encoding style. Possible values (without quotes):
  726. * <ul>
  727. * <li>ENT_COMPAT - (default) encode double quotes</li>
  728. * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
  729. * <li>ENT_QUOTES - encode double and single quotes</li>
  730. * </ul>
  731. * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
  732. * @return array html translation array
  733. * @since 1.5.1
  734. */
  735. function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT,$charset='us-ascii') {
  736. global $default_charset;
  737. if ($table == HTML_SPECIALCHARS) $charset='us-ascii';
  738. // Start array with ampersand
  739. $sq_html_ent_table = array( "&" => '&amp;' );
  740. // < and >
  741. $sq_html_ent_table = array_merge($sq_html_ent_table,
  742. array("<" => '&lt;',
  743. ">" => '&gt;')
  744. );
  745. // double quotes
  746. if ($quote_style == ENT_COMPAT)
  747. $sq_html_ent_table = array_merge($sq_html_ent_table,
  748. array("\"" => '&quot;')
  749. );
  750. // double and single quotes
  751. if ($quote_style == ENT_QUOTES)
  752. $sq_html_ent_table = array_merge($sq_html_ent_table,
  753. array("\"" => '&quot;',
  754. "'" => '&#39;')
  755. );
  756. if ($charset=='auto') $charset=$default_charset;
  757. // add entities that depend on charset
  758. switch($charset){
  759. case 'iso-8859-1':
  760. include_once(SM_PATH . 'functions/htmlentities/iso-8859-1.php');
  761. break;
  762. case 'utf-8':
  763. include_once(SM_PATH . 'functions/htmlentities/utf-8.php');
  764. break;
  765. case 'us-ascii':
  766. default:
  767. break;
  768. }
  769. // return table
  770. return $sq_html_ent_table;
  771. }
  772. /**
  773. * sq_htmlentities
  774. *
  775. * Convert all applicable characters to HTML entities.
  776. * Minimal php requirement - v.4.0.5.
  777. *
  778. * Function is designed for people that want to use full power of htmlentities() in
  779. * i18n environment.
  780. *
  781. * @param string $string string that has to be sanitized
  782. * @param integer $quote_style quote encoding style. Possible values (without quotes):
  783. * <ul>
  784. * <li>ENT_COMPAT - (default) encode double quotes</li>
  785. * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
  786. * <li>ENT_QUOTES - encode double and single quotes</li>
  787. * </ul>
  788. * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
  789. * @return string sanitized string
  790. * @since 1.5.1
  791. */
  792. function sq_htmlentities($string,$quote_style=ENT_COMPAT,$charset='us-ascii') {
  793. // get translation table
  794. $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES,$quote_style,$charset);
  795. // convert characters
  796. return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
  797. }
  798. /**
  799. * Tests if string contains 8bit symbols.
  800. *
  801. * If charset is not set, function defaults to default_charset.
  802. * $default_charset global must be set correctly if $charset is
  803. * not used.
  804. * @param string $string tested string
  805. * @param string $charset charset used in a string
  806. * @return bool true if 8bit symbols are detected
  807. * @since 1.5.1 and 1.4.4
  808. */
  809. function sq_is8bit($string,$charset='') {
  810. global $default_charset;
  811. if ($charset=='') $charset=$default_charset;
  812. /**
  813. * Don't use \240 in ranges. Sometimes RH 7.2 doesn't like it.
  814. * Don't use \200-\237 for iso-8859-x charsets. This range
  815. * stores control symbols in those charsets.
  816. * Use preg_match instead of ereg in order to avoid problems
  817. * with mbstring overloading
  818. */
  819. if (preg_match("/^iso-8859/i",$charset)) {
  820. $needle='/\240|[\241-\377]/';
  821. } else {
  822. $needle='/[\200-\237]|\240|[\241-\377]/';
  823. }
  824. return preg_match("$needle",$string);
  825. }
  826. /**
  827. * Replacement of mb_list_encodings function
  828. *
  829. * This function provides replacement for function that is available only
  830. * in php 5.x. Function does not test all mbstring encodings. Only the ones
  831. * that might be used in SM translations.
  832. *
  833. * Supported strings are stored in session in order to reduce number of
  834. * mb_internal_encoding function calls.
  835. *
  836. * If you want to test all mbstring encodings - fill $list_of_encodings
  837. * array.
  838. * @return array list of encodings supported by php mbstring extension
  839. * @since 1.5.1 and 1.4.6
  840. */
  841. function sq_mb_list_encodings() {
  842. if (! function_exists('mb_internal_encoding'))
  843. return array();
  844. // php 5+ function
  845. if (function_exists('mb_list_encodings')) {
  846. $ret = mb_list_encodings();
  847. array_walk($ret,'sq_lowercase_array_vals');
  848. return $ret;
  849. }
  850. // don't try to test encodings, if they are already stored in session
  851. if (sqgetGlobalVar('mb_supported_encodings',$mb_supported_encodings,SQ_SESSION))
  852. return $mb_supported_encodings;
  853. // save original encoding
  854. $orig_encoding=mb_internal_encoding();
  855. $list_of_encoding=array(
  856. 'pass',
  857. 'auto',
  858. 'ascii',
  859. 'jis',
  860. 'utf-8',
  861. 'sjis',
  862. 'euc-jp',
  863. 'iso-8859-1',
  864. 'iso-8859-2',
  865. 'iso-8859-7',
  866. 'iso-8859-9',
  867. 'iso-8859-15',
  868. 'koi8-r',
  869. 'koi8-u',
  870. 'big5',
  871. 'gb2312',
  872. 'gb18030',
  873. 'windows-1251',
  874. 'windows-1255',
  875. 'windows-1256',
  876. 'tis-620',
  877. 'iso-2022-jp',
  878. 'euc-cn',
  879. 'euc-kr',
  880. 'euc-tw',
  881. 'uhc',
  882. 'utf7-imap');
  883. $supported_encodings=array();
  884. foreach ($list_of_encoding as $encoding) {
  885. // try setting encodings. suppress warning messages
  886. if (@mb_internal_encoding($encoding))
  887. $supported_encodings[]=$encoding;
  888. }
  889. // restore original encoding
  890. mb_internal_encoding($orig_encoding);
  891. // register list in session
  892. sqsession_register($supported_encodings,'mb_supported_encodings');
  893. return $supported_encodings;
  894. }
  895. /**
  896. * Callback function used to lowercase array values.
  897. * @param string $val array value
  898. * @param mixed $key array key
  899. * @since 1.5.1 and 1.4.6
  900. */
  901. function sq_lowercase_array_vals(&$val,$key) {
  902. $val = strtolower($val);
  903. }
  904. /**
  905. * Function returns number of characters in string.
  906. *
  907. * Returned number might be different from number of bytes in string,
  908. * if $charset is multibyte charset. Detection depends on mbstring
  909. * functions. If mbstring does not support tested multibyte charset,
  910. * vanilla string length function is used.
  911. * @param string $str string
  912. * @param string $charset charset
  913. * @since 1.5.1 and 1.4.6
  914. * @return integer number of characters in string
  915. */
  916. function sq_strlen($str, $charset=null){
  917. // default option
  918. if (is_null($charset)) return strlen($str);
  919. // lowercase charset name
  920. $charset=strtolower($charset);
  921. // use automatic charset detection, if function call asks for it
  922. if ($charset=='auto') {
  923. global $default_charset, $squirrelmail_language;
  924. set_my_charset();
  925. $charset=$default_charset;
  926. if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
  927. }
  928. // Use mbstring only with listed charsets
  929. $aList_of_mb_charsets=array('utf-8','big5','gb2312','gb18030','euc-jp','euc-cn','euc-tw','euc-kr');
  930. // calculate string length according to charset
  931. if (in_array($charset,$aList_of_mb_charsets) && in_array($charset,sq_mb_list_encodings())) {
  932. $real_length = mb_strlen($str,$charset);
  933. } else {
  934. // own strlen detection code is removed because missing strpos,
  935. // strtoupper and substr implementations break string wrapping.
  936. $real_length=strlen($str);
  937. }
  938. return $real_length;
  939. }
  940. /**
  941. * string padding with multibyte support
  942. *
  943. * @link http://www.php.net/str_pad
  944. * @param string $string original string
  945. * @param integer $width padded string width
  946. * @param string $pad padding symbols
  947. * @param integer $padtype padding type
  948. * (internal php defines, see str_pad() description)
  949. * @param string $charset charset used in original string
  950. * @return string padded string
  951. */
  952. function sq_str_pad($string, $width, $pad, $padtype, $charset='') {
  953. $charset = strtolower($charset);
  954. $padded_string = '';
  955. switch ($charset) {
  956. case 'utf-8':
  957. case 'big5':
  958. case 'gb2312':
  959. case 'euc-kr':
  960. /*
  961. * all multibyte charsets try to increase width value by
  962. * adding difference between number of bytes and real length
  963. */
  964. $width = $width - sq_strlen($string,$charset) + strlen($string);
  965. default:
  966. $padded_string=str_pad($string,$width,$pad,$padtype);
  967. }
  968. return $padded_string;
  969. }
  970. /**
  971. * Wrapper that is used to switch between vanilla and multibyte substr
  972. * functions.
  973. * @param string $string
  974. * @param integer $start
  975. * @param integer $length
  976. * @param string $charset
  977. * @return string
  978. * @since 1.5.1
  979. * @link http://www.php.net/substr
  980. * @link http://www.php.net/mb_substr
  981. */
  982. function sq_substr($string,$start,$length=NULL,$charset='auto') {
  983. // if $length is NULL, use the full string length...
  984. // we have to do this to mimick the use of substr()
  985. // where $length is not given
  986. //
  987. if (is_null($length))
  988. $length = sq_strlen($length);
  989. // use automatic charset detection, if function call asks for it
  990. static $charset_auto, $bUse_mb;
  991. if ($charset=='auto') {
  992. if (!isset($charset_auto)) {
  993. global $default_charset, $squirrelmail_language;
  994. set_my_charset();
  995. $charset=$default_charset;
  996. if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
  997. $charset_auto = $charset;
  998. } else {
  999. $charset = $charset_auto;
  1000. }
  1001. }
  1002. $charset = strtolower($charset);
  1003. // in_array call is expensive => do it once and use a static var for
  1004. // storing the results
  1005. if (!isset($bUse_mb)) {
  1006. if (in_array($charset,sq_mb_list_encodings())) {
  1007. $bUse_mb = true;
  1008. } else {
  1009. $bUse_mb = false;
  1010. }
  1011. }
  1012. if ($bUse_mb) {
  1013. return mb_substr($string,$start,$length,$charset);
  1014. }
  1015. // TODO: add mbstring independent code
  1016. // use vanilla string functions as last option
  1017. return substr($string,$start,$length);
  1018. }
  1019. /**
  1020. * This is a replacement for PHP's substr_replace() that is
  1021. * multibyte-aware.
  1022. *
  1023. * @param string $string The string to operate upon
  1024. * @param string $replacement The string to be inserted
  1025. * @param int $start The offset at which to begin substring replacement
  1026. * @param int $length The number of characters after $start to remove
  1027. * NOTE that if you need to specify a charset but
  1028. * want to achieve normal substr_replace() behavior
  1029. * where $length is not specified, use NULL (OPTIONAL;
  1030. * default from $start to end of string)
  1031. * @param string $charset The charset of the given string. A value of NULL
  1032. * here will force the use of PHP's standard substr().
  1033. * (OPTIONAL; default is "auto", which indicates that
  1034. * the user's current charset should be used).
  1035. *
  1036. * @return string The manipulated string
  1037. *
  1038. * Of course, you can use more advanced (e.g., negative) values
  1039. * for $start and $length as needed - see the PHP manual for more
  1040. * information: http://www.php.net/manual/function.substr-replace.php
  1041. *
  1042. */
  1043. function sq_substr_replace($string, $replacement, $start, $length=NULL,
  1044. $charset='auto')
  1045. {
  1046. // NULL charset? Just use substr_replace()
  1047. //
  1048. if (is_null($charset))
  1049. return is_null($length) ? substr_replace($string, $replacement, $start)
  1050. : substr_replace($string, $replacement, $start, $length);
  1051. // use current character set?
  1052. //
  1053. if ($charset == 'auto')
  1054. {
  1055. //FIXME: is there any reason why this cannot be a global flag used by all string wrapper functions?
  1056. static $auto_charset;
  1057. if (!isset($auto_charset))
  1058. {
  1059. global $default_charset;
  1060. //FIXME - do we need this?
  1061. global $squirrelmail_language;
  1062. set_my_charset();
  1063. $auto_charset = $default_charset;
  1064. //FIXME - do we need this?
  1065. if ($squirrelmail_language == 'ja_JP') $auto_charset = 'euc-jp';
  1066. }
  1067. $charset = $auto_charset;
  1068. }
  1069. // standardize character set name
  1070. //
  1071. $charset = strtolower($charset);
  1072. /* ===== FIXME: this list is not used in 1.5.x, but if we need it, unless this differs between all our string function wrappers, we should store this info in the session
  1073. // only use mbstring with the following character sets
  1074. //
  1075. $sq_substr_replace_mb_charsets = array(
  1076. 'utf-8',
  1077. 'big5',
  1078. 'gb2312',
  1079. 'gb18030',
  1080. 'euc-jp',
  1081. 'euc-cn',
  1082. 'euc-tw',
  1083. 'euc-kr'
  1084. );
  1085. // now we can use our own implementation using
  1086. // mb_substr() and mb_strlen() if needed
  1087. //
  1088. if (in_array($charset, $sq_substr_replace_mb_charsets)
  1089. && in_array($charset, sq_mb_list_encodings()))
  1090. ===== */
  1091. //FIXME: is there any reason why this cannot be a global array used by all string wrapper functions?
  1092. if (in_array($charset, sq_mb_list_encodings()))
  1093. {
  1094. $string_length = mb_strlen($string, $charset);
  1095. if ($start < 0)
  1096. $start = max(0, $string_length + $start);
  1097. else if ($start > $string_length)
  1098. $start = $string_length;
  1099. if ($length < 0)
  1100. $length = max(0, $string_length - $start + $length);
  1101. else if (is_null($length) || $length > $string_length)
  1102. $length = $string_length;
  1103. if ($start + $length > $string_length)
  1104. $length = $string_length - $start;
  1105. return mb_substr($string, 0, $start, $charset)
  1106. . $replacement
  1107. . mb_substr($string,
  1108. $start + $length,
  1109. $string_length, // FIXME: I can't see why this is needed: - $start - $length,
  1110. $charset);
  1111. }
  1112. // else use normal substr_replace()
  1113. //
  1114. return is_null($length) ? substr_replace($string, $replacement, $start)
  1115. : substr_replace($string, $replacement, $start, $length);
  1116. }
  1117. /**
  1118. * Wrapper that is used to switch between vanilla and multibyte strpos
  1119. * functions.
  1120. * @param string $haystack
  1121. * @param mixed $needle
  1122. * @param integer $offset
  1123. * @param string $charset
  1124. * @return string
  1125. * @since 1.5.1
  1126. * @link http://www.php.net/strpos
  1127. * @link http://www.php.net/mb_strpos
  1128. */
  1129. function sq_strpos($haystack,$needle,$offset,$charset='auto') {
  1130. // use automatic charset detection, if function call asks for it
  1131. static $charset_auto, $bUse_mb;
  1132. if ($charset=='auto') {
  1133. if (!isset($charset_auto)) {
  1134. global $default_charset, $squirrelmail_language;
  1135. set_my_charset();
  1136. $charset=$default_charset;
  1137. if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
  1138. $charset_auto = $charset;
  1139. } else {
  1140. $charset = $charset_auto;
  1141. }
  1142. }
  1143. $charset = strtolower($charset);
  1144. // in_array call is expensive => do it once and use a static var for
  1145. // storing the results
  1146. if (!isset($bUse_mb)) {
  1147. if (in_array($charset,sq_mb_list_encodings())) {
  1148. $bUse_mb = true;
  1149. } else {
  1150. $bUse_mb = false;
  1151. }
  1152. }
  1153. if ($bUse_mb) {
  1154. return mb_strpos($haystack,$needle,$offset,$charset);
  1155. }
  1156. // TODO: add mbstring independent code
  1157. // use vanilla string functions as last option
  1158. return strpos($haystack,$needle,$offset);
  1159. }
  1160. /**
  1161. * Wrapper that is used to switch between vanilla and multibyte strtoupper
  1162. * functions.
  1163. * @param string $string
  1164. * @param string $charset
  1165. * @return string
  1166. * @since 1.5.1
  1167. * @link http://www.php.net/strtoupper
  1168. * @link http://www.php.net/mb_strtoupper
  1169. */
  1170. function sq_strtoupper($string,$charset='auto') {
  1171. // use automatic charset detection, if function call asks for it
  1172. static $charset_auto, $bUse_mb;
  1173. if ($charset=='auto') {
  1174. if (!isset($charset_auto)) {
  1175. global $default_charset, $squirrelmail_language;
  1176. set_my_charset();
  1177. $charset=$default_charset;
  1178. if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
  1179. $charset_auto = $charset;
  1180. } else {
  1181. $charset = $charset_auto;
  1182. }
  1183. }
  1184. $charset = strtolower($charset);
  1185. // in_array call is expensive => do it once and use a static var for
  1186. // storing the results
  1187. if (!isset($bUse_mb)) {
  1188. if (function_exists('mb_strtoupper') &&
  1189. in_array($charset,sq_mb_list_encodings())) {
  1190. $bUse_mb = true;
  1191. } else {
  1192. $bUse_mb = false;
  1193. }
  1194. }
  1195. if ($bUse_mb) {
  1196. return mb_strtoupper($string,$charset);
  1197. }
  1198. // TODO: add mbstring independent code
  1199. // use vanilla string functions as last option
  1200. return strtoupper($string);
  1201. }
  1202. /**
  1203. * Counts 8bit bytes in string
  1204. * @param string $string tested string
  1205. * @return integer number of 8bit bytes
  1206. */
  1207. function sq_count8bit($string) {
  1208. $count=0;
  1209. for ($i=0; $i<strlen($string); $i++) {
  1210. if (ord($string[$i]) > 127) $count++;
  1211. }
  1212. return $count;
  1213. }
  1214. /**
  1215. * Callback function to trim whitespace from a value, to be used in array_walk
  1216. * @param string $value value to trim
  1217. * @since 1.5.2 and 1.4.7
  1218. */
  1219. function sq_trim_value ( &$value ) {
  1220. $value = trim($value);
  1221. }
  1222. /**
  1223. * Truncates the given string so that it has at
  1224. * most $max_chars characters. NOTE that a "character"
  1225. * may be a multibyte character, or (optionally), an
  1226. * HTML entity , so this function is different than
  1227. * using substr() or mb_substr().
  1228. *
  1229. * NOTE that if $elipses is given and used, the returned
  1230. * number of characters will be $max_chars PLUS the
  1231. * length of $elipses
  1232. *
  1233. * @param string $string The string to truncate
  1234. * @param int $max_chars The maximum allowable characters
  1235. * @param string $elipses A string that will be added to
  1236. * the end of the truncated string
  1237. * (ONLY if it is truncated) (OPTIONAL;
  1238. * default not used)
  1239. * @param boolean $html_entities_as_chars Whether or not to keep
  1240. * HTML entities together
  1241. * (OPTIONAL; default ignore
  1242. * HTML entities)
  1243. *
  1244. * @return string The truncated string
  1245. *
  1246. * @since 1.4.20 and 1.5.2 (replaced truncateWithEntities())
  1247. *
  1248. */
  1249. function sm_truncate_string($string, $max_chars, $elipses='',
  1250. $html_entities_as_chars=FALSE)
  1251. {
  1252. // if the length of the string is less than
  1253. // the allowable number of characters, just
  1254. // return it as is (even if it contains any
  1255. // HTML entities, that would just make the
  1256. // actual length even smaller)
  1257. //
  1258. $actual_strlen = sq_strlen($string, 'auto');
  1259. if ($max_chars <= 0 || $actual_strlen <= $max_chars)
  1260. return $string;
  1261. // if needed, count the number of HTML entities in
  1262. // the string up to the maximum character limit,
  1263. // pushing that limit up for each entity found
  1264. //
  1265. $adjusted_max_chars = $max_chars;
  1266. if ($html_entities_as_chars)
  1267. {
  1268. // $loop_count is needed to prevent an endless loop
  1269. // which is caused by buggy mbstring versions that
  1270. // return 0 (zero) instead of FALSE in some rare
  1271. // cases. Thanks, PHP.
  1272. // see: http://bugs.php.net/bug.php?id=52731
  1273. // also: tracker $3053349
  1274. //
  1275. $loop_count = 0;
  1276. $entity_pos = $entity_end_pos = -1;
  1277. while ($entity_end_pos + 1 < $actual_strlen
  1278. && ($entity_pos = sq_strpos($string, '&', $entity_end_pos + 1)) !== FALSE
  1279. && ($entity_end_pos = sq_strpos($string, ';', $entity_pos)) !== FALSE
  1280. && $entity_pos <= $adjusted_max_chars
  1281. && $loop_count++ < $max_chars)
  1282. {
  1283. $adjusted_max_chars += $entity_end_pos - $entity_pos;
  1284. }
  1285. // this isn't necessary because sq_substr() would figure this
  1286. // out anyway, but we can avoid a sq_substr() call and we
  1287. // know that we don't have to add an elipses (this is now
  1288. // an accurate comparison, since $adjusted_max_chars, like
  1289. // $actual_strlen, does not take into account HTML entities)
  1290. //
  1291. if ($actual_strlen <= $adjusted_max_chars)
  1292. return $string;
  1293. }
  1294. // get the truncated string
  1295. //
  1296. $truncated_string = sq_substr($string, 0, $adjusted_max_chars);
  1297. // return with added elipses
  1298. //
  1299. return $truncated_string . $elipses;
  1300. }
  1301. /**
  1302. * Gathers the list of secuirty tokens currently
  1303. * stored in the user's preferences and optionally
  1304. * purges old ones from the list.
  1305. *
  1306. * @param boolean $purge_old Indicates if old tokens
  1307. * should be purged from the
  1308. * list ("old" is 2 days or
  1309. * older unless the administrator
  1310. * overrides that value using
  1311. * $max_token_age_days in
  1312. * config/config_local.php)
  1313. * (OPTIONAL; default is to always
  1314. * purge old tokens)
  1315. *
  1316. * @return array The list of tokens
  1317. *
  1318. * @since 1.4.19 and 1.5.2
  1319. *
  1320. */
  1321. function sm_get_user_security_tokens($purge_old=TRUE)
  1322. {
  1323. global $data_dir, $username, $max_token_age_days;
  1324. $tokens = getPref($data_dir, $username, 'security_tokens', '');
  1325. if (($tokens = unserialize($tokens)) === FALSE || !is_array($tokens))
  1326. $tokens = array();
  1327. // purge old tokens if necessary
  1328. //
  1329. if ($purge_old)
  1330. {
  1331. if (empty($max_token_age_days)) $max_token_age_days = 2;
  1332. $now = time();
  1333. $discard_token_date = $now - ($max_token_age_days * 86400);
  1334. $cleaned_tokens = array();
  1335. foreach ($tokens as $token => $timestamp)
  1336. if ($timestamp >= $discard_token_date)
  1337. $cleaned_tokens[$token] = $timestamp;
  1338. $tokens = $cleaned_tokens;
  1339. }
  1340. return $tokens;
  1341. }
  1342. /**
  1343. * Generates a security token that is then stored in
  1344. * the user's preferences with a timestamp for later
  1345. * verification/use.
  1346. *
  1347. * NOTE: The administrator can force SquirrelMail to generate
  1348. * a new token every time one is requested (which may increase
  1349. * obscurity through token randomness at the cost of some
  1350. * performance) by adding the following to
  1351. * config/config_local.php: $do_not_use_single_token = TRUE;
  1352. * Otherwise, only one token will be generated per user which
  1353. * will change only after it expires or is used outside of the
  1354. * validity period specified when calling sm_validate_security_token()
  1355. *
  1356. * WARNING: If the administrator has turned the token system
  1357. * off by setting $disable_security_tokens to TRUE in
  1358. * config/config.php or the configuration tool, this
  1359. * function will not store tokens in the user
  1360. * preferences (but it will still generate and return
  1361. * a random string).
  1362. *
  1363. * @param boolean $force_generate_new When TRUE, a new token will
  1364. * always be created even if current
  1365. * configuration dictates otherwise
  1366. * (OPTIONAL; default FALSE)
  1367. *
  1368. * @return string A security token
  1369. *
  1370. * @since 1.4.19 and 1.5.2
  1371. *
  1372. */
  1373. function sm_generate_security_token($force_generate_new=FALSE)
  1374. {
  1375. global $data_dir, $username, $disable_security_tokens, $do_not_use_single_token;
  1376. $max_generation_tries = 1000;
  1377. $tokens = sm_get_user_security_tokens();
  1378. if (!$force_generate_new && !$do_not_use_single_token && !empty($tokens))
  1379. return key($tokens);
  1380. $new_token = GenerateRandomString(12, '', 7);
  1381. $count = 0;
  1382. while (isset($tokens[$new_token]))
  1383. {
  1384. $new_token = GenerateRandomString(12, '', 7);
  1385. if (++$count > $max_generation_tries)
  1386. {
  1387. logout_error(_("Fatal token generation error; please contact your system administrator or the SquirrelMail Team"));
  1388. exit;
  1389. }
  1390. }
  1391. // is the token system enabled? CAREFUL!
  1392. //
  1393. if (!$disable_security_tokens)
  1394. {
  1395. $tokens[$new_token] = time();
  1396. setPref($data_dir, $username, 'security_tokens', serialize($tokens));
  1397. }
  1398. return $new_token;
  1399. }
  1400. /**
  1401. * Validates a given security token and optionally remove it
  1402. * from the user's preferences if it was valid. If the token
  1403. * is too old but otherwise valid, it will still be rejected.
  1404. *
  1405. * "Too old" is 2 days or older unless the administrator
  1406. * overrides that value using $max_token_age_days in
  1407. * config/config_local.php
  1408. *
  1409. * WARNING: If the administrator has turned the token system
  1410. * off by setting $disable_security_tokens to TRUE in
  1411. * config/config.php or the configuration tool, this
  1412. * function will always return TRUE.
  1413. *
  1414. * @param string $token The token to validate
  1415. * @param int $validity_period The number of seconds tokens are valid
  1416. * for (set to zero to remove valid tokens
  1417. * after only one use; use 3600 to allow
  1418. * tokens to be reused for an hour)
  1419. * (OPTIONAL; default is to only allow tokens
  1420. * to be used once)
  1421. * NOTE this is unrelated to $max_token_age_days
  1422. * or rather is an additional time constraint on
  1423. * tokens that allows them to be re-used (or not)
  1424. * within a more narrow timeframe
  1425. * @param boolean $show_error Indicates that if the token is not
  1426. * valid, this function should display
  1427. * a generic error, log the user out
  1428. * and exit - this function will never
  1429. * return in that case.
  1430. * (OPTIONAL; default FALSE)
  1431. *
  1432. * @return boolean TRUE if the token validated; FALSE otherwise
  1433. *
  1434. * @since 1.4.19 and 1.5.2
  1435. *
  1436. */
  1437. function sm_validate_security_token($token, $validity_period=0, $show_error=FALSE)
  1438. {
  1439. global $data_dir, $username, $max_token_age_days,
  1440. $disable_security_tokens;
  1441. // bypass token validation? CAREFUL!
  1442. //
  1443. if ($disable_security_tokens) return TRUE;
  1444. // don't purge old tokens here because we already
  1445. // do it when generating tokens
  1446. //
  1447. $tokens = sm_get_user_security_tokens(FALSE);
  1448. // token not found?
  1449. //
  1450. if (empty($tokens[$token]))
  1451. {
  1452. if (!$show_error) return FALSE;
  1453. logout_error(_("This page request could not be verified and appears to have expired."));
  1454. exit;
  1455. }
  1456. $now = time();
  1457. $timestamp = $tokens[$token];
  1458. // whether valid or not, we want to remove it from
  1459. // user prefs if it's old enough
  1460. //
  1461. if ($timestamp < $now - $validity_period)
  1462. {
  1463. unset($tokens[$token]);
  1464. setPref($data_dir, $username, 'security_tokens', serialize($tokens));
  1465. }
  1466. // reject tokens that are too old
  1467. //
  1468. if (empty($max_token_age_days)) $max_token_age_days = 2;
  1469. $old_token_date = $now - ($max_token_age_days * 86400);
  1470. if ($timestamp < $old_token_date)
  1471. {
  1472. if (!$show_error) return FALSE;
  1473. logout_error(_("The current page request appears to have originated from an untrusted source."));
  1474. exit;
  1475. }
  1476. // token OK!
  1477. //
  1478. return TRUE;
  1479. }