PageRenderTime 70ms CodeModel.GetById 13ms app.highlight 47ms RepoModel.GetById 1ms app.codeStats 0ms

/tags/rel-1_4_20/functions/strings.php

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