strings.php 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862
  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-2025 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. $path = substr(php_self(FALSE), 0, strrpos(php_self(FALSE), '/'));
  433. // proto+host+port are already set in config:
  434. if ( !empty($config_location_base) ) {
  435. return $config_location_base . $path ;
  436. }
  437. // we computed it before, get it from the session:
  438. if ( sqgetGlobalVar('sq_base_url', $full_url, SQ_SESSION) ) {
  439. return $full_url . $path;
  440. }
  441. // else: autodetect
  442. /* Check if this is a HTTPS or regular HTTP request. */
  443. $proto = 'http://';
  444. if ($is_secure_connection)
  445. $proto = 'https://';
  446. /* Get the hostname from the Host header or server config. */
  447. if ($sq_ignore_http_x_forwarded_headers
  448. || !sqgetGlobalVar('HTTP_X_FORWARDED_HOST', $host, SQ_SERVER)
  449. || empty($host)) {
  450. if ( !sqgetGlobalVar('HTTP_HOST', $host, SQ_SERVER) || empty($host) ) {
  451. if ( !sqgetGlobalVar('SERVER_NAME', $host, SQ_SERVER) || empty($host) ) {
  452. $host = '';
  453. }
  454. }
  455. }
  456. $port = '';
  457. if (! strstr($host, ':')) {
  458. // Note: HTTP_X_FORWARDED_PROTO could be sent from the client and
  459. // therefore possibly spoofed/hackable. Thus, SquirrelMail
  460. // ignores such headers by default. The administrator
  461. // can tell SM to use such header values by setting
  462. // $sq_ignore_http_x_forwarded_headers to boolean FALSE
  463. // in config/config.php or by using config/conf.pl.
  464. global $sq_ignore_http_x_forwarded_headers;
  465. if ($sq_ignore_http_x_forwarded_headers
  466. || !sqgetGlobalVar('HTTP_X_FORWARDED_PROTO', $forwarded_proto, SQ_SERVER))
  467. $forwarded_proto = '';
  468. if (sqgetGlobalVar('SERVER_PORT', $server_port, SQ_SERVER)) {
  469. if (($server_port != 80 && $proto == 'http://') ||
  470. ($server_port != 443 && $proto == 'https://' &&
  471. strcasecmp($forwarded_proto, 'https') !== 0)) {
  472. $port = sprintf(':%d', $server_port);
  473. }
  474. }
  475. }
  476. /* this is a workaround for the weird macosx caching that
  477. * causes Apache to return 16080 as the port number, which causes
  478. * SM to bail */
  479. if ($imap_server_type == 'macosx' && $port == ':16080') {
  480. $port = '';
  481. }
  482. /* Fallback is to omit the server name and use a relative */
  483. /* URI, although this is not RFC 2616 compliant. */
  484. $full_url = ($host ? $proto . $host . $port : '');
  485. sqsession_register($full_url, 'sq_base_url');
  486. return $full_url . $path;
  487. }
  488. /**
  489. * Get Message List URI
  490. *
  491. * @param string $mailbox Current mailbox name (unencoded/raw)
  492. * @param string $startMessage The mailbox page offset
  493. * @param string $what Any current search parameters (OPTIONAL;
  494. * default empty string)
  495. *
  496. * @return string The message list URI
  497. *
  498. * @since 1.5.2
  499. *
  500. */
  501. function get_message_list_uri($mailbox, $startMessage, $what='') {
  502. global $base_uri;
  503. $urlMailbox = urlencode($mailbox);
  504. $list_xtra = "?where=read_body.php&what=$what&mailbox=" . $urlMailbox.
  505. "&startMessage=$startMessage";
  506. return $base_uri .'src/right_main.php'. $list_xtra;
  507. }
  508. /**
  509. * Encrypts password
  510. *
  511. * These functions are used to encrypt the password before it is
  512. * stored in a cookie. The encryption key is generated by
  513. * OneTimePadCreate();
  514. *
  515. * @param string $string the (password)string to encrypt
  516. * @param string $epad the encryption key
  517. * @return string the base64-encoded encrypted password
  518. * @since 1.0
  519. */
  520. function OneTimePadEncrypt ($string, $epad) {
  521. $pad = base64_decode($epad);
  522. if (strlen($pad)>0) {
  523. // make sure that pad is longer than string
  524. while (strlen($string)>strlen($pad)) {
  525. $pad.=$pad;
  526. }
  527. } else {
  528. // FIXME: what should we do when $epad is not base64 encoded or empty.
  529. }
  530. $encrypted = '';
  531. for ($i = 0; $i < strlen ($string); $i++) {
  532. $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
  533. }
  534. return base64_encode($encrypted);
  535. }
  536. /**
  537. * Decrypts a password from the cookie
  538. *
  539. * Decrypts a password from the cookie, encrypted by OneTimePadEncrypt.
  540. * This uses the encryption key that is stored in the session.
  541. *
  542. * @param string $string the string to decrypt
  543. * @param string $epad the encryption key from the session
  544. * @return string the decrypted password
  545. * @since 1.0
  546. */
  547. function OneTimePadDecrypt ($string, $epad) {
  548. $pad = base64_decode($epad);
  549. if (strlen($pad)>0) {
  550. // make sure that pad is longer than string
  551. while (strlen($string)>strlen($pad)) {
  552. $pad.=$pad;
  553. }
  554. } else {
  555. // FIXME: what should we do when $epad is not base64 encoded or empty.
  556. }
  557. $encrypted = base64_decode ($string);
  558. $decrypted = '';
  559. for ($i = 0; $i < strlen ($encrypted); $i++) {
  560. $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
  561. }
  562. return $decrypted;
  563. }
  564. /**
  565. * Creates encryption key
  566. *
  567. * Creates an encryption key for encrypting the password stored in the cookie.
  568. * The encryption key itself is stored in the session.
  569. *
  570. * Pad must be longer or equal to encoded string length in 1.4.4/1.5.0 and older.
  571. * @param int $length optional, length of the string to generate
  572. * @return string the encryption key
  573. * @since 1.0
  574. */
  575. function OneTimePadCreate ($length=100) {
  576. $pad = '';
  577. for ($i = 0; $i < $length; $i++) {
  578. $pad .= chr(random_int(0,255));
  579. }
  580. return base64_encode($pad);
  581. }
  582. /**
  583. * Returns a string showing a byte size figure in
  584. * a more easily digested (readable) format
  585. *
  586. * @param int $bytes the size in bytes
  587. * @param int $filesize_divisor the divisor we'll use (OPTIONAL; default 1024)
  588. *
  589. * @return string The size in human readable format
  590. *
  591. * @since 1.0
  592. *
  593. */
  594. function show_readable_size($bytes, $filesize_divisor=1024) {
  595. $bytes /= $filesize_divisor;
  596. $type = _("KiB");
  597. if ($bytes / $filesize_divisor > 1) {
  598. $bytes /= $filesize_divisor;
  599. $type = _("MiB");
  600. }
  601. if ($bytes < 10) {
  602. $bytes *= 10;
  603. settype($bytes, 'integer');
  604. $bytes /= 10;
  605. } else {
  606. settype($bytes, 'integer');
  607. }
  608. global $nbsp;
  609. return $bytes . $nbsp . $type;
  610. }
  611. /**
  612. * Generates a random string from the character set you pass in
  613. *
  614. * @param int $size the length of the string to generate
  615. * @param string $chars a string containing the characters to use
  616. * @param int $flags a flag to add a specific set to the characters to use:
  617. * Flags:
  618. * 1 = add lowercase a-z to $chars
  619. * 2 = add uppercase A-Z to $chars
  620. * 4 = add numbers 0-9 to $chars
  621. * @return string the random string
  622. * @since 1.0
  623. */
  624. function GenerateRandomString($size, $chars, $flags = 0) {
  625. if ($flags & 0x1) {
  626. $chars .= 'abcdefghijklmnopqrstuvwxyz';
  627. }
  628. if ($flags & 0x2) {
  629. $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  630. }
  631. if ($flags & 0x4) {
  632. $chars .= '0123456789';
  633. }
  634. if (($size < 1) || (strlen($chars) < 1)) {
  635. return '';
  636. }
  637. $String = '';
  638. $j = strlen( $chars ) - 1;
  639. while (strlen($String) < $size) {
  640. $String .= $chars[random_int(0, $j)];
  641. }
  642. return $String;
  643. }
  644. /**
  645. * Escapes special characters for use in IMAP commands.
  646. *
  647. * @param string $str the string to escape
  648. * @return string the escaped string
  649. * @since 1.0.3
  650. */
  651. function quoteimap($str) {
  652. return str_replace(array('\\', '"'), array('\\\\', '\\"'), $str);
  653. }
  654. /**
  655. * Create compose link
  656. *
  657. * Returns a link to the compose-page, taking in consideration
  658. * the compose_in_new and javascript settings.
  659. *
  660. * @param string $url The URL to the compose page
  661. * @param string $text The link text, default "Compose"
  662. * @param string $target URL target, if any (since 1.4.3)
  663. * @param string $accesskey The access key to be used, if any
  664. *
  665. * @return string a link to the compose page
  666. *
  667. * @since 1.4.2
  668. */
  669. function makeComposeLink($url, $text = null, $target='', $accesskey='NONE') {
  670. global $compose_new_win, $compose_width,
  671. $compose_height, $oTemplate;
  672. if(!$text) {
  673. $text = _("Compose");
  674. }
  675. // if not using "compose in new window", make
  676. // regular link and be done with it
  677. if($compose_new_win != '1') {
  678. return makeInternalLink($url, $text, $target, $accesskey);
  679. }
  680. // build the compose in new window link...
  681. // if javascript is on, use onclick event to handle it
  682. if(checkForJavascript()) {
  683. sqgetGlobalVar('base_uri', $base_uri, SQ_SESSION);
  684. $compuri = SM_BASE_URI.$url;
  685. return create_hyperlink('javascript:void(0)', $text, '',
  686. "comp_in_new('$compuri','$compose_width','$compose_height')",
  687. '', '', '',
  688. ($accesskey == 'NONE'
  689. ? array()
  690. : array('accesskey' => $accesskey)));
  691. }
  692. // otherwise, just open new window using regular HTML
  693. return makeInternalLink($url, $text, '_blank', $accesskey);
  694. }
  695. /**
  696. * version of fwrite which checks for failure
  697. * @param resource $fp
  698. * @param string $string
  699. * @return number of written bytes. false on failure
  700. * @since 1.4.3
  701. */
  702. function sq_fwrite($fp, $string) {
  703. // write to file
  704. $count = @fwrite($fp,$string);
  705. // the number of bytes written should be the length of the string
  706. if($count != strlen($string)) {
  707. return FALSE;
  708. }
  709. return $count;
  710. }
  711. /**
  712. * sq_get_html_translation_table
  713. *
  714. * Returns the translation table used by sq_htmlentities()
  715. *
  716. * @param integer $table html translation table. Possible values (without quotes):
  717. * <ul>
  718. * <li>HTML_ENTITIES - full html entities table defined by charset</li>
  719. * <li>HTML_SPECIALCHARS - html special characters table</li>
  720. * </ul>
  721. * @param integer $quote_style quote encoding style. Possible values (without quotes):
  722. * <ul>
  723. * <li>ENT_COMPAT - (default) encode double quotes</li>
  724. * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
  725. * <li>ENT_QUOTES - encode double and single quotes</li>
  726. * </ul>
  727. * @param string $charset charset used for encoding. default to us-ascii, 'auto' uses $default_charset global value.
  728. * @return array html translation array
  729. * @since 1.5.1
  730. */
  731. function sq_get_html_translation_table($table,$quote_style=ENT_COMPAT,$charset='us-ascii') {
  732. global $default_charset;
  733. if ($table == HTML_SPECIALCHARS) $charset='us-ascii';
  734. // Start array with ampersand
  735. $sq_html_ent_table = array( "&" => '&amp;' );
  736. // < and >
  737. $sq_html_ent_table = array_merge($sq_html_ent_table,
  738. array("<" => '&lt;',
  739. ">" => '&gt;')
  740. );
  741. // double quotes
  742. if ($quote_style == ENT_COMPAT)
  743. $sq_html_ent_table = array_merge($sq_html_ent_table,
  744. array("\"" => '&quot;')
  745. );
  746. // double and single quotes
  747. if ($quote_style == ENT_QUOTES)
  748. $sq_html_ent_table = array_merge($sq_html_ent_table,
  749. array("\"" => '&quot;',
  750. "'" => '&#39;')
  751. );
  752. if ($charset=='auto') $charset=$default_charset;
  753. // add entities that depend on charset
  754. switch($charset){
  755. case 'iso-8859-1':
  756. include_once(SM_PATH . 'functions/htmlentities/iso-8859-1.php');
  757. break;
  758. case 'utf-8':
  759. include_once(SM_PATH . 'functions/htmlentities/utf-8.php');
  760. break;
  761. case 'us-ascii':
  762. default:
  763. break;
  764. }
  765. // return table
  766. return $sq_html_ent_table;
  767. }
  768. /**
  769. * sq_htmlentities
  770. *
  771. * Convert all applicable characters to HTML entities.
  772. * Minimal php requirement - v.4.0.5.
  773. *
  774. * Function is designed for people that want to use full power of htmlentities() in
  775. * i18n environment.
  776. *
  777. * @param string $string string that has to be sanitized
  778. * @param integer $quote_style quote encoding style. Possible values (without quotes):
  779. * <ul>
  780. * <li>ENT_COMPAT - (default) encode double quotes</li>
  781. * <li>ENT_NOQUOTES - don't encode double or single quotes</li>
  782. * <li>ENT_QUOTES - encode double and single quotes</li>
  783. * </ul>
  784. * @param string $charset charset used for encoding. defaults to 'us-ascii', 'auto' uses $default_charset global value.
  785. * @return string sanitized string
  786. * @since 1.5.1
  787. */
  788. function sq_htmlentities($string,$quote_style=ENT_COMPAT,$charset='us-ascii') {
  789. // get translation table
  790. $sq_html_ent_table=sq_get_html_translation_table(HTML_ENTITIES,$quote_style,$charset);
  791. // convert characters
  792. return str_replace(array_keys($sq_html_ent_table),array_values($sq_html_ent_table),$string);
  793. }
  794. /**
  795. * Tests if string contains 8bit symbols.
  796. *
  797. * If charset is not set, function defaults to default_charset.
  798. * $default_charset global must be set correctly if $charset is
  799. * not used.
  800. * @param string $string tested string
  801. * @param string $charset charset used in a string
  802. * @return bool true if 8bit symbols are detected
  803. * @since 1.5.1 and 1.4.4
  804. */
  805. function sq_is8bit($string,$charset='') {
  806. global $default_charset;
  807. if ($charset=='') $charset=$default_charset;
  808. /**
  809. * Don't use \240 in ranges. Sometimes RH 7.2 doesn't like it.
  810. * Don't use \200-\237 for iso-8859-x charsets. This range
  811. * stores control symbols in those charsets.
  812. * Use preg_match instead of ereg in order to avoid problems
  813. * with mbstring overloading
  814. */
  815. if (preg_match("/^iso-8859/i",$charset)) {
  816. $needle='/\240|[\241-\377]/';
  817. } else {
  818. $needle='/[\200-\237]|\240|[\241-\377]/';
  819. }
  820. return preg_match("$needle",$string);
  821. }
  822. /**
  823. * Replacement of mb_list_encodings function
  824. *
  825. * This function provides replacement for function that is available only
  826. * in php 5.x. Function does not test all mbstring encodings. Only the ones
  827. * that might be used in SM translations.
  828. *
  829. * Supported strings are stored in session in order to reduce number of
  830. * mb_internal_encoding function calls.
  831. *
  832. * If you want to test all mbstring encodings - fill $list_of_encodings
  833. * array.
  834. * @return array list of encodings supported by php mbstring extension
  835. * @since 1.5.1 and 1.4.6
  836. */
  837. function sq_mb_list_encodings() {
  838. if (! function_exists('mb_internal_encoding'))
  839. return array();
  840. // php 5+ function
  841. if (function_exists('mb_list_encodings')) {
  842. $ret = mb_list_encodings();
  843. array_walk($ret,'sq_lowercase_array_vals');
  844. return $ret;
  845. }
  846. // don't try to test encodings, if they are already stored in session
  847. if (sqgetGlobalVar('mb_supported_encodings',$mb_supported_encodings,SQ_SESSION))
  848. return $mb_supported_encodings;
  849. // save original encoding
  850. $orig_encoding=mb_internal_encoding();
  851. $list_of_encoding=array(
  852. 'pass',
  853. 'auto',
  854. 'ascii',
  855. 'jis',
  856. 'utf-8',
  857. 'sjis',
  858. 'euc-jp',
  859. 'iso-8859-1',
  860. 'iso-8859-2',
  861. 'iso-8859-7',
  862. 'iso-8859-9',
  863. 'iso-8859-15',
  864. 'koi8-r',
  865. 'koi8-u',
  866. 'big5',
  867. 'gb2312',
  868. 'gb18030',
  869. 'windows-1251',
  870. 'windows-1255',
  871. 'windows-1256',
  872. 'tis-620',
  873. 'iso-2022-jp',
  874. 'euc-cn',
  875. 'euc-kr',
  876. 'euc-tw',
  877. 'uhc',
  878. 'utf7-imap');
  879. $supported_encodings=array();
  880. foreach ($list_of_encoding as $encoding) {
  881. // try setting encodings. suppress warning messages
  882. if (@mb_internal_encoding($encoding))
  883. $supported_encodings[]=$encoding;
  884. }
  885. // restore original encoding
  886. mb_internal_encoding($orig_encoding);
  887. // register list in session
  888. sqsession_register($supported_encodings,'mb_supported_encodings');
  889. return $supported_encodings;
  890. }
  891. /**
  892. * Callback function used to lowercase array values.
  893. * @param string $val array value
  894. * @param mixed $key array key
  895. * @since 1.5.1 and 1.4.6
  896. */
  897. function sq_lowercase_array_vals(&$val,$key) {
  898. $val = strtolower($val);
  899. }
  900. /**
  901. * Function returns number of characters in string.
  902. *
  903. * Returned number might be different from number of bytes in string,
  904. * if $charset is multibyte charset. Detection depends on mbstring
  905. * functions. If mbstring does not support tested multibyte charset,
  906. * vanilla string length function is used.
  907. * @param string $str string
  908. * @param string $charset charset
  909. * @since 1.5.1 and 1.4.6
  910. * @return integer number of characters in string
  911. */
  912. function sq_strlen($str, $charset=null){
  913. // default option
  914. if (is_null($charset)) return strlen($str);
  915. // lowercase charset name
  916. $charset=strtolower($charset);
  917. // use automatic charset detection, if function call asks for it
  918. if ($charset=='auto') {
  919. global $default_charset, $squirrelmail_language;
  920. set_my_charset();
  921. $charset=$default_charset;
  922. if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
  923. }
  924. // Use mbstring only with listed charsets
  925. $aList_of_mb_charsets=array('utf-8','big5','gb2312','gb18030','euc-jp','euc-cn','euc-tw','euc-kr');
  926. // calculate string length according to charset
  927. if (in_array($charset,$aList_of_mb_charsets) && in_array($charset,sq_mb_list_encodings())) {
  928. $real_length = mb_strlen($str,$charset);
  929. } else {
  930. // own strlen detection code is removed because missing strpos,
  931. // strtoupper and substr implementations break string wrapping.
  932. $real_length=strlen($str);
  933. }
  934. return $real_length;
  935. }
  936. /**
  937. * string padding with multibyte support
  938. *
  939. * @link http://www.php.net/str_pad
  940. * @param string $string original string
  941. * @param integer $width padded string width
  942. * @param string $pad padding symbols
  943. * @param integer $padtype padding type
  944. * (internal php defines, see str_pad() description)
  945. * @param string $charset charset used in original string
  946. * @return string padded string
  947. */
  948. function sq_str_pad($string, $width, $pad, $padtype, $charset='') {
  949. $charset = strtolower($charset);
  950. $padded_string = '';
  951. switch ($charset) {
  952. case 'utf-8':
  953. case 'big5':
  954. case 'gb2312':
  955. case 'euc-kr':
  956. /*
  957. * all multibyte charsets try to increase width value by
  958. * adding difference between number of bytes and real length
  959. */
  960. $width = $width - sq_strlen($string,$charset) + strlen($string);
  961. default:
  962. $padded_string=str_pad($string,$width,$pad,$padtype);
  963. }
  964. return $padded_string;
  965. }
  966. /**
  967. * Wrapper that is used to switch between vanilla and multibyte substr
  968. * functions.
  969. * @param string $string
  970. * @param integer $start
  971. * @param integer $length
  972. * @param string $charset
  973. * @return string
  974. * @since 1.5.1
  975. * @link http://www.php.net/substr
  976. * @link http://www.php.net/mb_substr
  977. */
  978. function sq_substr($string,$start,$length=NULL,$charset='auto') {
  979. // if $length is NULL, use the full string length...
  980. // we have to do this to mimick the use of substr()
  981. // where $length is not given
  982. //
  983. if (is_null($length))
  984. $length = sq_strlen($length);
  985. // use automatic charset detection, if function call asks for it
  986. static $charset_auto, $bUse_mb;
  987. if ($charset=='auto') {
  988. if (!isset($charset_auto)) {
  989. global $default_charset, $squirrelmail_language;
  990. set_my_charset();
  991. $charset=$default_charset;
  992. if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
  993. $charset_auto = $charset;
  994. } else {
  995. $charset = $charset_auto;
  996. }
  997. }
  998. $charset = strtolower($charset);
  999. // in_array call is expensive => do it once and use a static var for
  1000. // storing the results
  1001. if (!isset($bUse_mb)) {
  1002. if (in_array($charset,sq_mb_list_encodings())) {
  1003. $bUse_mb = true;
  1004. } else {
  1005. $bUse_mb = false;
  1006. }
  1007. }
  1008. if ($bUse_mb) {
  1009. return mb_substr($string,$start,$length,$charset);
  1010. }
  1011. // TODO: add mbstring independent code
  1012. // use vanilla string functions as last option
  1013. return substr($string,$start,$length);
  1014. }
  1015. /**
  1016. * This is a replacement for PHP's substr_replace() that is
  1017. * multibyte-aware.
  1018. *
  1019. * @param string $string The string to operate upon
  1020. * @param string $replacement The string to be inserted
  1021. * @param int $start The offset at which to begin substring replacement
  1022. * @param int $length The number of characters after $start to remove
  1023. * NOTE that if you need to specify a charset but
  1024. * want to achieve normal substr_replace() behavior
  1025. * where $length is not specified, use NULL (OPTIONAL;
  1026. * default from $start to end of string)
  1027. * @param string $charset The charset of the given string. A value of NULL
  1028. * here will force the use of PHP's standard substr().
  1029. * (OPTIONAL; default is "auto", which indicates that
  1030. * the user's current charset should be used).
  1031. *
  1032. * @return string The manipulated string
  1033. *
  1034. * Of course, you can use more advanced (e.g., negative) values
  1035. * for $start and $length as needed - see the PHP manual for more
  1036. * information: http://www.php.net/manual/function.substr-replace.php
  1037. *
  1038. */
  1039. function sq_substr_replace($string, $replacement, $start, $length=NULL,
  1040. $charset='auto')
  1041. {
  1042. // NULL charset? Just use substr_replace()
  1043. //
  1044. if (is_null($charset))
  1045. return is_null($length) ? substr_replace($string, $replacement, $start)
  1046. : substr_replace($string, $replacement, $start, $length);
  1047. // use current character set?
  1048. //
  1049. if ($charset == 'auto')
  1050. {
  1051. //FIXME: is there any reason why this cannot be a global flag used by all string wrapper functions?
  1052. static $auto_charset;
  1053. if (!isset($auto_charset))
  1054. {
  1055. global $default_charset;
  1056. //FIXME - do we need this?
  1057. global $squirrelmail_language;
  1058. set_my_charset();
  1059. $auto_charset = $default_charset;
  1060. //FIXME - do we need this?
  1061. if ($squirrelmail_language == 'ja_JP') $auto_charset = 'euc-jp';
  1062. }
  1063. $charset = $auto_charset;
  1064. }
  1065. // standardize character set name
  1066. //
  1067. $charset = strtolower($charset);
  1068. /* ===== 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
  1069. // only use mbstring with the following character sets
  1070. //
  1071. $sq_substr_replace_mb_charsets = array(
  1072. 'utf-8',
  1073. 'big5',
  1074. 'gb2312',
  1075. 'gb18030',
  1076. 'euc-jp',
  1077. 'euc-cn',
  1078. 'euc-tw',
  1079. 'euc-kr'
  1080. );
  1081. // now we can use our own implementation using
  1082. // mb_substr() and mb_strlen() if needed
  1083. //
  1084. if (in_array($charset, $sq_substr_replace_mb_charsets)
  1085. && in_array($charset, sq_mb_list_encodings()))
  1086. ===== */
  1087. //FIXME: is there any reason why this cannot be a global array used by all string wrapper functions?
  1088. if (in_array($charset, sq_mb_list_encodings()))
  1089. {
  1090. $string_length = mb_strlen($string, $charset);
  1091. if ($start < 0)
  1092. $start = max(0, $string_length + $start);
  1093. else if ($start > $string_length)
  1094. $start = $string_length;
  1095. if ($length < 0)
  1096. $length = max(0, $string_length - $start + $length);
  1097. else if (is_null($length) || $length > $string_length)
  1098. $length = $string_length;
  1099. if ($start + $length > $string_length)
  1100. $length = $string_length - $start;
  1101. return mb_substr($string, 0, $start, $charset)
  1102. . $replacement
  1103. . mb_substr($string,
  1104. $start + $length,
  1105. $string_length, // FIXME: I can't see why this is needed: - $start - $length,
  1106. $charset);
  1107. }
  1108. // else use normal substr_replace()
  1109. //
  1110. return is_null($length) ? substr_replace($string, $replacement, $start)
  1111. : substr_replace($string, $replacement, $start, $length);
  1112. }
  1113. /**
  1114. * Wrapper that is used to switch between vanilla and multibyte strpos
  1115. * functions.
  1116. * @param string $haystack
  1117. * @param mixed $needle
  1118. * @param integer $offset
  1119. * @param string $charset
  1120. * @return string
  1121. * @since 1.5.1
  1122. * @link http://www.php.net/strpos
  1123. * @link http://www.php.net/mb_strpos
  1124. */
  1125. function sq_strpos($haystack,$needle,$offset,$charset='auto') {
  1126. // use automatic charset detection, if function call asks for it
  1127. static $charset_auto, $bUse_mb;
  1128. if ($charset=='auto') {
  1129. if (!isset($charset_auto)) {
  1130. global $default_charset, $squirrelmail_language;
  1131. set_my_charset();
  1132. $charset=$default_charset;
  1133. if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
  1134. $charset_auto = $charset;
  1135. } else {
  1136. $charset = $charset_auto;
  1137. }
  1138. }
  1139. $charset = strtolower($charset);
  1140. // in_array call is expensive => do it once and use a static var for
  1141. // storing the results
  1142. if (!isset($bUse_mb)) {
  1143. if (in_array($charset,sq_mb_list_encodings())) {
  1144. $bUse_mb = true;
  1145. } else {
  1146. $bUse_mb = false;
  1147. }
  1148. }
  1149. if ($bUse_mb) {
  1150. return mb_strpos($haystack,$needle,$offset,$charset);
  1151. }
  1152. // TODO: add mbstring independent code
  1153. // use vanilla string functions as last option
  1154. return strpos($haystack,$needle,$offset);
  1155. }
  1156. /**
  1157. * Wrapper that is used to switch between vanilla and multibyte strtoupper
  1158. * functions.
  1159. * @param string $string
  1160. * @param string $charset
  1161. * @return string
  1162. * @since 1.5.1
  1163. * @link http://www.php.net/strtoupper
  1164. * @link http://www.php.net/mb_strtoupper
  1165. */
  1166. function sq_strtoupper($string,$charset='auto') {
  1167. // use automatic charset detection, if function call asks for it
  1168. static $charset_auto, $bUse_mb;
  1169. if ($charset=='auto') {
  1170. if (!isset($charset_auto)) {
  1171. global $default_charset, $squirrelmail_language;
  1172. set_my_charset();
  1173. $charset=$default_charset;
  1174. if ($squirrelmail_language=='ja_JP') $charset='euc-jp';
  1175. $charset_auto = $charset;
  1176. } else {
  1177. $charset = $charset_auto;
  1178. }
  1179. }
  1180. $charset = strtolower($charset);
  1181. // in_array call is expensive => do it once and use a static var for
  1182. // storing the results
  1183. if (!isset($bUse_mb)) {
  1184. if (function_exists('mb_strtoupper') &&
  1185. in_array($charset,sq_mb_list_encodings())) {
  1186. $bUse_mb = true;
  1187. } else {
  1188. $bUse_mb = false;
  1189. }
  1190. }
  1191. if ($bUse_mb) {
  1192. return mb_strtoupper($string,$charset);
  1193. }
  1194. // TODO: add mbstring independent code
  1195. // use vanilla string functions as last option
  1196. return strtoupper($string);
  1197. }
  1198. /**
  1199. * Counts 8bit bytes in string
  1200. * @param string $string tested string
  1201. * @return integer number of 8bit bytes
  1202. */
  1203. function sq_count8bit($string) {
  1204. $count=0;
  1205. for ($i=0; $i<strlen($string); $i++) {
  1206. if (ord($string[$i]) > 127) $count++;
  1207. }
  1208. return $count;
  1209. }
  1210. /**
  1211. * Callback function to trim whitespace from a value, to be used in array_walk
  1212. * @param string $value value to trim
  1213. * @since 1.5.2 and 1.4.7
  1214. */
  1215. function sq_trim_value ( &$value ) {
  1216. $value = trim($value);
  1217. }
  1218. /**
  1219. * Truncates the given string so that it has at
  1220. * most $max_chars characters. NOTE that a "character"
  1221. * may be a multibyte character, or (optionally), an
  1222. * HTML entity , so this function is different than
  1223. * using substr() or mb_substr().
  1224. *
  1225. * NOTE that if $elipses is given and used, the returned
  1226. * number of characters will be $max_chars PLUS the
  1227. * length of $elipses
  1228. *
  1229. * @param string $string The string to truncate
  1230. * @param int $max_chars The maximum allowable characters
  1231. * @param string $elipses A string that will be added to
  1232. * the end of the truncated string
  1233. * (ONLY if it is truncated) (OPTIONAL;
  1234. * default not used)
  1235. * @param boolean $html_entities_as_chars Whether or not to keep
  1236. * HTML entities together
  1237. * (OPTIONAL; default ignore
  1238. * HTML entities)
  1239. *
  1240. * @return string The truncated string
  1241. *
  1242. * @since 1.4.20 and 1.5.2 (replaced truncateWithEntities())
  1243. *
  1244. */
  1245. function sm_truncate_string($string, $max_chars, $elipses='',
  1246. $html_entities_as_chars=FALSE)
  1247. {
  1248. // if the length of the string is less than
  1249. // the allowable number of characters, just
  1250. // return it as is (even if it contains any
  1251. // HTML entities, that would just make the
  1252. // actual length even smaller)
  1253. //
  1254. $actual_strlen = sq_strlen($string, 'auto');
  1255. if ($max_chars <= 0 || $actual_strlen <= $max_chars)
  1256. return $string;
  1257. // if needed, count the number of HTML entities in
  1258. // the string up to the maximum character limit,
  1259. // pushing that limit up for each entity found
  1260. //
  1261. $adjusted_max_chars = $max_chars;
  1262. if ($html_entities_as_chars)
  1263. {
  1264. // $loop_count is needed to prevent an endless loop
  1265. // which is caused by buggy mbstring versions that
  1266. // return 0 (zero) instead of FALSE in some rare
  1267. // cases. Thanks, PHP.
  1268. // see: http://bugs.php.net/bug.php?id=52731
  1269. // also: tracker $3053349
  1270. //
  1271. $loop_count = 0;
  1272. $entity_pos = $entity_end_pos = -1;
  1273. while ($entity_end_pos + 1 < $actual_strlen
  1274. && ($entity_pos = sq_strpos($string, '&', $entity_end_pos + 1)) !== FALSE
  1275. && ($entity_end_pos = sq_strpos($string, ';', $entity_pos)) !== FALSE
  1276. && $entity_pos <= $adjusted_max_chars
  1277. && $loop_count++ < $max_chars)
  1278. {
  1279. $adjusted_max_chars += $entity_end_pos - $entity_pos;
  1280. }
  1281. // this isn't necessary because sq_substr() would figure this
  1282. // out anyway, but we can avoid a sq_substr() call and we
  1283. // know that we don't have to add an elipses (this is now
  1284. // an accurate comparison, since $adjusted_max_chars, like
  1285. // $actual_strlen, does not take into account HTML entities)
  1286. //
  1287. if ($actual_strlen <= $adjusted_max_chars)
  1288. return $string;
  1289. }
  1290. // get the truncated string
  1291. //
  1292. $truncated_string = sq_substr($string, 0, $adjusted_max_chars);
  1293. // return with added elipses
  1294. //
  1295. return $truncated_string . $elipses;
  1296. }
  1297. /**
  1298. * Gathers the list of secuirty tokens currently
  1299. * stored in the user's preferences and optionally
  1300. * purges old ones from the list.
  1301. *
  1302. * @param boolean $purge_old Indicates if old tokens
  1303. * should be purged from the
  1304. * list ("old" is 2 days or
  1305. * older unless the administrator
  1306. * overrides that value using
  1307. * $max_token_age_days in
  1308. * config/config_local.php)
  1309. * (OPTIONAL; default is to always
  1310. * purge old tokens)
  1311. *
  1312. * @return array The list of tokens
  1313. *
  1314. * @since 1.4.19 and 1.5.2
  1315. *
  1316. */
  1317. function sm_get_user_security_tokens($purge_old=TRUE)
  1318. {
  1319. global $data_dir, $username, $max_token_age_days,
  1320. $use_expiring_security_tokens;
  1321. $tokens = getPref($data_dir, $username, 'security_tokens', '');
  1322. if (($tokens = unserialize($tokens)) === FALSE || !is_array($tokens))
  1323. $tokens = array();
  1324. // purge old tokens if necessary
  1325. //
  1326. if ($purge_old)
  1327. {
  1328. if (empty($max_token_age_days)) $max_token_age_days = 2;
  1329. $now = time();
  1330. $discard_token_date = $now - ($max_token_age_days * 86400);
  1331. $cleaned_tokens = array();
  1332. foreach ($tokens as $token => $timestamp)
  1333. if ($timestamp >= $discard_token_date)
  1334. $cleaned_tokens[$token] = $timestamp;
  1335. $tokens = $cleaned_tokens;
  1336. }
  1337. return $tokens;
  1338. }
  1339. /**
  1340. * Generates a security token that is then stored in
  1341. * the user's preferences with a timestamp for later
  1342. * verification/use (although session-based tokens
  1343. * are not stored in user preferences).
  1344. *
  1345. * NOTE: By default SquirrelMail will use a single session-based
  1346. * token, but if desired, user tokens can have expiration
  1347. * dates associated with them and become invalid even during
  1348. * the same login session. When in that mode, the note
  1349. * immediately below applies, otherwise it is irrelevant.
  1350. * To enable that mode, the administrator must add the
  1351. * following to config/config_local.php:
  1352. * $use_expiring_security_tokens = TRUE;
  1353. *
  1354. * NOTE: The administrator can force SquirrelMail to generate
  1355. * a new token every time one is requested (which may increase
  1356. * obscurity through token randomness at the cost of some
  1357. * performance) by adding the following to
  1358. * config/config_local.php: $do_not_use_single_token = TRUE;
  1359. * Otherwise, only one token will be generated per user which
  1360. * will change only after it expires or is used outside of the
  1361. * validity period specified when calling sm_validate_security_token()
  1362. *
  1363. * WARNING: If the administrator has turned the token system
  1364. * off by setting $disable_security_tokens to TRUE in
  1365. * config/config.php or the configuration tool, this
  1366. * function will not store tokens in the user
  1367. * preferences (but it will still generate and return
  1368. * a random string).
  1369. *
  1370. * @param boolean $force_generate_new When TRUE, a new token will
  1371. * always be created even if current
  1372. * configuration dictates otherwise
  1373. * (OPTIONAL; default FALSE)
  1374. *
  1375. * @return string A security token
  1376. *
  1377. * @since 1.4.19 and 1.5.2
  1378. *
  1379. */
  1380. function sm_generate_security_token($force_generate_new=FALSE)
  1381. {
  1382. global $data_dir, $username, $disable_security_tokens, $do_not_use_single_token,
  1383. $use_expiring_security_tokens;
  1384. $max_generation_tries = 1000;
  1385. // if we're using session-based tokens, just return
  1386. // the same one every time (generate it if it's not there)
  1387. //
  1388. if (!$use_expiring_security_tokens)
  1389. {
  1390. if (sqgetGlobalVar('sm_security_token', $token, SQ_SESSION))
  1391. return $token;
  1392. // create new one since there was none in session
  1393. $token = GenerateRandomString(12, '', 7);
  1394. sqsession_register($token, 'sm_security_token');
  1395. return $token;
  1396. }
  1397. $tokens = sm_get_user_security_tokens();
  1398. if (!$force_generate_new && !$do_not_use_single_token && !empty($tokens))
  1399. return key($tokens);
  1400. $new_token = GenerateRandomString(12, '', 7);
  1401. $count = 0;
  1402. while (isset($tokens[$new_token]))
  1403. {
  1404. $new_token = GenerateRandomString(12, '', 7);
  1405. if (++$count > $max_generation_tries)
  1406. {
  1407. logout_error(_("Fatal token generation error; please contact your system administrator or the SquirrelMail Team"));
  1408. exit;
  1409. }
  1410. }
  1411. // is the token system enabled? CAREFUL!
  1412. //
  1413. if (!$disable_security_tokens)
  1414. {
  1415. $tokens[$new_token] = time();
  1416. setPref($data_dir, $username, 'security_tokens', serialize($tokens));
  1417. }
  1418. return $new_token;
  1419. }
  1420. /**
  1421. * Validates a given security token and optionally remove it
  1422. * from the user's preferences if it was valid. If the token
  1423. * is too old but otherwise valid, it will still be rejected.
  1424. *
  1425. * "Too old" is 2 days or older unless the administrator
  1426. * overrides that value using $max_token_age_days in
  1427. * config/config_local.php
  1428. *
  1429. * Session-based tokens of course are always reused and are
  1430. * valid for the lifetime of the login session.
  1431. *
  1432. * WARNING: If the administrator has turned the token system
  1433. * off by setting $disable_security_tokens to TRUE in
  1434. * config/config.php or the configuration tool, this
  1435. * function will always return TRUE.
  1436. *
  1437. * @param string $token The token to validate
  1438. * @param int $validity_period The number of seconds tokens are valid
  1439. * for (set to zero to remove valid tokens
  1440. * after only one use; set to -1 to allow
  1441. * indefinite re-use (but still subject to
  1442. * $max_token_age_days - see elsewhere);
  1443. * use 3600 to allow tokens to be reused for
  1444. * an hour) (OPTIONAL; default is to only
  1445. * allow tokens to be used once)
  1446. * NOTE this is unrelated to $max_token_age_days
  1447. * or rather is an additional time constraint on
  1448. * tokens that allows them to be re-used (or not)
  1449. * within a more narrow timeframe
  1450. * @param boolean $show_error Indicates that if the token is not
  1451. * valid, this function should display
  1452. * a generic error, log the user out
  1453. * and exit - this function will never
  1454. * return in that case.
  1455. * (OPTIONAL; default FALSE)
  1456. *
  1457. * @return boolean TRUE if the token validated; FALSE otherwise
  1458. *
  1459. * @since 1.4.19 and 1.5.2
  1460. *
  1461. */
  1462. function sm_validate_security_token($token, $validity_period=0, $show_error=FALSE)
  1463. {
  1464. global $data_dir, $username, $max_token_age_days,
  1465. $use_expiring_security_tokens,
  1466. $disable_security_tokens;
  1467. // bypass token validation? CAREFUL!
  1468. //
  1469. if ($disable_security_tokens) return TRUE;
  1470. // if we're using session-based tokens, just compare
  1471. // the same one every time
  1472. //
  1473. if (!$use_expiring_security_tokens)
  1474. {
  1475. if (!sqgetGlobalVar('sm_security_token', $session_token, SQ_SESSION))
  1476. {
  1477. if (!$show_error) return FALSE;
  1478. logout_error(_("Fatal security token error; please log in again"));
  1479. exit;
  1480. }
  1481. if ($token !== $session_token)
  1482. {
  1483. if (!$show_error) return FALSE;
  1484. logout_error(_("The current page request appears to have originated from an untrusted source."));
  1485. exit;
  1486. }
  1487. return TRUE;
  1488. }
  1489. // don't purge old tokens here because we already
  1490. // do it when generating tokens
  1491. //
  1492. $tokens = sm_get_user_security_tokens(FALSE);
  1493. // token not found?
  1494. //
  1495. if (empty($tokens[$token]))
  1496. {
  1497. if (!$show_error) return FALSE;
  1498. logout_error(_("This page request could not be verified and appears to have expired."));
  1499. exit;
  1500. }
  1501. $now = time();
  1502. $timestamp = $tokens[$token];
  1503. // whether valid or not, we want to remove it from
  1504. // user prefs if it's old enough (unless requested to
  1505. // bypass this (in which case $validity_period is -1))
  1506. //
  1507. if ($validity_period >= 0
  1508. && $timestamp < $now - $validity_period)
  1509. {
  1510. unset($tokens[$token]);
  1511. setPref($data_dir, $username, 'security_tokens', serialize($tokens));
  1512. }
  1513. // reject tokens that are too old
  1514. //
  1515. if (empty($max_token_age_days)) $max_token_age_days = 2;
  1516. $old_token_date = $now - ($max_token_age_days * 86400);
  1517. if ($timestamp < $old_token_date)
  1518. {
  1519. if (!$show_error) return FALSE;
  1520. logout_error(_("The current page request appears to have originated from an untrusted source."));
  1521. exit;
  1522. }
  1523. // token OK!
  1524. //
  1525. return TRUE;
  1526. }
  1527. /**
  1528. * Wrapper for PHP's htmlspecialchars() that
  1529. * attempts to add the correct character encoding
  1530. *
  1531. * @param string $string The string to be converted
  1532. * @param int $flags A bitmask that controls the behavior of
  1533. * htmlspecialchars() -- NOTE that this parameter
  1534. * should only be used to dictate handling of
  1535. * quotes; handling invalid code sequences is done
  1536. * using the $invalid_sequence_flag parameter below
  1537. * (See http://php.net/manual/function.htmlspecialchars.php )
  1538. * (OPTIONAL; default ENT_COMPAT)
  1539. * @param string $encoding The character encoding to use in the conversion
  1540. * (if not one of the character sets supported
  1541. * by PHP's htmlspecialchars(), then $encoding
  1542. * will be ignored and iso-8859-1 will be used,
  1543. * unless a default has been specified in
  1544. * $default_htmlspecialchars_encoding in
  1545. * config_local.php) (OPTIONAL; default automatic
  1546. * detection)
  1547. * @param boolean $double_encode Whether or not to convert entities that are
  1548. * already in the string (only supported in
  1549. * PHP 5.2.3+) (OPTIONAL; default TRUE)
  1550. * @param mixed $invalid_sequence_flag A bitmask that controls how invalid
  1551. * code sequences should be handled;
  1552. * When calling htmlspecialchars(),
  1553. * this value will be combined with
  1554. * the $flags parameter above
  1555. * (See http://php.net/manual/function.htmlspecialchars.php )
  1556. * (OPTIONAL; defaults to the string
  1557. * "ent_substitute" that, for PHP 5.4+,
  1558. * is converted to the ENT_SUBSTITUTE
  1559. * constant, otherwise empty)
  1560. *
  1561. * @return string The converted text
  1562. *
  1563. */
  1564. function sm_encode_html_special_chars($string, $flags=ENT_COMPAT,
  1565. $encoding=NULL, $double_encode=TRUE,
  1566. $invalid_sequence_flag='ent_substitute')
  1567. {
  1568. if ($invalid_sequence_flag === 'ent_substitute')
  1569. {
  1570. if (check_php_version(5, 4, 0))
  1571. $invalid_sequence_flag = ENT_SUBSTITUTE;
  1572. else
  1573. $invalid_sequence_flag = 0;
  1574. }
  1575. // charsets supported by PHP's htmlspecialchars
  1576. // (move this elsewhere if needed)
  1577. //
  1578. static $htmlspecialchars_charsets = array(
  1579. 'iso-8859-1', 'iso8859-1',
  1580. 'iso-8859-5', 'iso8859-5',
  1581. 'iso-8859-15', 'iso8859-15',
  1582. 'utf-8',
  1583. 'cp866', 'ibm866', '866',
  1584. 'cp1251', 'windows-1251', 'win-1251', '1251',
  1585. 'cp1252', 'windows-1252', '1252',
  1586. 'koi8-R', 'koi8-ru', 'koi8r',
  1587. 'big5', '950',
  1588. 'gb2312', '936',
  1589. 'big5-hkscs',
  1590. 'shift_jis', 'sjis', 'sjis-win', 'cp932', '932',
  1591. 'euc-jp', 'eucjp', 'eucjp-win',
  1592. 'macroman',
  1593. );
  1594. // if not given, set encoding to the charset being
  1595. // used by the current user interface language
  1596. //
  1597. if (!$encoding)
  1598. {
  1599. global $default_charset;
  1600. if ($default_charset == 'iso-2022-jp')
  1601. $default_charset = 'EUC-JP';
  1602. $encoding = $default_charset;
  1603. }
  1604. // two ways to handle encodings not supported by htmlspecialchars() -
  1605. // one takes less CPU cycles but can munge characters in certain
  1606. // translations, the other is more exact but requires more resources
  1607. //
  1608. global $html_special_chars_extended_fix;
  1609. //FIXME: need to document that the config switch above can be enabled in config_local... but first, we need to decide if we will implement the second option here -- currently there hasn't been a need for it (munged characters seem quite rare).... see tracker #2806 for some tips https://sourceforge.net/p/squirrelmail/bugs/2806
  1610. if (!in_array(strtolower($encoding), $htmlspecialchars_charsets))
  1611. {
  1612. if ($html_special_chars_extended_fix)
  1613. {
  1614. // convert to utf-8 first, run htmlspecialchars() and convert
  1615. // back to original encoding below
  1616. //
  1617. //FIXME: try conversion functions in this order: recode_string(), iconv(), mbstring (with various charset checks: sq_mb_list_encodings(), mb_check_encoding) -- oh, first check for internal charset_decode_CHARSET() function?? or just use (does this put everything into HTML entities already? shouldn't, but if it does, return right here):
  1618. $string = charset_decode($encoding, $string, TRUE, TRUE);
  1619. $string = charset_encode($string, $encoding, TRUE);
  1620. }
  1621. else
  1622. {
  1623. // simply force use of an encoding that is supported (some
  1624. // characters may be munged)
  1625. //
  1626. // use default from configuration if provided or hard-coded fallback
  1627. //
  1628. global $default_htmlspecialchars_encoding;
  1629. if (!empty($default_htmlspecialchars_encoding))
  1630. $encoding = $default_htmlspecialchars_encoding;
  1631. else
  1632. $encoding = 'iso-8859-1';
  1633. }
  1634. }
  1635. // TODO: Is adding this check an unnecessary performance hit?
  1636. if (check_php_version(5, 2, 3))
  1637. $ret = htmlspecialchars($string, $flags | $invalid_sequence_flag,
  1638. $encoding, $double_encode);
  1639. else
  1640. $ret = htmlspecialchars($string, $flags | $invalid_sequence_flag,
  1641. $encoding);
  1642. // convert back to original encoding if needed (see above)
  1643. //
  1644. if ($html_special_chars_extended_fix
  1645. && !in_array(strtolower($encoding), $htmlspecialchars_charsets))
  1646. {
  1647. //FIXME: NOT FINISHED - here, we'd convert from utf-8 back to original charset (if we obey $lossy_encoding and end up returning in utf-8 instead of original charset, does that screw up the caller?)
  1648. }
  1649. return $ret;
  1650. }