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