phpgroupware-cvs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Phpgroupware-cvs] old/squirrelmail/inc array.php, 1.1 smtp.php, 1.1 pre


From: skwashd
Subject: [Phpgroupware-cvs] old/squirrelmail/inc array.php, 1.1 smtp.php, 1.1 prefs.php, 1.1 plugin.php, 1.1 page_header.php, 1.1 strings.php, 1.1 translate_setup.php, 1.1 url_parser.php, 1.1 tree.php, 1.1 mime.php, 1.1 mailbox_display.php, 1.1 i18n.php, 1.1 hook_preferences.inc.php, 1.1 hook_home.inc.php, 1.1 imap.php, 1.1 imap_general.php, 1.1 imap_search.php, 1.1 imap_messages.php, 1.1 imap_mailbox.php, 1.1 hook_admin.inc.php, 1.1 functions.inc.php, 1.1 class.bopreferences.inc.php, 1.1 class.bocompose.inc.php, 1.1 auth.php, 1.1 class.phpmailer.inc.php, 1.1 class.smtp.php, 1.1 display_messages.php, 1.1 date.php, 1.1 class.uicompose.inc.php, 1.1
Date: Thu, 5 May 2005 02:56:00 +0200

Update of old/squirrelmail/inc

Added Files:
     Branch: MAIN
            array.php 
            smtp.php 
            prefs.php 
            plugin.php 
            page_header.php 
            strings.php 
            translate_setup.php 
            url_parser.php 
            tree.php 
            mime.php 
            mailbox_display.php 
            i18n.php 
            hook_preferences.inc.php 
            hook_home.inc.php 
            imap.php 
            imap_general.php 
            imap_search.php 
            imap_messages.php 
            imap_mailbox.php 
            hook_admin.inc.php 
            functions.inc.php 
            class.bopreferences.inc.php 
            class.bocompose.inc.php 
            auth.php 
            class.phpmailer.inc.php 
            class.smtp.php 
            display_messages.php 
            date.php 
            class.uicompose.inc.php 

Log Message:
cvs clean up

====================================================
Index: array.php
<?php
   /**
    **  array.php
    **
    **  This contains functions that work with array manipulation.  They
    **  will help sort, and do other types of things with arrays
    **
    **  $Id: array.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $
    **/

   $array_php = true;

   function ary_sort($ary,$col, $dir = 1){
      // The globals are used because USORT determines what is passed to comp2
      // These should be $this->col and $this->dir in a class
      // Would beat using globals
      if(!is_array($col)){
         $col = array($col);
      }
      $GLOBALS['col'] = $col;  // Column or Columns as an array
      if ($dir > 0)
          $dir = 1;
      else
          $dir = -1;
      $GLOBALS['dir'] = $dir;  // Direction, a positive number for ascending a 
negative for descending

      usort($ary,'array_comp2');
      return $ary;
  }

  function array_comp2($a,$b,$i = 0) {
         global $col;
         global $dir;
         $c = count($col) -1;
         if ($a[$col[$i]] == $b[$col[$i]]){
            $r = 0;
            while($i < $c && $r == 0){
               $i++;
               $r = comp2($a,$b,$i);
            }
         } elseif($a[$col[$i]] < $b[$col[$i]]){
            return (- $dir);
         }
         return $dir;
      }

   function removeElement($array, $element) {
      $j = 0;
      for ($i = 0;$i < count($array);$i++)
         if ($i != $element) {
            $newArray[$j] = $array[$i];
            $j++;
         }

      return $newArray;
   }

  function array_cleave($array1, $column)
  {
    $key=0;
    $array2 = array();
    while ($key < count($array1)) {
        array_push($array2, $array1[$key][$column]);
        $key++;
    }

    return ($array2);
  }

?>

====================================================
Index: smtp.php
<?php
   /** smtp.php
    **
    ** This contains all the functions needed to send messages through
    ** an smtp server or sendmail.
    **
    ** $Id: smtp.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $
    **/

   $smtp_php = true;

   // This should most probably go to some initialization...
   if (ereg("^(address@hidden/]+)address@hidden/](.+)$", $username, 
$usernamedata)) {
      $popuser = $usernamedata[1];
      $domain  = $usernamedata[2];
          unset($usernamedata);
   } else {
      $popuser = $username;
   }
   // We need domain for smtp
   if (!$domain)
      $domain = getenv('HOSTNAME');

   // Returns true only if this message is multipart
   function isMultipart () {
      global $attachments;

      if (count($attachments)>0)
         return true;
      else
         return false;
   }

   // Attach the files that are due to be attached
   function attachFiles ($fp) {
      global $attachments, $phpgw, $phpgw_info;

      $sep = $phpgw->common->filesystem_separator();
      $length = 0;

      if (isMultipart()) {
         reset($attachments);
         while (list($localname, $remotename) = each($attachments)) {
            // This is to make sure noone is giving a filename in another
            // directory
            $localname = ereg_replace ("\\/", '', $localname);

            $fileinfo = fopen ($phpgw_info["server"]["temp_dir"] . $sep . 
$localname.'.info', 'r');
            $filetype = fgets ($fileinfo, 8192);
            fclose ($fileinfo);
            $filetype = trim ($filetype);
            if ($filetype=='')
               $filetype = 'application/octet-stream';

            $header = '--'.mimeBoundary()."\r\n";
            $header .= "Content-Type: $filetype;name=\"$remotename\"\r\n";
            $header .= "Content-Disposition: attachment; 
filename=\"$remotename\"\r\n";
            $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
            fputs ($fp, $header);
            $length += strlen($header);

            $file = fopen ($phpgw_info["server"]["temp_dir"] . $sep . 
$localname, 'r');
            while ($tmp = fread($file, 570)) {
               $encoded = chunk_split(base64_encode($tmp));
               $length += strlen($encoded);
               fputs ($fp, $encoded);
            }
            fclose ($file);
         }
      }

      return $length;
   }

   // Delete files that are uploaded for attaching
   function deleteAttachments() {
      global $attachments, $phpgw, $phpgw_info;

      $sep = $phpgw->common->filesystem_separator();

      if (isMultipart()) {
         reset($attachments);
         while (list($localname, $remotename) = each($attachments)) {
            if (!ereg ("\\/", $localname)) {
               unlink ($phpgw_info["server"]["temp_dir"] . $sep . $localname);
               unlink ($phpgw_info["server"]["temp_dir"] . $sep . $localname . 
'.info');
            }
         }
      }
   }

   // Return a nice MIME-boundary
   function mimeBoundary () {
      static $mimeBoundaryString;

      if ($mimeBoundaryString == "") {
         $mimeBoundaryString = GenerateRandomString(70, '\'()+,-./:=?_', 7);
      }

      return $mimeBoundaryString;
   }

   /* Time offset for correct timezone */
   function timezone () {
      global $invert_time;

      $diff_second = date('Z');
      if ($invert_time)
          $diff_second = - $diff_second;
      if ($diff_second > 0)
         $sign = '+';
      else
         $sign = '-';

      $diff_second = abs($diff_second);

      $diff_hour = floor ($diff_second / 3600);
      $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);

      $zonename = '('.strftime('%Z').')';
      $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, 
$zonename);
      return ($result);
   }

   /* Print all the needed RFC822 headers */
   function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
      global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
      global $data_dir, $username, $popuser, $domain, $version, $useSendmail;
      global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
      global $REMOTE_HOST, $phpgw_info;

      // Storing the header to make sure the header is the same
      // everytime the header is printed.
      static $header, $headerlength;

      if ($header == '') {
         $to = parseAddrs($t);
         $cc = parseAddrs($c);
         $bcc = parseAddrs($b);
         $reply_to = $phpgw_info['user']['preferences']['email']["address"];
         $from = $phpgw_info['user']['fullname'];
         $from_addr = $phpgw_info['user']['preferences']['email']["address"];

         if ($from_addr == '')
            $from_addr = $popuser.'@'.$domain;

         $to_list = getLineOfAddrs($to);
         $cc_list = getLineOfAddrs($cc);
         $bcc_list = getLineOfAddrs($bcc);

         /* Encoding 8-bit characters and making from line */
         $subject = sqStripSlashes(encodeHeader($subject));
         if ($from == '')
            $from = "<$from_addr>";
         else
            $from = '"' . encodeHeader($from) . "\" <$from_addr>";

         /* This creates an RFC 822 date */
         $date = date("D, j M Y H:i:s ", mktime()) . timezone();

         /* Create a message-id */
         $message_id = '<' . $REMOTE_PORT . '.' . $REMOTE_ADDR . '.';
         $message_id .= time() . '.squirrel@' . $SERVER_NAME .'>';

         /* Make an RFC822 Received: line */
         if (isset($REMOTE_HOST))
            $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
         else
            $received_from = $REMOTE_ADDR;

         if (isset($HTTP_VIA) || isset ($HTTP_X_FORWARDED_FOR)) {
            if ($HTTP_X_FORWARDED_FOR == '')
               $HTTP_X_FORWARDED_FOR = 'unknown';
            $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
         }

         $header  = "Received: from $received_from\r\n";
         $header .= "        (SquirrelMail authenticated user $username)\r\n";
         $header .= "        by $SERVER_NAME with HTTP;\r\n";
         $header .= "        $date\r\n";

         /* Insert the rest of the header fields */
         $header .= "Message-ID: $message_id\r\n";
         $header .= "Date: $date\r\n";
         $header .= "Subject: $subject\r\n";
         $header .= "From: $from\r\n";
         $header .= "To: $to_list \r\n";    // Who it's TO

         /* Insert headers from the $more_headers array */
         if(is_array($more_headers)) {
            reset($more_headers);
            while(list($h_name, $h_val) = each($more_headers)) {
               $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
            }
         }

         if ($cc_list) {
            $header .= "Cc: $cc_list\r\n"; // Who the CCs are
         }

         if ($reply_to != '')
            $header .= "Reply-To: $reply_to\r\n";

         if ($useSendmail) {
            if ($bcc_list) {
               // BCCs is removed from header by sendmail
               $header .= "Bcc: $bcc_list\r\n";
            }
         }

         $header .= "X-Mailer: SquirrelMail for PHPGroupware (version 
$version)\r\n"; // Identify SquirrelMail

         // Do the MIME-stuff
         $header .= "MIME-Version: 1.0\r\n";

         if (isMultipart()) {
            $header .= 'Content-Type: multipart/mixed; boundary="';
            $header .= mimeBoundary();
            $header .= "\"\r\n";
         } else {
            if ($default_charset != '')
               $header .= "Content-Type: text/plain; 
charset=$default_charset\r\n";
            else
               $header .= "Content-Type: text/plain;\r\n";
            $header .= "Content-Transfer-Encoding: 8bit\r\n";
         }
         $header .= "\r\n"; // One blank line to separate header and body

         $headerlength = strlen($header);
      }

      // Write the header
      fputs ($fp, $header);

      return $headerlength;
   }

   // Send the body
   function writeBody ($fp, $passedBody) {
      global $default_charset;

      $attachmentlength = 0;

      if (isMultipart()) {
         $body = '--'.mimeBoundary()."\r\n";

         if ($default_charset != "")
            $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
         else
            $body .= "Content-Type: text/plain\r\n";

         $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
         $body .= sqStripSlashes($passedBody) . "\r\n\r\n";
         fputs ($fp, $body);

         $attachmentlength = attachFiles($fp);

         if (!isset($postbody)) $postbody = "";
         $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
         fputs ($fp, $postbody);
      } else {
         $body = sqStripSlashes($passedBody) . "\r\n";
         fputs ($fp, $body);
         $postbody = "\r\n";
         fputs ($fp, $postbody);
      }

      return (strlen($body) + strlen($postbody) + $attachmentlength);
   }

   // Send mail using the sendmail command
   function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
      global $sendmail_path, $popuser, $username, $domain;

      // Build envelope sender address. Make sure it doesn't contain
      // spaces or other "weird" chars that would allow a user to
      // exploit the shell/pipe it is used in.
      $envelopefrom = "address@hidden";
      $envelopefrom = ereg_replace("[[:blank:]]",'', $envelopefrom);
      $envelopefrom = ereg_replace("[[:space:]]",'', $envelopefrom);
      $envelopefrom = ereg_replace("[[:cntrl:]]",'', $envelopefrom);

      // open pipe to sendmail
      $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), 'w');

      $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
      $bodylength = writeBody($fp, $body);

      pclose($fp);

      return ($headerlength + $bodylength);
   }

   function smtpReadData($smtpConnection) {
      $read = fgets($smtpConnection, 1024);
      $counter = 0;
      while ($read) {
         echo $read . '<BR>';
         $data[$counter] = $read;
         $read = fgets($smtpConnection, 1024);
         $counter++;
      }
   }

        function sendSMTP($t, $c, $b, $subject, $body, $more_headers)
        {
                global $username, $popuser, $domain, $version, 
$smtpServerAddress, $smtpPort,
                $data_dir, $color, $phpgw_info;

      $to = parseAddrs($t);
      $cc = parseAddrs($c);
      $bcc = parseAddrs($b);

//address@hidden: added "" around username
      $from_addr = '"'.$phpgw_info["user"]["fullname"] . '"<' . 
$phpgw_info['user']['preferences']['email']["address"] . '>';
//
//address@hidden: impossible to reach ... $from_addr has just been set.
      if (!$from_addr)
         $from_addr = "address@hidden";

//address@hidden: alternative proposal for computing from_addr:
      $from_addr = $phpgw_info['user']['preferences']['email']["address"];
      if (!$from_addr)
         $from_addr = "address@hidden";
      if ($phpgw_info["user"]["fullname"])
         $from_addr = '"'.$phpgw_info["user"]["fullname"].'"<'.$from_addr.'>';

      $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, 
$errorString);
      if (!$smtpConnection) {
         echo 'Error connecting to SMTP Server.<br>';
         echo "$errorNumber : $errorString<br>";
         exit;
      }
      $tmp = fgets($smtpConnection, 1024);
      errorCheck($tmp, $smtpConnection);

      $to_list = getLineOfAddrs($to);
      $cc_list = getLineOfAddrs($cc);

      /** Lets introduce ourselves */
      fputs($smtpConnection, "HELO $domain\r\n");
      $tmp = fgets($smtpConnection, 1024);
      errorCheck($tmp, $smtpConnection);

      /** Ok, who is sending the message? */
      fputs($smtpConnection, "MAIL FROM: $from_addr \r\n");
      $tmp = fgets($smtpConnection, 1024);
      errorCheck($tmp, $smtpConnection);

      /** send who the recipients are */
      for ($i = 0; $i < count($to); $i++) {
//address@hidden: removed <> around 'to'
         fputs($smtpConnection, "RCPT TO: $to[$i] \r\n");
         $tmp = fgets($smtpConnection, 1024);
         errorCheck($tmp, $smtpConnection);
      }
      for ($i = 0; $i < count($cc); $i++) {
//address@hidden: removed <> around 'cc'
         fputs($smtpConnection, "RCPT TO: $cc[$i] \r\n");
         $tmp = fgets($smtpConnection, 1024);
         errorCheck($tmp, $smtpConnection);
      }
      for ($i = 0; $i < count($bcc); $i++) {
//address@hidden: removed <> around 'bcc'
         fputs($smtpConnection, "RCPT TO: $bcc[$i] \r\n");
         $tmp = fgets($smtpConnection, 1024);
         errorCheck($tmp, $smtpConnection);
      }

      /** Lets start sending the actual message */
      fputs($smtpConnection, "DATA\r\n");
      $tmp = fgets($smtpConnection, 1024);
      errorCheck($tmp, $smtpConnection);

      // Send the message
      $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, 
$more_headers);
      $bodylength = writeBody($smtpConnection, $body);

      fputs($smtpConnection, ".\r\n"); // end the DATA part
      $tmp = fgets($smtpConnection, 1024);
      $num = errorCheck($tmp, $smtpConnection);

                if ($num != 250)
                {
                        $tmp = nl2br(htmlspecialchars($tmp));
                        echo "ERROR<BR>Message not sent!<BR>Reason given: 
$tmp<BR></BODY></HTML>";
                }

      fputs($smtpConnection, "QUIT\r\n"); // log off

      fclose($smtpConnection);

      return ($headerlength + $bodylength);
   }


   function errorCheck($line, $smtpConnection) {
      global $page_header_php;
      global $color;
      if (!isset($page_header_php)) {
         include (PHPGW_APP_ROOT . '/inc/page_header.php');
      }

      // Read new lines on a multiline response
      $lines = $line;
      while(ereg("^[0-9]+-", $line)) {
         $line = fgets($smtpConnection, 1024);
         $lines .= $line;
      }

      // Status:  0 = fatal
      //          5 = ok

      $err_num = substr($line, 0, strpos($line, " "));
      switch ($err_num) {
         case 500:   $message = 'Syntax error; command not recognized';
                     $status = 0;
                     break;
         case 501:   $message = 'Syntax error in parameters or arguments';
                     $status = 0;
                     break;
         case 502:   $message = 'Command not implemented';
                     $status = 0;
                     break;
         case 503:   $message = 'Bad sequence of commands';
                     $status = 0;
                     break;
         case 504:   $message = 'Command parameter not implemented';
                     $status = 0;
                     break;


         case 211:   $message = 'System status, or system help reply';
                     $status = 5;
                     break;
         case 214:   $message = 'Help message';
                     $status = 5;
                     break;


         case 220:   $message = 'Service ready';
                     $status = 5;
                     break;
         case 221:   $message = 'Service closing transmission channel';
                     $status = 5;
                     break;
         case 421:   $message = 'Service not available, closing chanel';
                     $status = 0;
                     break;


         case 250:   $message = 'Requested mail action okay, completed';
                     $status = 5;
                     break;
         case 251:   $message = 'User not local; will forward';
                     $status = 5;
                     break;
         case 450:   $message = 'Requested mail action not taken:  mailbox 
unavailable';
                     $status = 0;
                     break;
         case 550:   $message = 'Requested action not taken:  mailbox 
unavailable';
                     $status = 0;
                     break;
         case 451:   $message = 'Requested action aborted:  error in 
processing';
                     $status = 0;
                     break;
         case 551:   $message = 'User not local; please try forwarding';
                     $status = 0;
                     break;
         case 452:   $message = 'Requested action not taken:  insufficient 
system storage';
                     $status = 0;
                     break;
         case 552:   $message = 'Requested mail action aborted:  exceeding 
storage allocation';
                     $status = 0;
                     break;
         case 553:   $message = 'Requested action not taken: mailbox name not 
allowed';
                     $status = 0;
                     break;
         case 354:   $message = 'Start mail input; end with .';
                     $status = 5;
                     break;
         case 554:   $message = 'Transaction failed';
                     $status = 0;
                     break;
         default:    $message = 'Unknown response: '. 
nl2br(htmlspecialchars($lines));
                     $status = 0;
                     $error_num = '001';
                     break;
      }

      if ($status == 0) {
        global $phpgw;
                        $phpgw->common->phpgw_header();
                        echo parse_navbar();
//address@hidden: 27.6.2001
         //displayPageHeader($imapConnection, $color, 'None');
         displayPageHeader($color, 'None');
         echo '<TT>';
         echo "<br><b><font color=\"$color[1]\">ERROR</font></b><br><br>";
         echo "&nbsp;&nbsp;&nbsp;<B>Error Number: </B>$err_num<BR>";
         echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Reason: 
</B>$message<BR>";
         $lines = nl2br(htmlspecialchars($lines));
         echo "<B>Server Response: </B>$lines<BR>";
         echo '<BR>MAIL NOT SENT';
         echo '</TT></BODY></HTML>';
         $phpgw->common->phpgw_exit(True);
      }
      return $err_num;
   }

   function sendMessage($t, $c, $b, $subject, $body, $reply_id) {
      global $useSendmail, $msg_id, $is_reply, $mailbox;
      global $data_dir, $username, $domain, $key, $version, $sent_folder, 
$imapServerAddress, $imapPort;
      $more_headers = Array();

      $imap_stream = sqimap_login($username, $key, $imapServerAddress, 
$imapPort, 1);

      if ($reply_id = trim($reply_id)) {
         sqimap_mailbox_select ($imap_stream, $mailbox);
         sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, 'Answered');

         // Insert In-Reply-To and References headers if the
         // message-id of the message we reply to is set (longer than "<>")
         // The References header should really be the old Referenced header
         // with the message ID appended, but it can be only the message ID too.
         $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
         if(strlen($hdr->message_id) > 2) {
            $more_headers['In-Reply-To'] = $hdr->message_id;
            $more_headers['References']  = $hdr->message_id;
         }
      }

      // In order to remove the problem of users not able to create
          // messages with "." on a blank line, RFC821 has made provision
          // in section 4.5.2 (Transparency).
          $body = ereg_replace("\n\.", "\n\.\.", $body);
          $body = ereg_replace("^\.", "\.\.", $body);

      // this is to catch all plain \n instances and
      // replace them with \r\n.
      $body = ereg_replace("\r\n", "\n", $body);
      $body = ereg_replace("\n", "\r\n", $body);

      if ($useSendmail) {
         $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
      } else {
         $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
      }

      $sent_folder = trim($sent_folder);
      if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
         sqimap_append ($imap_stream, $sent_folder, $length);
         write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
         writeBody ($imap_stream, $body);
         sqimap_append_done ($imap_stream);
      }
      sqimap_logout($imap_stream);
      // Delete the files uploaded for attaching (if any).
      deleteAttachments();
   }

?>

====================================================
Index: prefs.php
<?php
   /**
    **  prefs.php
    **
    **  This contains functions for manipulating user preferences
    **
    **  $Id: prefs.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $
    **/

   $prefs_php = true;

   /** returns the value for $string **/
   function getPref($data_dir, $username, $string)
   {
      global $phpgw;
      return True;

      $filename = "$data_dir$username.pref";
      if (!file_exists($filename)) {
         printf (lang("Preference file %1 not found. Exiting abnormally"), 
$filename);
         $phpgw->common->phpgw_exit(True);
      }

      $file = fopen($filename, "r");

      /** read in all the preferences **/
      for ($i=0; !feof($file); $i++) {
         $pref = fgets($file, 1024);
         if (substr($pref, 0, strpos($pref, "=")) == $string) {
            fclose($file);
            return trim(substr($pref, strpos($pref, "=")+1));
         }
      }
      fclose($file);
      return "";
   }

   function removePref($data_dir, $username, $string) {
        return True;
      $filename = "$data_dir$username.pref";
      $found = false;
      if (!file_exists($filename)) {
         printf (lang("Preference file, %1, does not exist. Log out, and log 
back in to create a default preference file."), $filename);
         echo "<br>\n";
         exit;
      }
      $file = fopen($filename, "r");

      for ($i=0; !feof($file); $i++) {
         $pref[$i] = fgets($file, 1024);
         if (substr($pref[$i], 0, strpos($pref[$i], "=")) == $string) {
            $i--;
         }
      }
      fclose($file);

      for ($i=0,$j=0; $i < count($pref); $i++) {
         if (substr($pref[$i], 0, 9) == "highlight") {
            $hlt[$j] = substr($pref[$i], strpos($pref[$i], "=")+1);
            $j++;
         }
      }

      $file = fopen($filename, "w");
      for ($i=0; $i < count($pref); $i++) {
         if (substr($pref[$i], 0, 9) != "highlight") {
            fwrite($file, "$pref[$i]", 1024);
         }
      }
      if (isset($htl)) {
         for ($i=0; $i < count($hlt); $i++) {
            fwrite($file, "highlight$i=$hlt[$i]");
         }
      }
      fclose($file);
   }

   /** sets the pref, $string, to $set_to **/
   function setPref($data_dir, $username, $string, $set_to) {
        return True;
      $filename = "$data_dir$username.pref";
      $found = false;
      if (!file_exists($filename)) {
         printf (lang("Preference file, %1, does not exist. Log out, and log 
back in to create a default preference file."), $filename);
         echo "\n<br>\n";
         exit;
      }
      $file = fopen($filename, "r");

      /** read in all the preferences **/
      for ($i=0; !feof($file); $i++) {
         $pref[$i] = fgets($file, 1024);
         if (substr($pref[$i], 0, strpos($pref[$i], "=")) == $string) {
            $found = true;
            $pos = $i;
         }
      }
      fclose($file);

      $file = fopen($filename, "w");
      if ($found == true) {
         for ($i=0; $i < count($pref); $i++) {
            if ($i == $pos) {
               fwrite($file, "$string=$set_to\n", 1024);
            } else {
               fwrite($file, "$pref[$i]", 1024);
            }
         }
      } else {
         for ($i=0; $i < count($pref); $i++) {
            fwrite($file, "$pref[$i]", 1024);
         }
         fwrite($file, "$string=$set_to\n", 1024);
      }

      fclose($file);
   }




   /** This checks if there is a pref file, if there isn't, it will
       create it. **/
   function checkForPrefs($data_dir, $username) {
        return True;
      $filename = "$data_dir$username.pref";
      if (!file_exists($filename)) {
         if (!copy("$data_dir" . "default_pref", $filename)) {
            echo lang("Error opening ") ."$filename";
            exit;
         }
      }
   }

?>

====================================================
Index: plugin.php
<?php

/**
 ** plugin.php
 **
 ** This file provides the framework for a plugin architecture.
 **
 ** Plugins will eventually be a way to provide added functionality
 ** without having to patch the SquirrelMail source code. Have some
 ** patience, though, as the these funtions might change in the near
 ** future.
 **
 ** Documentation on how to write plugins might show up some time.
 **
 ** $Id: plugin.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $
 **/


   $plugin_php = true;

   // This function adds a plugin
   function use_plugin ($name) {
      $f_setup = PHPGW_APP_ROOT . '/plugins/'.$name.'/setup.php';
      if (file_exists($f_setup)) {
         include ($f_setup);
         $function = 'squirrelmail_plugin_init_'.$name;
         if (function_exists($function)) {
            $function();
         }
      }
   }

   // This function executes a hook
   function do_hook ($name) {
      global $squirrelmail_plugin_hooks;
      $Data = func_get_args();
      if (isset($squirrelmail_plugin_hooks[$name]) &&
          is_array($squirrelmail_plugin_hooks[$name])) {
         foreach ($squirrelmail_plugin_hooks[$name] as $id => $function) {
            // Add something to set correct gettext domain for plugin
            if (function_exists($function)) {
                $function($Data);
            }
         }
      }

      // Variable-length argument lists have a slight problem when
      // passing values by reference.  Pity.  This is a workaround.
      return $Data;
  }

   // On startup, register all plugins configured for use
   if (isset($plugins) && is_array($plugins))
      foreach ($plugins as $id => $name)
         use_plugin($name);

?>

====================================================
Index: page_header.php
<?php
   /**
    **  page_header.php
    **
    **  Prints the page header (duh)
    **
    **  $Id: page_header.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $
    **/

        $page_header_php = true;

        if (!isset($prefs_php))
        {
                include(PHPGW_APP_ROOT . '/inc/prefs.php');
        }

        if (!isset($i18n_php))
        {
                include(PHPGW_APP_ROOT . '/inc/i18n.php');
        }

        if (!isset($plugin_php))
        {
                include(PHPGW_APP_ROOT . '/inc/plugin.php');
        }

        // Check to see if gettext is installed
        set_up_language(getPref($data_dir, $username, "language"));
        // This is done to ensure that the character set is correct.

        function displayHtmlHeader ($title="SquirrelMail")
        {
                global $theme_css;

                echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 
Transitional//EN">';
                echo "\n\n";
                echo "<HTML>\n";
                echo "<HEAD>\n";

                if ($theme_css != "")
                {
                        printf ('<LINK REL="stylesheet" TYPE="text/css" 
HREF="%s">',$theme_css);
                        echo "\n";
                }

                do_hook ("generic_header");

                echo "<TITLE>$title</TITLE>\n";
                echo "</HEAD>\n\n";
        }

        function displayInternalLink ($path, $extra_vars, $text, $target="")
        {
                global $phpgw, $phpgw_info;

                if ($target != "")
                        $target = " target=\"$target\"";

                echo '<a href="'. $phpgw->link('/squirrelmail/' . 
$path,$extra_vars) . '"'.$target.'>'.$text.'</a>';
        }

        function displayPageHeader($color, $mailbox)
        {
                global $phpgw, $boxes;
                global $imapConnection;

                #displayHtmlHeader ();

                #printf('<BODY TEXT="%s" BGCOLOR="%s" LINK="%s" VLINK="%s" 
ALINK="%s">',
                #       $color[8], $color[4], $color[7], $color[7], $color[7]);
                #echo "\n\n";

                /** Here is the header and wrapping table **/
                $shortBoxName = readShortMailboxName($mailbox, ".");
                $shortBoxName = sqStripSlashes($shortBoxName);

                echo "<A NAME=pagetop></A>\n";
                echo "<TABLE BGCOLOR=\"$color[4]\" BORDER=0 WIDTH=\"100%\" 
CELLSPACING=0 CELLPADDING=2>\n";
                echo "   <TR BGCOLOR=\"$color[9]\">\n";
                echo "      <TD ALIGN=left WIDTH=\"30%\">\n";

                $urlMailbox = urlencode($mailbox);
                #displayInternalLink ("compose.php","mailbox=$urlMailbox", 
lang("Compose"));
                #print "(old)";
                $linkData = array
                (
                        'menuaction'    => 'squirrelmail.uicompose.compose',
                        'mailbox'       => $urlMailbox
                );
                printf("&nbsp;<a 
href=\"%s\">%s</a>",$phpgw->link('/index.php',$linkData),lang("Compose"));

                echo "&nbsp;&nbsp;\n";
                //address@hidden: enabled with changes in move_messages
                displayInternalLink ("search.php","mailbox=$urlMailbox", 
lang("Search"));
                echo "&nbsp;&nbsp;\n";
#               displayInternalLink ("src/help.php","", lang("Help"));
                echo "&nbsp;&nbsp;\n";
                echo "      </b></TD>\n";

                // Folder list
                echo "\n\n\n<FORM name=folderList method=post 
action=\"".$phpgw->link("/squirrelmail/index.php")."\">\n";
                echo "      <TD WIDTH=40% ALIGN=RIGHT VALIGN=CENTER>\n";
                echo '         <TT><SELECT NAME="mailbox" 
onChange="document.folderList.submit()">'."\n";

//address@hidden: there are cases where boxes is not an array
                if (!is_array($boxes)) {
                        if (!isset($imapConnection))  {
                                if (!isset($config_php))
                                {
                                        include(PHPGW_APP_ROOT . 
'/config/config.php');
                                }
                                $key      = 
$phpgw_info['user']['preferences']['email']['passwd'];
                                $username = 
$phpgw_info['user']['preferences']['email']['userid'];

                                $imapConnection = sqimap_login($username, $key,
                                        $imapServerAddress, $imapPort, 0);
                        }
                        $boxes = sqimap_mailbox_list($imapConnection);
                        $phpgw->session->register("boxes");
                }
                reset($boxes);
                for ($i = 0; $i < count($boxes); $i++)
                {
                        if (!in_array("noselect", $boxes[$i]["flags"]))
                        {
                                $box = $boxes[$i]['unformatted'];
                                $box2 = 
replace_spaces($boxes[$i]['unformatted-disp']);
                                echo "         <OPTION VALUE=\"$box\"";
                                if($box==$mailbox)
                                {
                                        echo "selected";
                                }
                                echo ">$box2</option>\n";
                        }
                }
                echo '         </SELECT></TT>'."\n";
                echo '         <INPUT TYPE=HIDDEN NAME="startMessage" 
VALUE="1">'."\n";
#               echo '         <INPUT TYPE=HIDDEN NAME="newsort" 
VALUE="0">'."\n";
                echo '         <noscript>';
                echo '         <SMALL><INPUT TYPE=SUBMIT NAME="GoButton" 
VALUE="'. lang("Select") ."\"></SMALL></NOBR>\n";
                echo '         </noscript>';
                echo "      </TD>\n";
                echo "</FORM>\n";

                echo "   </TR>\n";
                echo "</TABLE>\n\n";

#               echo "<TABLE BGCOLOR=\"$color[4]\" BORDER=0 WIDTH=\"100%\" 
CELLSPACING=0 CELLPADDING=2>\n";
#               echo "   <TR>\n";
#               echo "      <TD ALIGN=left WIDTH=\"99%\">\n";
#
#               do_hook("menuline");
#
#               echo "      </TD><TD ALIGN=right nowrap WIDTH=\"1%\">\n";
#               echo "         <A HREF=\"http://www.squirrelmail.org/\"; 
TARGET=\"_top\">SquirrelMail</A>\n";
#               echo "      </TD>\n";
#               echo "   </TR>\n";
#               echo "</TABLE>\n\n";
        }
?>

====================================================
Index: strings.php
<?php

   /* $Id: strings.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $ */

   $strings_php = true;

   //*************************************************************************
   // Count the number of occurances of $needle are in $haystack.
   // $needle can be a character or string, and need not occur in $haystack
   //*************************************************************************
   function countCharInString($haystack, $needle) {
      if ($needle == '') return 0;
      return count(explode($needle, $haystack));
   }

   //*************************************************************************
   // Read from the back of $haystack until $needle is found, or the begining
   //    of the $haystack is reached.  $needle is a single character
   //*************************************************************************
   function readShortMailboxName($haystack, $needle) {
      if ($needle == '') return $haystack;
      $parts = explode($needle, $haystack);
      $elem = array_pop($parts);
      while ($elem == '' && count($parts))
      {
          $elem = array_pop($parts);
      }
      return $elem;
   }

   //*************************************************************************
   // Read from the back of $haystack until $needle is found, or the begining
   //    of the $haystack is reached.  $needle is a single character
   //*************************************************************************
   function readMailboxParent($haystack, $needle) {
      if ($needle == '') return '';
      $parts = explode($needle, $haystack);
      $elem = array_pop($parts);
      while ($elem == '' && count($parts))
      {
          $elem = array_pop($parts);
      }
      return join($needle, $parts);
   }

   // Searches for the next position in a string minus white space
   function next_pos_minus_white ($haystack, $pos) {
      while (substr($haystack, $pos, 1) == ' ' ||
             substr($haystack, $pos, 1) == "\t" ||
             substr($haystack, $pos, 1) == "\n" ||
             substr($haystack, $pos, 1) == "\r") {
         if ($pos >= strlen($haystack))
            return -1;
         $pos++;
      }
      return $pos;
   }

   // Wraps text at $wrap characters
   // Has a problem with special HTML characters, so call this before
   // you do character translation.
   // Specifically, &#039 comes up as 5 characters instead of 1.
   // This should not add newlines to the end of lines.
   function sqWordWrap(&$line, $wrap) {
      preg_match('/^([\\s>]*)([^\\s>].*)?$/', $line, $regs);
      $beginning_spaces = $regs[1];
          if (isset($regs[2])) {
         $words = explode(' ', $regs[2]);
      } else {
         $words = "";
          }

      $i = 0;
      $line = $beginning_spaces;

      while ($i < count($words)) {
         // Force one word to be on a line (minimum)
         $line .= $words[$i];
         $line_len = strlen($beginning_spaces) + strlen($words[$i]) + 2;
         if (isset($words[$i + 1]))
             $line_len += strlen($words[$i + 1]);
         $i ++;

         // Add more words (as long as they fit)
         while ($line_len < $wrap && $i < count($words)) {
            $line .= ' ' . $words[$i];
            $i++;
            if (isset($words[$i]))
                $line_len += strlen($words[$i]) + 1;
            else
                $line_len += 1;
         }

         // Skip spaces if they are the first thing on a continued line
         while (!isset($words[$i]) && $i < count($words)) {
            $i ++;
         }

         // Go to the next line if we have more to process
         if ($i < count($words)) {
            $line .= "\n" . $beginning_spaces;
         }
      }
   }


   // Does the opposite of sqWordWrap()
   function sqUnWordWrap(&$body)
   {
       $lines = explode("\n", $body);
       $body = "";
       $PreviousSpaces = "";
       for ($i = 0; $i < count($lines); $i ++)
       {
           preg_match('/^([\\s>]*)([^\\s>].*)?$/', $lines[$i], $regs);
           $CurrentSpaces = $regs[1];
           if (isset($regs[2]))
               $CurrentRest = $regs[2];
           if ($i == 0)
           {
               $PreviousSpaces = $CurrentSpaces;
               $body = $lines[$i];
           }
           else if ($PreviousSpaces == $CurrentSpaces &&  // Do the beginnings 
match
               strlen($lines[$i - 1]) > 65 &&             // Over 65 characters 
long
               strlen($CurrentRest))                      // and there's a line 
to continue with
           {
               $body .= ' ' . $CurrentRest;
           }
           else
           {
               $body .= "\n" . $lines[$i];
               $PreviousSpaces = $CurrentSpaces;
           }
       }
       $body .= "\n";
   }


   /** Returns an array of email addresses **/
   /* Be cautious of "address@hidden" */
   function parseAddrs($text) {
      if (trim($text) == "")
         return array();
      $text = str_replace(' ', '', $text);
      $text = ereg_replace('"[^"]*"', '', $text);
      $text = ereg_replace('\\([^\\)]*\\)', '', $text);
      $text = str_replace(',', ';', $text);
      $array = explode(';', $text);
      for ($i = 0; $i < count ($array); $i++) {
                            $array[$i] = eregi_replace ("^.*[<]", '', 
$array[$i]);
                            $array[$i] = eregi_replace ("[>].*$", '', 
$array[$i]);
                  }
      return $array;
   }

   /** Returns a line of comma separated email addresses from an array **/
   function getLineOfAddrs($array) {
      if (is_array($array)) {
        $to_line = implode(', ', $array);
        $to_line = trim(ereg_replace(',,+', ',', $to_line));
      } else {
        $to_line = '';
      }
      return $to_line;
   }

   function translateText(&$body, $wrap_at, $charset) {
      global $where, $what; // from searching
                global $url_parser_php;

      if (!isset($url_parser_php)) {
         include (PHPGW_APP_ROOT .'/inc/url_parser.php');
      }

      $body_ary = explode("\n", $body);
      $PriorQuotes = 0;
      for ($i=0; $i < count($body_ary); $i++) {
         $line = $body_ary[$i];
         if (strlen($line) - 2 >= $wrap_at) {
            sqWordWrap($line, $wrap_at);
         }
         $line = charset_decode($charset, $line);
         $line = str_replace("\t", '        ', $line);

         parseUrl ($line);

         $Quotes = 0;
         $pos = 0;
         while (1)
         {
             if ($line[$pos] == ' ')
             {
                $pos ++;
             }
             else if (strpos($line, '&gt;', $pos) === $pos)
             {
                $pos += 4;
                $Quotes ++;
             }
             else
             {
                 break;
             }
         }

         if ($Quotes > 1)
            $line = '<FONT COLOR="FF0000">'.$line.'</FONT>';
         elseif ($Quotes)
            $line = '<FONT COLOR="800000">'.$line.'</FONT>';

         $body_ary[$i] = $line;
      }
      $body = '<pre>' . implode("\n", $body_ary) . '</pre>';
   }

   /* SquirrelMail version number -- DO NOT CHANGE */
   $version = '1.0.1';


   function find_mailbox_name ($mailbox) {
      if (ereg(" *\"([^\r\n\"]*)\"[ \r\n]*$", $mailbox, $regs))
          return $regs[1];
      ereg(" *([^ \r\n\"]*)[ \r\n]*$",$mailbox,$regs);
      return $regs[1];

   }

   function replace_spaces ($string) {
      return str_replace(' ', '&nbsp;', $string);
   }

   function replace_escaped_spaces ($string) {
      return str_replace('&nbsp;', ' ', $string);
   }

   function get_location () {
      # This determines the location to forward to relative
      # to your server.  If this doesnt work correctly for
      # you (although it should), you can remove all this
      # code except the last two lines, and change the header()
      # function to look something like this, customized to
      # the location of SquirrelMail on your server:
      #
      #   http://www.myhost.com/squirrelmail/src/login.php

      global $PHP_SELF, $SERVER_NAME, $HTTPS, $HTTP_HOST, $SERVER_PORT;

      // Get the path
      $path = substr($PHP_SELF, 0, strrpos($PHP_SELF, '/'));

      // Check if this is a HTTPS or regular HTTP request
      $proto = 'http://';
      if(isset($HTTPS) && !strcasecmp($HTTPS, 'on') ) {
        $proto = 'https://';
      }

      // Get the hostname from the Host header or server config.
      $host = '';
      if (isset($HTTP_HOST) && !empty($HTTP_HOST))
      {
          $host = $HTTP_HOST;
      }
      else if (isset($SERVER_NAME) && !empty($SERVER_NAME))
      {
          $host = $SERVER_NAME;
      }

      $port = '';
      if (! strstr($host, ':'))
      {
          if (isset($SERVER_PORT)) {
              if (($SERVER_PORT != 80 && $proto == 'http://')
                      || ($SERVER_PORT != 443 && $proto == 'https://')) {
                  $port = sprintf(':%d', $SERVER_PORT);
              }
          }
      }

      if ($host)
          return $proto . $host . $port . $path;

      // Fallback is to omit the server name and use a relative URI,
      // although this is not RFC 2616 compliant.
      return $path;
   }

   function sqStripSlashes($string) {
      if (get_magic_quotes_gpc()) {
         $string = stripslashes($string);
      }
      return $string;
   }


   // These functions are used to encrypt the passowrd before it is
   // stored in a cookie.
   function OneTimePadEncrypt ($string, $epad) {
      $pad = base64_decode($epad);
      $encrypted = '';
      for ($i = 0; $i < strlen ($string); $i++) {
         $encrypted .= chr (ord($string[$i]) ^ ord($pad[$i]));
      }

      return base64_encode($encrypted);
   }

   function OneTimePadDecrypt ($string, $epad) {
      $pad = base64_decode($epad);
      $encrypted = base64_decode ($string);
      $decrypted = '';
      for ($i = 0; $i < strlen ($encrypted); $i++) {
         $decrypted .= chr (ord($encrypted[$i]) ^ ord($pad[$i]));
      }

      return $decrypted;
   }


   // Randomize the mt_rand() function.  Toss this in strings or
   // integers and it will seed the generator appropriately.
   // With strings, it is better to get them long. Use md5() to
   // lengthen smaller strings.
   function sq_mt_seed($Val)
   {
       // if mt_getrandmax() does not return a 2^n - 1 number,
       // this might not work well.  This uses $Max as a bitmask.
       $Max = mt_getrandmax();

       if (! is_int($Val))
       {
           if (function_exists('crc32'))
           {
               $Val = crc32($Val);
           }
           else
           {
               $Str = $Val;
               $Pos = 0;
               $Val = 0;
               $Mask = $Max / 2;
               $HighBit = $Max ^ $Mask;
               while ($Pos < strlen($Str))
               {
                   if ($Val & $HighBit)
                   {
                       $Val = (($Val & $Mask) << 1) + 1;
                   }
                   else
                   {
                       $Val = ($Val & $Mask) << 1;
                   }
                   $Val ^= $Str[$Pos];
                   $Pos ++;
               }
           }
       }

       if ($Val < 0)
         $Val *= -1;
       if ($Val = 0)
         return;

       mt_srand(($Val ^ mt_rand(0, $Max)) & $Max);
   }


   // This function initializes the random number generator fairly well.
   // It also only initializes it once, so you don't accidentally get
   // the same 'random' numbers twice in one session.
   function sq_mt_randomize()
   {
      global $REMOTE_PORT, $REMOTE_ADDR, $UNIQUE_ID;
      static $randomized;

      if ($randomized)
         return;

      // Global
      sq_mt_seed((int)((double) microtime() * 1000000));
      sq_mt_seed(md5($REMOTE_PORT . $REMOTE_ADDR . getmypid()));

      // getrusage
      if (function_exists('getrusage')) {
         $dat = getrusage();
         $Str = '';
         foreach ($dat as $k => $v)
         {
             $Str .= $k . $v;
         }
         sq_mt_seed(md5($Str));
      }

      // Apache-specific
      sq_mt_seed(md5($UNIQUE_ID));

      $randomized = 1;
   }

   function OneTimePadCreate ($length=100) {
      sq_mt_randomize();

      $pad = '';
      for ($i = 0; $i < $length; $i++) {
         $pad .= chr(mt_rand(0,255));
      }

      return base64_encode($pad);
   }

   // Check if we have a required PHP-version. Return TRUE if we do,
   // or FALSE if we don't.
   // To check for 4.0.1, use sqCheckPHPVersion(4,0,1)
   // To check for 4.0b3, use sqCheckPHPVersion(4,0,-3)
   // Does not handle betas like 4.0.1b1 or development versions
   function sqCheckPHPVersion($major, $minor, $release) {

      $ver = phpversion();
      eregi('^([0-9]+)\\.([0-9]+)(.*)', $ver, $regs);

      // Parse the version string
      $vmajor  = strval($regs[1]);
      $vminor  = strval($regs[2]);
      $vrel    = $regs[3];
      if($vrel[0] == ".")
         $vrel = strval(substr($vrel, 1));
      if($vrel[0] == 'b' || $vrel[0] == 'B')
         $vrel = - strval(substr($vrel, 1));
      if($vrel[0] == 'r' || $vrel[0] == 'R')
         $vrel = - strval(substr($vrel, 2))/10;

      // Compare major version
      if($vmajor < $major) return false;
      if($vmajor > $major) return true;

      // Major is the same. Compare minor
      if($vminor < $minor) return false;
      if($vminor > $minor) return true;

      // Major and minor is the same as the required one.
      // Compare release
      if($vrel >= 0 && $release >= 0) {       // Neither are beta
         if($vrel < $release) return false;
      } else if($vrel >= 0 && $release < 0){  // This is not beta, required is 
beta
         return true;
      } else if($vrel < 0 && $release >= 0){  // This is beta, require not beta
         return false;
      } else {                                // Both are beta
         if($vrel > $release) return false;
      }

      return true;
   }

   /* Returns a string showing the size of the message/attachment */
   function show_readable_size($bytes)
   {
       $bytes /= 1024;
       $type = 'k';

       if ($bytes / 1024 > 1)
       {
           $bytes /= 1024;
           $type = 'm';
       }

       if ($bytes < 10)
       {
           $bytes *= 10;
           settype($bytes, 'integer');
           $bytes /= 10;
       }
       else
           settype($bytes, 'integer');

       return $bytes . '<small>&nbsp;' . $type . '</small>';
   }

   /* Generates a random string from the caracter set you pass in
    *
    * Flags:
    *   1 = add lowercase a-z to $chars
    *   2 = add uppercase A-Z to $chars
    *   4 = add numbers 0-9 to $chars
    */

   function GenerateRandomString($size, $chars, $flags = 0)
   {
      if ($flags & 0x1)
          $chars .= 'abcdefghijklmnopqrstuvwxyz';
      if ($flags & 0x2)
          $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      if ($flags & 0x4)
          $chars .= '0123456789';

      if ($size < 1 || strlen($chars) < 1)
          return '';

      sq_mt_randomize(); // Initialize the random number generator

          $String = "";
      while (strlen($String) < $size) {
         $String .= $chars[mt_rand(0, strlen($chars))];
      }

      return $String;
   }

?>

====================================================
Index: translate_setup.php
<?php

$translate_setup = 1;

/* Easy plugin that sends the body of the message to a new browser
window using the specified translator.  It can also translate your
outgoing message if you send it to someone in a different country.

  Languages from i18n, incorporated in the auto-language selection:
    en - English
    no - Norwegian (Bokm&aring;l)
    no_NO_ny - Norwegian (Nynorsk)
    de - Deutsch
    ru - Russian KOI8-R
    pl - Polish
    sv - Swedish
    nl - Dutch
    pt_BR - Portuguese (Brazil)
    fr - French
    it - Italian
    cs - Czech
    es - Spanish
    ko - Korean
*/


/* Initialize the translation plugin */
/*
function squirrelmail_plugin_init_translate()
{
  global $squirrelmail_plugin_hooks;

  $squirrelmail_plugin_hooks['read_body_bottom']['translate'] = 
'translate_read_form';
  $squirrelmail_plugin_hooks['options_link_and_description']['translate'] = 
'translate_opt';
  $squirrelmail_plugin_hooks['options_save']['translate'] = 'translate_sav';
  $squirrelmail_plugin_hooks['loading_prefs']['translate'] = 'translate_pref';
  $squirrelmail_plugin_hooks['compose_button_row']['translate'] = 
'translate_button';
}
*/


/* Show the translation for a message you're reading */
function translate_read_form()
{
  global $color, $translate_server;
  global $body, $translate_dir;
  global $translate_show_read;

  global $phpgw_info;
  $translate_server = 
$phpgw_info["user"]["preferences"]["squirrelmail"]["translate_server"];
  $translate_location = 
$phpgw_info["user"]["preferences"]["squirrelmail"]["translate_location"];
  $translate_show_read = 
$phpgw_info["user"]["preferences"]["squirrelmail"]["translate_show_read"];
  //$translate_show_send = 
$phpgw_info["user"]["preferences"]["squirrelmail"]["translate_show_send"];
  //$translate_same_window = 
$phpgw_info["user"]["preferences"]["squirrelmail"]["translate_same_window"];

  if (! $translate_show_read)
    return;

  $translate_dir = 'to';

  $new_body = $body;
  $pos = strpos($new_body,
    '">Download this as a file</A></CENTER><BR></SMALL>');
  if (is_int($pos))
  {
    $new_body = substr($new_body, 0, $pos);
  }

  $trans = get_html_translation_table('HTMLENTITIES');
  $trans[' '] = '&nbsp;';
  $trans = array_flip($trans);
  $new_body = strtr($new_body, $trans);

  $new_body = urldecode($new_body);
  $new_body = strip_tags($new_body);

  /* I really don't like this next part ... */
  $new_body = str_replace('"', "''", $new_body);
  $new_body = strtr($new_body, "\n", ' ');

  $function = 'translate_form_' . $translate_server;
  $function($new_body);
}

function translate_table_end()
{
  ?></td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
  </form>
  <?PHP
}


function translate_button()
{
  global $translate_show_send;

  if (! $translate_show_send)
    return;

  //echo "Button";
}


function translate_opt()
{
  global $color;

  ?>
  <table width=50% cellpadding=3 cellspacing=0 border=0 align=center>
  <tr>
     <td bgcolor="<?PHP
       echo $color[9]
     ?>">
       <a href="../plugins/translate/options.php">Translations</a>
     </td>
  </tr>
  <tr>
     <td bgcolor="<?PHP
       echo $color[0]
     ?>">
        Which translator should be used when you get messages in
        a different language?
     </td>
  </tr>
  </table>
  <?PHP
}

function translate_sav()
{
  global $username,$data_dir;
  global $submit_translate, $translate_translate_server;
  global $translate_translate_location;
  global $translate_translate_show_read;
  global $translate_translate_show_send;
  global $translate_translate_same_window;

  if ($submit_translate)
  {
    if (isset($translate_translate_server))
    {
      setPref($data_dir, $username, 'translate_server', 
$translate_translate_server);
    }
    else
    {
      setPref($data_dir, $username, 'translate_server', 'babelfish');
    }

    if (isset($translate_translate_location))
    {
      setPref($data_dir, $username, 'translate_location', 
$translate_translate_location);
    }
    else
    {
      setPref($data_dir, $username, 'translate_location', 'center');
    }

    if (isset($translate_translate_show_read))
    {
      setPref($data_dir, $username, 'translate_show_read', '1');
    }
    else
    {
      setPref($data_dir, $username, 'translate_show_read', '');
    }

    if (isset($translate_translate_show_send))
    {
      setPref($data_dir, $username, 'translate_show_send', '1');
    }
    else
    {
      setPref($data_dir, $username, 'translate_show_send', '');
    }

    if (isset($translate_translate_same_window))
    {
      setPref($data_dir, $username, 'translate_same_window', '1');
    }
    else
    {
      setPref($data_dir, $username, 'translate_same_window', '');
    }

   echo '<center>Translation options saved.</center>';
  }
}


function translate_pref()
{
  global $username, $data_dir;
  global $translate_server, $translate_location;
  global $translate_show_send, $translate_show_read;
  global $translate_same_window;

  $translate_server = getPref($data_dir, $username, 'translate_server');
  if ($translate_server == '')
    $translate_server = 'babelfish';

  $translate_location = getPref($data_dir, $username, 'translate_location');
  if ($translate_location == '')
    $translate_location = 'center';

  $translate_show_send = getPref($data_dir, $username, 'translate_show_send');
  $translate_show_read = getPref($data_dir, $username, 'translate_show_read');
  $translate_same_window = getPref($data_dir, $username, 
'translate_same_window');
}


/* This function could be sped up.
   It basically negates the process if a ! is found in the beginning and
   matches a * at the end with 0 or more characters.  */
function translate_does_it_match_language($test)
{
  global $squirrelmail_language;
  $true = 1;
  $false = 0;
  $index = 0;
  $smindex = 0;

  if (! $test || ! $squirrelmail_language)
    return $false;

  if ($test[$index] == '!')
  {
    $index ++;
    $true = 0;
    $false = 1;
  }

  if ($index == 0 && $test == $squirrelmail_language)
    return $true;

  while ($test[$index])
  {
    if ($test[$index] == '*')
    {
      return $true;
    }
    if ($test[$index] != $squirrelmail_language[$smindex])
    {
      return $false;
    }
    $index ++;
    $smindex ++;
  }

  return $false;
}


function translate_lang_opt($from, $to, $value, $text)
{
    global $translate_dir;

    echo '  <option value="' . $value . '"';

    if (translate_does_it_match_language($to) &&
      $translate_dir == 'to')
        echo ' SELECTED';

    if (translate_does_it_match_language($from) &&
      $translate_dir == 'from')
        echo ' SELECTED';

    echo '>' . $text . "</option>\n";
}


function translate_new_form($action)
{
  global $translate_dir, $translate_new_window, $translate_location;
  global $color, $translate_same_window;

  echo '<form action="';

  if ($translate_dir == 'to')
  {
    echo $action;
  }
  else
  {
    echo 'translate.php';
  }

  echo '" method="post"';

  if (! $translate_same_window)
  {
      echo ' target="_blank"';
  }

  echo ">\n";

  ?><table align="<?PHP
      echo $translate_location;
  ?>" cellpadding=3 cellspacing=0 border=0 bgcolor=<?PHP
      echo $color[10]
  ?>>
    <tr>
      <td>
        <table cellpadding=2 cellspacing=1 border=0 bgcolor="<?PHP
            echo $color[5]
        ?>">
          <tr>
            <td><?PHP
}


function translate_form_babelfish($message)
{
  translate_new_form('http://babelfish.altavista.com/translate.dyn');
?><input type="hidden" name="doit" value="done">
<input type="hidden" name="BabelFishFrontPage" value="yes">
<input type="hidden" name="bblType" value="urltext">
<input type="hidden" name="urltext" value="<?PHP
    echo $message;
?>">
<select name="lp">
<?PHP
  translate_lang_opt('en',  'fr',  'en_fr', 'English to French');
  translate_lang_opt('',    'de',  'en_de', 'English to German');
  translate_lang_opt('',    'it',  'en_it', 'English to Italian');
  translate_lang_opt('',    'pt*', 'en_pt', 'English to Portuguese');
  translate_lang_opt('',    'es',  'en_es', 'English to Spanish');
  translate_lang_opt('fr',  'en',  'fr_en', 'French to English');
  translate_lang_opt('de',  '',    'de_en', 'German to English');
  translate_lang_opt('it',  '',    'it_en', 'Italian to English');
  translate_lang_opt('pt*', '',    'pt_en', 'Portuguese to English');
  translate_lang_opt('es',  '',    'es_en', 'Spanish to English');
  translate_lang_opt('',    '',    'de_fr', 'German to French');
  translate_lang_opt('',    '',    'fr_de', 'French to German');
  translate_lang_opt('ru',  '',    'ru_en', 'Russian to English');
?></select>
Babelfish: <input type="Submit" value="Translate">
<?PHP
  translate_table_end();
}


function translate_form_go($message)
{
  translate_new_form('http://translator.go.com/cb/trans_entry');
?><input type=hidden name=input_type value=text>
<select name=lp>
<?PHP
  translate_lang_opt('en', 'es', 'en_sp', 'English to Spanish');
  translate_lang_opt('',   'fr', 'en_fr', 'English to French');
  translate_lang_opt('',   'de', 'en_ge', 'English to German');
  translate_lang_opt('',   'it', 'en_it', 'English to Italian');
  translate_lang_opt('',   'pt', 'en_pt', 'English to Portuguese');
  translate_lang_opt('es', 'en', 'sp_en', 'Spanish to English');
  translate_lang_opt('fr', '',   'fr_en', 'French to English');
  translate_lang_opt('de', '',   'ge_en', 'German to English');
  translate_lang_opt('it', '',   'it_en', 'Italian to English');
  translate_lang_opt('pt', '',   'pt_en', 'Portuguese to English');
?></select>
<input type="hidden" name="text" value="<?PHP
    echo $message;
?>">
Go.com: <input type="Submit" value="Translate">
<?PHP
  translate_table_end();
}


function translate_form_intertran($message)
{
  translate_new_form('http://www.tranexp.com:2000/InterTran');
?><INPUT TYPE="hidden" NAME="topframe" VALUE="yes">
<INPUT TYPE="hidden" NAME="type" VALUE="text">
<input type="hidden" name="text" value="<?PHP
    echo $message;
?>">
<SELECT name="from">
<?PHP
  translate_lang_opt('pt_BR', '',    'pob', 'Brazilian Portuguese');
  translate_lang_opt('',      '',    'bul', 'Bulgarian (CP 1251)');
  translate_lang_opt('',      '',    'cro', 'Croatian (CP 1250)');
  translate_lang_opt('cs',    '',    'che', 'Czech (CP 1250)');
  translate_lang_opt('',      '',    'dan', 'Danish');
  translate_lang_opt('nl',    '',    'dut', 'Dutch');
  translate_lang_opt('en',    '!en', 'eng', 'English');
  translate_lang_opt('',      '',    'spe', 'European Spanish');
  translate_lang_opt('',      '',    'fin', 'Finnish');
  translate_lang_opt('fr',    '',    'fre', 'French');
  translate_lang_opt('de',    '',    'ger', 'German');
  translate_lang_opt('',      '',    'grk', 'Greek');
  translate_lang_opt('',      '',    'hun', 'Hungarian (CP 1250)');
  translate_lang_opt('',      '',    'ice', 'Icelandic');
  translate_lang_opt('it',    '',    'ita', 'Italian');
  translate_lang_opt('',      '',    'jpn', 'Japanese (Shift JIS)');
  translate_lang_opt('',      '',    'spl', 'Latin American Spanish');
  translate_lang_opt('no*',   '',    'nor', 'Norwegian');
  translate_lang_opt('pl',    '',    'pol', 'Polish (ISO 8859-2)');
  translate_lang_opt('',      '',    'poe', 'Portuguese');
  translate_lang_opt('',      '',    'rom', 'Romanian (CP 1250)');
  translate_lang_opt('ru',    '',    'rus', 'Russian (CP 1251)');
  translate_lang_opt('',      '',    'sel', 'Serbian (CP 1250)');
  translate_lang_opt('',      '',    'slo', 'Slovenian (CP 1250)');
  translate_lang_opt('es',    '',    'spa', 'Spanish');
  translate_lang_opt('sv',    '',    'swe', 'Swedish');
  translate_lang_opt('',      '',    'wel', 'Welsh');
?></SELECT>
to
<SELECT name="to">
<?PHP
  translate_lang_opt('',    'pt_BR', 'pob', 'Brazilian Portuguese');
  translate_lang_opt('',    '',      'bul', 'Bulgarian (CP 1251)');
  translate_lang_opt('',    '',      'cro', 'Croatian (CP 1250)');
  translate_lang_opt('',    'cs',    'che', 'Czech (CP 1250)');
  translate_lang_opt('',    '',      'dan', 'Danish');
  translate_lang_opt('',    'nl',    'dut', 'Dutch');
  translate_lang_opt('!en', 'en',    'eng', 'English');
  translate_lang_opt('',    '',      'spe', 'European Spanish');
  translate_lang_opt('',    '',      'fin', 'Finnish');
  translate_lang_opt('',    'fr',    'fre', 'French');
  translate_lang_opt('',    'de',    'ger', 'German');
  translate_lang_opt('',    '',      'grk', 'Greek');
  translate_lang_opt('',    '',      'hun', 'Hungarian (CP 1250)');
  translate_lang_opt('',    '',      'ice', 'Icelandic');
  translate_lang_opt('',    'it',    'ita', 'Italian');
  translate_lang_opt('',    '',      'jpn', 'Japanese (Shift JIS)');
  translate_lang_opt('',    '',      'spl', 'Latin American Spanish');
  translate_lang_opt('',    'no*',   'nor', 'Norwegian');
  translate_lang_opt('',    'pl',    'pol', 'Polish (ISO 8859-2)');
  translate_lang_opt('',    '',      'poe', 'Portuguese');
  translate_lang_opt('',    '',      'rom', 'Romanian (CP 1250)');
  translate_lang_opt('',    'ru',    'rus', 'Russian (CP 1251)');
  translate_lang_opt('',    '',      'sel', 'Serbian (CP 1250)');
  translate_lang_opt('',    '',      'slo', 'Slovenian (CP 1250)');
  translate_lang_opt('',    'es',    'spa', 'Spanish');
  translate_lang_opt('',    'sv',    'swe', 'Swedish');
  translate_lang_opt('',    '',      'wel', 'Welsh');
?></SELECT>
InterTran:  <input type=submit value="Translate">
<?PHP
  translate_table_end();
}


function translate_form_gpltrans($message)
{
  translate_new_form('http://www.translator.cx/cgi-bin/gplTrans');
?><select name="toenglish">
<?PHP
  translate_lang_opt('en',  '!en', 'no',  'From English');
  translate_lang_opt('!en', 'en',  'yes', 'To English');
?></select>
<select name="language">
<?PHP
  translate_lang_opt('nl', 'nl', 'dutch_dict',      'Dutch');
  translate_lang_opt('fr', 'fr', 'french_dict',     'French');
  translate_lang_opt('de', 'de', 'german_dict',     'German');
  translate_lang_opt('',   '',   'indonesian_dict', 'Indonesian');
  translate_lang_opt('it', 'it', 'italian_dict',    'Italian');
  translate_lang_opt('',   '',   'latin_dict',      'Latin');
  translate_lang_opt('pt', 'pt', 'portuguese_dict', 'Portuguese');
  translate_lang_opt('es', 'es', 'spanish_dict',    'Spanish');
?></select>
<input type="hidden" name="text" value="<?PHP
    echo $message;
?>">
GPLTrans: <input type="submit" value="Translate">
<?PHP
  translate_table_end();
}


function translate_form_dictionary($message) {
  //translate_new_form('http://translate.dictionary.com:8800/systran/cgi');
  translate_new_form('http://translator.dictionary.com/fcgi/translate');
  //<input type=hidden name=urltext value="<?PHP
?><INPUT TYPE=HIDDEN NAME=partner VALUE=LEXICO>
<input type=hidden name=text value="<?PHP
    echo $message;
?>">
<SELECT NAME="lp">
<?PHP
  translate_lang_opt('en',  'fr', 'en_fr', 'English to French');
  translate_lang_opt('',    'de', 'en_de', 'English to German');
  translate_lang_opt('',    'it', 'en_it', 'English to Italian');
  translate_lang_opt('',    'pt*', 'en_pt', 'English to Portuguese');
  translate_lang_opt('',    'es', 'en_sp', 'English to Spanish');
  translate_lang_opt('fr',  '', 'fr_en', 'French to English');
  translate_lang_opt('',    '', 'fr_ge', 'French to German');
  translate_lang_opt('',    '', 'ge_fr', 'German to French');
  translate_lang_opt('de',  '', 'de_en', 'German to English');
  translate_lang_opt('it',  '', 'it_en', 'Italian to English');
  translate_lang_opt('pt*', '', 'pt_en', 'Portuguese to English');
  translate_lang_opt('es',  '', 'sp_en', 'Spanish to English');
?></SELECT>
Dictionary.com: <INPUT TYPE="submit" VALUE="Translate">
<?PHP
  translate_table_end();
}



function translate_form_freetrans($message) {
  translate_new_form('http://ets.freetranslation.com:5081/');
  //<input type=hidden name=urltext value="<?PHP
?>
<INPUT TYPE="hidden" NAME="Sequence" VALUE="core">
<INPUT TYPE="hidden" NAME="Mode" VALUE="html">
<INPUT TYPE="hidden" NAME="template" VALUE="TextResults2.htm">
<input type="hidden" name="SrcText" value="<?PHP
    echo $message;
?>">
<SELECT NAME="Language">
<?PHP
    translate_lang_opt('es', 'en', "Spanish/English", 'Spanish to English');
    translate_lang_opt('fr', 'en', "French/English", 'French to English');
    translate_lang_opt('de', 'en', "German/English", 'German to English');
    translate_lang_opt('pt', 'en', "Portuguese/English", 'Portuguese to 
English');
    translate_lang_opt('en', 'es', "English/Spanish", 'English to Spanish');
    translate_lang_opt('en', 'fr', "English/French", 'English to French');
    translate_lang_opt('en', 'de', "English/German", 'English to German');
    translate_lang_opt('en', 'it', "English/Italian", 'English to Italian');
    translate_lang_opt('en', 'no', "English/Norwegian", 'English to Norwegian');
    translate_lang_opt('en', 'pt', "English/Portuguese", 'English to 
Portuguese');
?></SELECT>
Free Translation: <INPUT TYPE="submit" VALUE="Translate!">
<?PHP
translate_table_end();
}


?>

====================================================
Index: url_parser.php
<?php
   /* URL Passing code to allow links from with in emails */
   /* $Id: url_parser.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $ */

   $url_parser_php = true;

   function replaceBlock ($in, $replace, $start, $end) {
      $begin = substr($in,0,$start);
      $end   = substr($in,$end,strlen($in)-$end);
      $ret   = $begin.$replace.$end;
      return $ret;
   }

   function parseEmail (&$body) {
      global $phpgw, $phpgw_info, $color;
      $Size = strlen($body);

      // Having this defined in just one spot could help when changes need
      // to be made to the pattern
      // Make sure that the expression is evaluated case insensitively
      //
      // Here's pretty sophisticated IP matching:
      // $IPMatch = '(2[0-5][0-9]|1?[0-9]{1,2})';
      // $IPMatch = '\[?' . $IPMatch . '(\.' . $IPMatch . '){3}\]?';
      //
      // Here's enough:
      $IPMatch = '\[?[0-9]{1,3}(\.[0-9]{1,3}){3}\]?';
      $Host = '(' . $IPMatch . 
'|[0-9a-z]([-.]?[0-9a-z])*\.[a-wyz][a-z](g|l|m|pa|t|u|v)?)';
      $Expression = '[0-9a-z]([-_.]?[0-9a-z])*(%' . $Host . ')?@' . $Host;

      /*
        This is here in case we ever decide to use highlighting of searched
        text.  this does it for email addresses

      if ($what && ($where == "BODY" || $where == "TEXT")) {
         eregi ($Expression, $body, $regs);
         $oldaddr = $regs[0];
         if ($oldaddr) {
            $newaddr = eregi_replace ($what, "<b><font 
color=\"$color[2]\">$what</font></font></b>", $oldaddr);
            $body = str_replace ($oldaddr, "<a 
href=\"compose.php?send_to=$oldaddr\">$newaddr</a>", $body);
         }
      } else {
         $body = eregi_replace ($Expression, "<a 
href=\"compose.php?send_to=\\0\">\\0</a>", $body);
      }
      */

      $linkData = array
      (
        'menuaction'    => 'squirrelmail.uicompose.compose',
        'mailbox'       => urlencode($GLOBALS['HTTP_GET_VARS']['mailbox']),
        'send_to'       => "\\0"
      );

      $body = eregi_replace ($Expression, "<a href=\"" . 
$GLOBALS['phpgw']->link('/index.php',$linkData) . "\">\\0</a>", $body);

      // If there are any changes, it'll just get bigger.
      if ($Size != strlen($body))
          return 1;
      return 0;
   }


   function parseUrl (&$body)
   {
      $url_tokens = array(
         'http://',
         'https://',
         'ftp://',
         'telnet:',  // Special case -- doesn't need the slashes
         'gopher://',
         'news://');

      $poss_ends = array(' ', "\n", "\r", '<', '>', ".\r", ".\n", '.&nbsp;',
         '&nbsp;', ')', '(', '&quot;', '&lt;', '&gt;', '.<', ']', '[', '{',
         '}', "\240");

      $start = 0;
      $target_pos = strlen($body);

      while ($start != $target_pos)
      {
        $target_token = '';

        // Find the first token to replace
        foreach ($url_tokens as $the_token)
        {
          $pos = strpos(strtolower($body), $the_token, $start);
          if (is_int($pos) && $pos < $target_pos)
          {
            $target_pos = $pos;
            $target_token = $the_token;
          }
        }

        // Look for email addresses between $start and $target_pos
        $check_str = substr($body, $start, $target_pos);

        if (parseEmail($check_str))
        {
          $body = replaceBlock($body, $check_str, $start, $target_pos);
          $target_pos = strlen($check_str) + $start;
        }

        // If there was a token to replace, replace it
        if ($target_token != '')
        {
          // Find the end of the URL
          $end=strlen($body);
          foreach ($poss_ends as $key => $val)
          {
            $enda = strpos($body,$val,$target_pos);
            if (is_int($enda) && $enda < $end)
              $end = $enda;
          }

          // Extract URL
          $url = substr($body, $target_pos, $end-$target_pos);

          // Replace URL with HyperLinked Url, requires 1 char in link
          if ($url != '' && $url != $target_token)
          {
            $url_str = "<a href=\"$url\" target=\"_blank\">$url</a>";
            $body = replaceBlock($body,$url_str,$target_pos,$end);
            $target_pos += strlen($url_str);
          }
          else
          {
             // Not quite a valid link, skip ahead to next chance
             $target_pos += strlen($target_token);
          }
        }

        // Move forward
        $start = $target_pos;
        $target_pos = strlen($body);
      }
   }

?>

====================================================
Index: tree.php
<?php

   /* $Id: tree.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $ */

   $tree_php = true;

   if (!isset($imap_php))
      include(PHPGW_APP_ROOT . '/inc/imap.php');
   if (!isset($config_php))
      include(PHPGW_APP_ROOT . '/config/config.php');

   // Recursive function to find the correct parent for a new node
   function findParentForChild($value, $treeIndexToStart, $tree) {
      // is $value in $tree[$treeIndexToStart]['value']
      if ((isset($tree[$treeIndexToStart])) && (strstr($value, 
$tree[$treeIndexToStart]['value']))) {
         // do I have children, if not then must be a childnode of the current 
node
         if ($tree[$treeIndexToStart]['doIHaveChildren']) {
            // loop through each subNode checking to see if we are a subNode of 
one of them
            for ($i=0;$i< count($tree[$treeIndexToStart]['subNodes']);$i++) {
               $result = findParentForChild($value, 
$tree[$treeIndexToStart]['subNodes'][$i], $tree);
               if ($result > -1)
                  return $result;
            }
            // if we aren't a child of one of the subNodes, must be a child of 
current node
            return $treeIndexToStart;
         } else
            return $treeIndexToStart;
      } else {
         // we aren't a child of this node at all
         return -1;
      }
   }

   function addChildNodeToTree($comparisonValue, $value, &$tree) {
      $parentNode = findParentForChild($comparisonValue, 0, $tree);

      // create a new subNode
      $newNodeIndex = count($tree);
      $tree[$newNodeIndex]['value'] = $value;
      $tree[$newNodeIndex]['doIHaveChildren'] = false;

      if ($tree[$parentNode]['doIHaveChildren'] == false) {
         // make sure the parent knows it has children
         $tree[$parentNode]['subNodes'][0] = $newNodeIndex;
         $tree[$parentNode]['doIHaveChildren'] = true;
      } else {
         $nextSubNode = count($tree[$parentNode]['subNodes']);
         // make sure the parent knows it has children
         $tree[$parentNode]['subNodes'][$nextSubNode] = $newNodeIndex;
      }
   }

   function walkTreeInPreOrderEmptyTrash($index, $imap_stream, $tree) {
      global $trash_folder;
      if ($tree[$index]['doIHaveChildren']) {
         for ($j = 0; $j < count($tree[$index]['subNodes']); $j++) {
            walkTreeInPreOrderEmptyTrash($tree[$index]['subNodes'][$j], 
$imap_stream, $tree);
         }
         if ($tree[$index]['value'] != $trash_folder) {
            sqimap_mailbox_delete($imap_stream, $tree[$index]['value']);
         } else {
            $numMessages = sqimap_get_num_messages($imap_stream, $trash_folder);
            if ($numMessages > 0) {
               sqimap_mailbox_select($imap_stream, $trash_folder);
               sqimap_messages_flag ($imap_stream, 1, $numMessages, 'Deleted');
               sqimap_mailbox_expunge($imap_stream, $trash_folder, true);
            }
         }
      } else {
         if ($tree[$index]['value'] != $trash_folder) {
            sqimap_mailbox_delete($imap_stream, $tree[$index]['value']);
         } else {
            $numMessages = sqimap_get_num_messages($imap_stream, $trash_folder);
            if ($numMessages > 0) {
               sqimap_mailbox_select($imap_stream, $trash_folder);
               sqimap_messages_flag ($imap_stream, 1, $numMessages, 'Deleted');
               sqimap_mailbox_expunge($imap_stream, $trash_folder, true);
            }
         }
      }
   }

   function walkTreeInPreOrderDeleteFolders($index, $imap_stream, $tree) {
      if ($tree[$index]['doIHaveChildren']) {
         for ($j = 0; $j < count($tree[$index]['subNodes']); $j++) {
            walkTreeInPreOrderDeleteFolders($tree[$index]['subNodes'][$j], 
$imap_stream, $tree);
         }
         sqimap_mailbox_delete($imap_stream, $tree[$index]['value']);
      } else {
         sqimap_mailbox_delete($imap_stream, $tree[$index]['value']);
      }
   }

   function walkTreeInPostOrderCreatingFoldersUnderTrash($index, $imap_stream, 
$tree, $dm, $topFolderName) {
      global $trash_folder;

      $position = strrpos($topFolderName, $dm) + 1;
      $subFolderName = substr($tree[$index]['value'], $position);

      if ($tree[$index]['doIHaveChildren']) {
         sqimap_mailbox_create($imap_stream, $trash_folder . $dm . 
$subFolderName, "");
         sqimap_mailbox_select($imap_stream, $tree[$index]['value']);

         $messageCount = sqimap_get_num_messages($imap_stream, 
$tree[$index]['value']);
         if ($messageCount > 0)
            sqimap_messages_copy($imap_stream, 1, $messageCount, $trash_folder 
. $dm . $subFolderName);

         for ($j = 0;$j < count($tree[$index]['subNodes']); $j++)
            
walkTreeInPostOrderCreatingFoldersUnderTrash($tree[$index]['subNodes'][$j], 
$imap_stream, $tree, $dm, $topFolderName);
      } else {
         sqimap_mailbox_create($imap_stream, $trash_folder . $dm . 
$subFolderName, '');
         sqimap_mailbox_select($imap_stream, $tree[$index]['value']);

         $messageCount = sqimap_get_num_messages($imap_stream, 
$tree[$index]['value']);
         if ($messageCount > 0)
            sqimap_messages_copy($imap_stream, 1, $messageCount, $trash_folder 
. $dm . $subFolderName);
      }
   }

   function simpleWalkTreePre($index, $tree) {
      if ($tree[$index]['doIHaveChildren']) {
         for ($j = 0; $j < count($tree[$index]['subNodes']); $j++) {
            simpleWalkTreePre($tree[$index]['subNodes'][$j], $tree);
         }
         echo $tree[$index]['value'] . '<br>';
      } else {
         echo $tree[$index]['value'] . '<br>';
      }
   }
?>

====================================================
Index: mime.php
<?php
   /** mime.php
    **
    ** This contains the functions necessary to detect and decode MIME
    ** messages.
    **
    ** $Id: mime.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $
    **/

   $debug_mime = false;
   $mime_php = true;

        if (!isset($i18n_php))
        {
      include(PHPGW_APP_ROOT . '/inc/i18n.php');
        }

        if (!isset($imap_php))
        {
                include(PHPGW_APP_ROOT . '/inc/imap.php');
        }

        if (!isset($config_php))
        {
                include(PHPGW_APP_ROOT . '/config/config.php');
        }

   /** Setting up the objects that have the structure for the message **/

   class msg_header {
      /** msg_header contains generic variables for values that **/
      /** could be in a header.                                 **/

      var $type0 = '', $type1 = '', $boundary = '', $charset = '';
      var $encoding = '', $size = 0, $to = array(), $from = '', $date = '';
      var $cc = array(), $bcc = array(), $reply_to = '', $subject = '';
      var $id = 0, $mailbox = '', $description = '', $filename = '';
      var $entity_id = 0, $message_id = 0;
/** Added to grab phpGW_type **/
      var $phpgw_type = array();
   }

   class message {
      /** message is the object that contains messages.  It is a recursive
          object in that through the $entities variable, it can contain
          more objects of type message.  See documentation in mime.txt for
          a better description of how this works.
       **/
      var $header = '';
      var $entities = array();

      function addEntity ($msg) {
         $this->entities[] = $msg;
      }
   }



   /* 
---------------------------------------------------------------------------------
 */
   /* MIME DECODING                                                             
        */
   /* 
---------------------------------------------------------------------------------
 */

   // This function gets the structure of a message and stores it in the 
"message" class.
   // It will return this object for use with all relevant header information 
and
   // fully parsed into the standard "message" object format.
   function mime_structure ($imap_stream, $header) {
      global $debug_mime;
      sqimap_messages_flag ($imap_stream, $header->id, $header->id, "Seen");

      $id = $header->id;
      fputs ($imap_stream, "a001 FETCH $id BODYSTRUCTURE\r\n");
      //
      // This should use sqimap_read_data instead of reading it itself
      //
      $read = fgets ($imap_stream, 10000);
      $response = substr($read, 0, 4);
      $bodystructure = "";
      while ($response != "a001") {
         $bodystructure .= $read;
         $read = fgets ($imap_stream, 10000);
         $response = substr($read, 0, 4);
      }
      $read = $bodystructure;

      if ($debug_mime) echo "<tt>$read</tt><br><br>\n";
      // isolate the body structure and remove beginning and end parenthesis
      $read = trim(substr ($read, strpos(strtolower($read), "bodystructure") + 
13));
      $read = trim(substr ($read, 0, -1));
      $end = mime_match_parenthesis(0, $read);
      while ($end == strlen($read)-1) {
         $read = trim(substr ($read, 0, -1));
         $read = trim(substr ($read, 1));
         $end = mime_match_parenthesis(0, $read);
      }

      if ($debug_mime) echo "<tt>$read</tt><br><br>\n";

      $msg = mime_parse_structure ($read, 0);
      $msg->header = $header;
      return $msg;
   }

   // this starts the parsing of a particular structure.  It is called 
recursively,
   // so it can be passed different structures.  It returns an object of type
   // $message.
   // First, it checks to see if it is a multipart message.  If it is, then it
   // handles that as it sees is necessary.  If it is just a regular entity,
   // then it parses it and adds the necessary header information (by calling 
out
   // to mime_get_elements()
   function mime_parse_structure ($structure, $ent_id) {
      global $debug_mime;
      if ($debug_mime) echo "<font color=008800><tt>START: 
mime_parse_structure()</tt></font><br>\n";
      $msg = new message();
      if (substr($structure, 0, 1) == "(") {
         $ent_id = mime_new_element_level($ent_id);
         $start = $end = -1;
         if ($debug_mime) echo "<br><font 
color=0000aa><tt>$structure</tt></font><br>";
         do {
            if ($debug_mime) echo "<font color=008800><tt>Found 
entity...</tt></font><br>";
            $start = $end+1;
            $end = mime_match_parenthesis ($start, $structure);

            $element = substr($structure, $start+1, ($end - $start)-1);
            $ent_id = mime_increment_id ($ent_id);
            $newmsg = mime_parse_structure ($element, $ent_id);
            $msg->addEntity ($newmsg);
         } while (substr($structure, $end+1, 1) == "(");
      } else {
         // parse the elements
         if ($debug_mime) echo "<br><font 
color=0000aa><tt>$structure</tt></font><br>";
         $msg = mime_get_element ($structure, $msg, $ent_id);
         if ($debug_mime) echo "<br>";
      }
      return $msg;
      if ($debug_mime) echo "<font color=008800><tt>&nbsp;&nbsp;END: 
mime_parse_structure()</tt></font><br>";
   }

   // Increments the element ID.  An element id can look like any of
   // the following:  1, 1.2, 4.3.2.4.1, etc.  This function increments
   // the last number of the element id, changing 1.2 to 1.3.
   function mime_increment_id ($id) {
      global $debug_mime;
      if (strpos($id, ".")) {
         $first = substr($id, 0, strrpos($id, "."));
         $last = substr($id, strrpos($id, ".")+1);
         $last++;
         $new = $first . "." .$last;
      } else {
         $new = $id + 1;
      }
      if ($debug_mime) echo "<b>INCREMENT: $new</b><br>";
      return $new;
   }

   // See comment for mime_increment_id().
   // This adds another level on to the entity_id changing 1.3 to 1.3.0
   // NOTE:  1.3.0 is not a valid element ID.  It MUST be incremented
   //        before it can be used.  I left it this way so as not to have
   //        to make a special case if it is the first entity_id.  It
   //        always increments it, and that works fine.
   function mime_new_element_level ($id) {
      if (!$id) $id = 0;
      else      $id = $id . ".0";

      return $id;
   }

   function mime_get_element (&$structure, $msg, $ent_id) {
      global $debug_mime;
      $elem_num = 1;
      $msg->header = new msg_header();
      $msg->header->entity_id = $ent_id;

      while (strlen($structure) > 0) {
         $structure = trim($structure);
         $char = substr($structure, 0, 1);

         if (strtolower(substr($structure, 0, 3)) == "nil") {
            $text = "";
            $structure = substr($structure, 3);
         } else if ($char == "\"") {
            // loop through until we find the matching quote, and return that 
as a string
            $pos = 1;
            $char = substr($structure, $pos, 1);
            $text = "";
            while ($char != "\"" && $pos < strlen($structure)) {
               $text .= $char;
               $pos++;
               $char = substr($structure, $pos, 1);
            }
            $structure = substr($structure, strlen($text) + 2);
         } else if ($char == "(") {
            // comment me
            $end = mime_match_parenthesis (0, $structure);
            $sub = substr($structure, 1, $end-1);
            if (! isset($properties))
                $properties = array();
            $properties = mime_get_props($properties, $sub);
            $structure = substr($structure, strlen($sub) + 2);
         } else {
            // loop through until we find a space or an end parenthesis
            $pos = 0;
            $char = substr($structure, $pos, 1);
            $text = "";
            while ($char != " " && $char != ")" && $pos < strlen($structure)) {
               $text .= $char;
               $pos++;
               $char = substr($structure, $pos, 1);
            }
            $structure = substr($structure, strlen($text));
         }
         if ($debug_mime) echo "<tt>$elem_num : $text</tt><br>";

         // This is where all the text parts get put into the header
         switch ($elem_num) {
            case 1:
               $msg->header->type0 = strtolower($text);
               if ($debug_mime) echo "<tt>type0 = 
".strtolower($text)."</tt><br>";
               break;
            case 2:
               $msg->header->type1 = strtolower($text);
               if ($debug_mime) echo "<tt>type1 = 
".strtolower($text)."</tt><br>";
               break;
            case 5:
               $msg->header->description = $text;
               if ($debug_mime) echo "<tt>description = $text</tt><br>";
               break;
            case 6:
               $msg->header->encoding = strtolower($text);
               if ($debug_mime) echo "<tt>encoding = 
".strtolower($text)."</tt><br>";
               break;
            case 7:
               $msg->header->size = $text;
               if ($debug_mime) echo "<tt>size = $text</tt><br>";
               break;
            default:
               if ($msg->header->type0 == "text" && $elem_num == 8) {
                  // This is a plain text message, so lets get the number of 
lines
                  // that it contains.
                  $msg->header->num_lines = $text;
                  if ($debug_mime) echo "<tt>num_lines = $text</tt><br>";

               } else if ($msg->header->type0 == "message" && 
$msg->header->type1 == "rfc822" && $elem_num == 8) {
                  // This is an encapsulated message, so lets start all over 
again and
                  // parse this message adding it on to the existing one.
                  $structure = trim($structure);
                  if (substr($structure, 0, 1) == "(") {
                     $e = mime_match_parenthesis (0, $structure);
                     $structure = substr($structure, 0, $e);
                     $structure = substr($structure, 1);
                     $m = mime_parse_structure($structure, 
$msg->header->entity_id);

                     // the following conditional is there to correct a bug 
that wasn't
                     // incrementing the entity IDs correctly because of the 
special case
                     // that message/rfc822 is.  This fixes it fine.
                     if (substr($structure, 1, 1) != "(")
                        $m->header->entity_id = 
mime_increment_id(mime_new_element_level($ent_id));

                     // Now we'll go through and reformat the results.
                     if ($m->entities) {
                        for ($i=0; $i < count($m->entities); $i++) {
                           $msg->addEntity($m->entities[$i]);
                        }
                     } else {
                        $msg->addEntity($m);
                     }
                     $structure = "";
                  }
               }
               break;
         }
         $elem_num++;
         $text = "";
      }
      // loop through the additional properties and put those in the various 
headers
      if ($msg->header->type0 != "message") {
         for ($i=0; $i < count($properties); $i++) {
            $msg->header->{$properties[$i]["name"]} = $properties[$i]["value"];
            if ($debug_mime) echo "<tt>".$properties[$i]["name"]." = " . 
$properties[$i]["value"] . "</tt><br>";
         }
      }

      return $msg;
   }

   // I did most of the MIME stuff yesterday (June 20, 2000), but I couldn't
   // figure out how to do this part, so I decided to go to bed.  I woke up
   // in the morning and had a flash of insight.  I went to the white-board
   // and scribbled it out, then spent a bit programming it, and this is the
   // result.  Nothing complicated, but I think my brain was fried yesterday.
   // Funny how that happens some times.
   //
   // This gets properties in a nested parenthesisized list.  For example,
   // this would get passed something like:  ("attachment" ("filename" 
"luke.tar.gz"))
   // This returns an array called $props with all paired up properties.
   // It ignores the "attachment" for now, maybe that should change later
   // down the road.  In this case, what is returned is:
   //    $props[0]["name"] = "filename";
   //    $props[0]["value"] = "luke.tar.gz";
   function mime_get_props ($props, $structure) {
      global $debug_mime;
      while (strlen($structure) > 0) {
         $structure = trim($structure);
         $char = substr($structure, 0, 1);

         if ($char == "\"") {
            $pos = 1;
            $char = substr($structure, $pos, 1);
            $tmp = "";
            while ($char != "\"" && $pos < strlen($structure)) {
               $tmp .= $char;
               $pos++;
               $char = substr($structure, $pos, 1);
            }
            $structure = trim(substr($structure, strlen($tmp) + 2));
            $char = substr($structure, 0, 1);

            if ($char == "\"") {
               $pos = 1;
               $char = substr($structure, $pos, 1);
               $value = "";
               while ($char != "\"" && $pos < strlen($structure)) {
                  $value .= $char;
                  $pos++;
                  $char = substr($structure, $pos, 1);
               }
               $structure = trim(substr($structure, strlen($tmp) + 2));

               $k = count($props);
               $props[$k]["name"] = strtolower($tmp);
               $props[$k]["value"] = $value;
            } else if ($char == "(") {
               $end = mime_match_parenthesis (0, $structure);
               $sub = substr($structure, 1, $end-1);
               if (! isset($props))
                   $props = array();
               $props = mime_get_props($props, $sub);
               $structure = substr($structure, strlen($sub) + 2);
            }
            return $props;
         } else if ($char == "(") {
            $end = mime_match_parenthesis (0, $structure);
            $sub = substr($structure, 1, $end-1);
            $props = mime_get_props($props, $sub);
            $structure = substr($structure, strlen($sub) + 2);
            return $props;
         } else {
            return $props;
         }
      }
   }

   //  Matches parenthesis.  It will return the position of the matching
   //  parenthesis in $structure.  For instance, if $structure was:
   //     ("text" "plain" ("val1name", "1") nil ... )
   //     x                                         x
   //  then this would return 42 to match up those two.
   function mime_match_parenthesis ($pos, $structure) {
      $char = substr($structure, $pos, 1);

      // ignore all extra characters
      // If inside of a string, skip string -- Boundary IDs and other
      // things can have ) in them.
      while ($pos < strlen($structure)) {
         $pos++;
         $char = substr($structure, $pos, 1);
         if ($char == ")") {
            return $pos;
         } else if ($char == '"') {
            $pos ++;
            while (substr($structure, $pos, 1) != '"' &&
               $pos < strlen($structure)) {
               $pos ++;
            }
         } else if ($char == "(") {
            $pos = mime_match_parenthesis ($pos, $structure);
         }
      }
   }

   function mime_fetch_body ($imap_stream, $id, $ent_id) {
      // do a bit of error correction.  If we couldn't find the entity id, just 
guess
      // that it is the first one.  That is usually the case anyway.
      if (!$ent_id) $ent_id = 1;

      fputs ($imap_stream, "a010 FETCH $id BODY[$ent_id]\r\n");
      $data = sqimap_read_data ($imap_stream, 'a010', true, $response, 
$message);
      $topline = array_shift($data);
      while (! ereg('\* [0-9]+ FETCH ', $topline) && data)
          $topline = array_shift($data);
      $wholemessage = implode('', $data);

      if (ereg('\{([^\}]*)\}', $topline, $regs)) {
         return substr($wholemessage, 0, $regs[1]);
      }
      else if (ereg('"([^"]*)"', $topline, $regs)) {
         return $regs[1];
      }

      $str = "Body retrival error.  Please report this bug!\n";
      $str .= "Response:  $response\n";
      $str .= "Message:  $message\n";
      $str .= "FETCH line:  $topline";
      $str .= "---------------\n$wholemessage";
      foreach ($data as $d)
      {
          $str .= htmlspecialchars($d) . "\n";
      }
      return $str;

      return "Body retrival error, please report this bug!\n\nTop line is 
\"$topline\"\n";
   }

   function mime_print_body_lines ($imap_stream, $id, $ent_id, $encoding) {
      // do a bit of error correction.  If we couldn't find the entity id, just 
guess
      // that it is the first one.  That is usually the case anyway.
      if (!$ent_id) $ent_id = 1;

      fputs ($imap_stream, "a001 FETCH $id BODY[$ent_id]\r\n");
          $cnt = 0;
          $continue = true;
                $read = fgets ($imap_stream,4096);
                while (!ereg("^a001 (OK|BAD|NO)(.*)$", $read, $regs)) {
                        if (trim($read) == ")==") {
                                $read1 = $read;
                                $read = fgets ($imap_stream,4096);
                                if (ereg("^a001 (OK|BAD|NO)(.*)$", $read, 
$regs)) {
                                        return;
                                } else {
                                        echo decodeBody($read1, $encoding);
                                        echo decodeBody($read, $encoding);
                                }
                        } else if ($cnt) {
                                echo decodeBody($read, $encoding);
                        }
                        $read = fgets ($imap_stream,4096);
                        $cnt++;
                }
   }

   /* -[ END MIME DECODING 
]----------------------------------------------------------- */



   /** This is the first function called.  It decides if this is a multipart
       message or if it should be handled as a single entity
    **/
   function decodeMime ($imap_stream, &$header) {
      global $username, $key, $imapServerAddress, $imapPort;
      return mime_structure ($imap_stream, $header);
   }

   // This is here for debugging purposese.  It will print out a list
   // of all the entity IDs that are in the $message object.
   function listEntities ($message) {
      if ($message) {
         if ($message->header->entity_id)
         echo "<tt>" . $message->header->entity_id . " : " . 
$message->header->type0 . "/" . $message->header->type1 . "<br>";
         for ($i = 0; $message->entities[$i]; $i++) {
            $msg = listEntities($message->entities[$i], $ent_id);
            if ($msg)
               return $msg;
         }
      }
   }

   // returns a $message object for a particular entity id
   function getEntity ($message, $ent_id) {
      if ($message) {
         if ($message->header->entity_id == $ent_id && strlen($ent_id) == 
strlen($message->header->entity_id)) {
            return $message;
         } else {
            for ($i = 0; isset($message->entities[$i]); $i++) {
               $msg = getEntity ($message->entities[$i], $ent_id);
               if ($msg)
                  return $msg;
            }
         }
      }
   }

   // figures out what entity to display and returns the $message object
   // for that entity.
   function findDisplayEntity ($message) {
      if ($message) {
         if ($message->header->type0 == "text") {
            if ($message->header->type1 == "plain" ||
                $message->header->type1 == "html") {
               if (isset($message->header->entity_id))
                   return $message->header->entity_id;
               return 0;
            }
         } else {
            for ($i=0; $message->entities[$i]; $i++) {
               return findDisplayEntity($message->entities[$i]);
            }
         }
      }
   }

   /** This returns a parsed string called $body. That string can then
       be displayed as the actual message in the HTML. It contains
       everything needed, including HTML Tags, Attachments at the
       bottom, etc.
    **/
   function formatBody($imap_stream, $message, $color, $wrap_at) {
      // this if statement checks for the entity to show as the
      // primary message. To add more of them, just put them in the
      // order that is their priority.
      global $startMessage, $username, $key, $imapServerAddress, $imapPort;
      global $phpgw;

      $id = $message->header->id;
      $urlmailbox = urlencode($message->header->mailbox);

      // Get the right entity and redefine message to be this entity
      $ent_num = findDisplayEntity ($message);
      $body_message = getEntity($message, $ent_num);
      if (($body_message->header->type0 == "text") ||
          ($body_message->header->type0 == "rfc822")) {

         $body = mime_fetch_body ($imap_stream, $id, $ent_num);
         $body = decodeBody($body, $body_message->header->encoding);

         // If there are other types that shouldn't be formatted, add
         // them here
         if ($body_message->header->type1 != "html") {
            translateText($body, $wrap_at, $body_message->header->charset);
         }

         $body .= '<SMALL><CENTER><A 
HREF="'.$phpgw->link('/squirrelmail/download.php',"absolute_dl=true&passed_id=$id&passed_ent_id=$ent_num&mailbox=$urlmailbox").'">'.
 lang("Download this as a file") ."</A></CENTER><BR></SMALL>";

         /** Display the ATTACHMENTS: message if there's more than one part **/
         $body .= "</TD></TR></TABLE>";
         if (isset($message->entities[0])) {
            $body .= formatAttachments ($message, $ent_num, 
$message->header->mailbox, $id);
         }
      } else {
         $body .= formatAttachments ($message, -1, $message->header->mailbox, 
$id);
      }
          $body = eregi_replace('base href','base hreff',$body);
      return $body;
   }

   // A recursive function that returns a list of attachments with links
   // to where to download these attachments
   function formatAttachments ($message, $ent_id, $mailbox, $id) {
      global $where, $what;
      global $startMessage, $color;
      global $phpgw;
      static $ShownHTML = 0;

          $body = "";
      if ($ShownHTML == 0)
      {
            $ShownHTML = 1;

            $body .= "<TABLE WIDTH=100% CELLSPACING=0 CELLPADDING=2 BORDER=0 
BGCOLOR=\"$color[0]\"><TR>\n";
            $body .= "<TH ALIGN=\"left\" BGCOLOR=\"$color[9]\"><B>\n";
            $body .= lang("Attachments") . ':';
            $body .= "</B></TH></TR><TR><TD>\n";

            $body .= "<TABLE CELLSPACING=0 CELLPADDING=1 BORDER=0>\n";

            $body .= formatAttachments ($message, $ent_id, $mailbox, $id);

            $body .= "</TABLE></TD></TR></TABLE>";

            return $body;
      }

      if ($message) {
         if (!$message->entities) {
            $type0 = strtolower($message->header->type0);
            $type1 = strtolower($message->header->type1);

            if ($message->header->entity_id != $ent_id) {
               $filename = decodeHeader($message->header->filename);
               if (trim($filename) == "") {
                  $display_filename = "untitled-".$message->header->entity_id;
               } else {
                  $display_filename = $filename;
               }

               $urlMailbox = urlencode($mailbox);
               $ent = urlencode($message->header->entity_id);

               $DefaultLink = $phpgw->link(
                  
"/squirrelmail/download.php","startMessage=$startMessage&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent");
               if ($where && $what)
                  $DefaultLink .= '&where=' . urlencode($where) . '&what=' . 
urlencode($what);
               $Links['download link']['text'] = lang("download");
               $Links['download link']['href'] = $phpgw->link(
                   
"/squirrelmail/download.php","absolute_dl=true&passed_id=$id&mailbox=$urlMailbox&passed_ent_id=$ent");
               $ImageURL = '';

               $HookResults = do_hook("attachment $type0/$type1", $Links,
                   $startMessage, $id, $urlMailbox, $ent, $DefaultLink,
                   $display_filename, $where, $what);

               $Links = $HookResults[1];
               $DefaultLink = $HookResults[6];

               $body .= '<TR><TD>&nbsp;&nbsp;</TD><TD>';
               $body .= "<A 
HREF=\"$DefaultLink\">$display_filename</A>&nbsp;</TD>";
               $body .= '<TD><SMALL><b>' . 
show_readable_size($message->header->size) .
                   '</b>&nbsp;&nbsp;</small></TD>';
               $body .= "<TD><SMALL>[ $type0/$type1 ]&nbsp;</SMALL></TD>";
               $body .= '<TD><SMALL>';
               if ($message->header->description)
                  $body .= '<b>' . 
htmlspecialchars($message->header->description) . '</b>';
               $body .= '</SMALL></TD><TD><SMALL>&nbsp;';


               $SkipSpaces = 1;
               foreach ($Links as $Val)
               {
                  if ($SkipSpaces)
                  {
                     $SkipSpaces = 0;
                  }
                  else
                  {
                     $body .= '&nbsp;&nbsp;|&nbsp;&nbsp;';
                  }
                  $body .= '<a href="' . $Val['href'] . '">' .  $Val['text'] . 
'</a>';
               }

               unset($Links);

               $body .= "</SMALL></TD></TR>\n";
            }
            return $body;
         } else {
            for ($i = 0; $i < count($message->entities); $i++) {
               $body .= formatAttachments ($message->entities[$i], $ent_id, 
$mailbox, $id);
            }
            return $body;
         }
      }
   }


   /** this function decodes the body depending on the encoding type. **/
   function decodeBody($body, $encoding) {
      $body = str_replace("\r\n", "\n", $body);
      $encoding = strtolower($encoding);

      if ($encoding == "quoted-printable") {
         $body = quoted_printable_decode($body);

         while (ereg("=\n", $body))
            $body = ereg_replace ("=\n", "", $body);
      } else if ($encoding == "base64") {
         $body = base64_decode($body);
      }

      // All other encodings are returned raw.
      return $body;
   }


   // This functions decode strings that is encoded according to
   // RFC1522 (MIME Part Two: Message Header Extensions for Non-ASCII Text).
   function decodeHeader ($string) {
      if (eregi('=\?([^?]+)\?(q|b)\?([^?]+)\?=',
                $string, $res)) {
         if (ucfirst($res[2]) == "B") {
            $replace = base64_decode($res[3]);
         } else {
            $replace = ereg_replace("_", " ", $res[3]);
            // Convert lowercase Quoted Printable to uppercase for
            // quoted_printable_decode to understand it.
            while 
(ereg("(=([0-9][abcdef])|([abcdef][0-9])|([abcdef][abcdef]))", $replace, $res)) 
{
               $replace = str_replace($res[1], strtoupper($res[1]), $replace);
            }
            $replace = quoted_printable_decode($replace);
         }

         $replace = charset_decode ($res[1], $replace);

         $string = eregi_replace
            ('=\?([^?]+)\?(q|b)\?([^?]+)\?=',
             $replace, $string);
         // In case there should be more encoding in the string: recurse
         return (decodeHeader($string));
      } else
         return ($string);
   }

   // Encode a string according to RFC 1522 for use in headers if it
   // contains 8-bit characters or anything that looks like it should
   // be encoded.
   function encodeHeader ($string) {
      global $default_charset;

      // Encode only if the string contains 8-bit characters or =?
      if (ereg("([\200-\377]|=\\?)", $string)) {
         $newstring = "=?$default_charset?Q?";

         // First the special characters
         $string = str_replace("=", "=3D", $string);
         $string = str_replace("?", "=3F", $string);
         $string = str_replace("_", "=5F", $string);
         $string = str_replace(" ", "_", $string);

         for ( $ch = 127 ; $ch <= 255 ; $ch++ ) {
            $replace = chr($ch);
            $insert = sprintf("=%02X", $ch);
            $string = str_replace($replace, $insert, $string);
            $ch++;
         }

         $newstring = "=?$default_charset?Q?".$string."?=";

         return $newstring;
      }

      return $string;
   }

?>

====================================================
Index: mailbox_display.php
<?php

   /**
    **  mailbox_display.php
    **
    **  This contains functions that display mailbox information, such as the
    **  table row that has sender, date, subject, etc...
    **
    **  $Id: mailbox_display.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $
    **/

   $mailbox_display_php = true;

   function printMessageInfo($imapConnection, $t, $i, $msg, $mailbox, $sort, 
$startMessage, $where, $what) {
      global $checkall, $color, $msort, $sent_folder, $message_highlight_list, 
$index_order,
             $phpgw, $phpgw_info;

#      print "msg: ".$msg['ID'].";<br>";

//address@hidden: from in sent_folder is to
      $senderName = sqimap_find_displayable_name( ($mailbox == $sent_folder) ? 
$msg['TO'] : $msg['FROM']);
      $urlMailbox = urlencode($mailbox);
      $subject = trim($msg['SUBJECT']);
      if ($subject == '')
         $subject = lang("(no subject)");

      echo "<TR>\n";

      if (isset($msg['FLAG_FLAGGED']) && $msg['FLAG_FLAGGED'] == true)
      {
         $flag = "<font color=$color[2]>";
         $flag_end = '</font>';
      }
      else
      {
         $flag = '';
         $flag_end = '';
      }
      if (!isset($msg['FLAG_SEEN']) || $msg['FLAG_SEEN'] == false)
      {
         $bold = '<b>';
         $bold_end = '</b>';
      }
      else
      {
         $bold = '';
         $bold_end = '';
      }
      if ($mailbox == $sent_folder)
      {
         $italic = '<i>';
         $italic_end = '</i>';
      }
      else
      {
         $italic = '';
         $italic_end = '';
      }
      if (isset($msg['FLAG_DELETED']) && $msg['FLAG_DELETED'])
      {
         $fontstr = "<font color=\"$color[9]\">";
         $fontstr_end = '</font>';
      }
      else
      {
         $fontstr = '';
         $fontstr_end = '';
      }

      for ($i=0; $i < count($message_highlight_list); $i++) {
         if (trim($message_highlight_list[$i]['value']) != '') {
            if ($message_highlight_list[$i]['match_type'] == 'to_cc') {
               if (strpos('^^'.strtolower($msg['TO']), 
strtolower($message_highlight_list[$i]['value'])) || 
strpos('^^'.strtolower($msg['CC']), 
strtolower($message_highlight_list[$i]['value']))) {
                  $hlt_color = $message_highlight_list[$i]['color'];
                  continue;
               }
            } else if 
(strpos('^^'.strtolower($msg[strtoupper($message_highlight_list[$i]['match_type'])]),strtolower($message_highlight_list[$i]['value'])))
 {
               $hlt_color = $message_highlight_list[$i]['color'];
               continue;
            }
         }
      }

      if (!isset($hlt_color))
         $hlt_color = $color[4];

      if ($where && $what) {
         $search_stuff = '&where='.urlencode($where).'&what='.urlencode($what);
      }

      if ($checkall == 1)
         $checked = ' checked';
      else
         $checked = '';

      for ($i=1; $i <= count($index_order); $i++) {
         switch ($index_order[$i]) {
            case 1: # checkbox
               echo "   <td width=1% bgcolor=$hlt_color align=center><input 
type=checkbox name=\"msg[$t]\" value=".$msg["ID"]."$checked></TD>\n";
               break;
            case 2: # from
               echo "   <td width=30% 
bgcolor=$hlt_color>$italic$bold$flag$fontstr$senderName$fontstr_end$flag_end$bold_end$italic_end</td>\n";
               break;
            case 3: # date
               echo "   <td nowrap width=1% 
bgcolor=$hlt_color><center>$bold$flag$fontstr".$msg["DATE_STRING"]."$fontstr_end$flag_end$bold_end</center></td>\n";
               break;
            case 4: # subject
               $htmlSubject = str_replace("\"","''",$subject);
               echo "   <td bgcolor=$hlt_color>$bold";
                   if (! isset($search_stuff)) { $search_stuff = ''; }
               echo "<a href=\"" .
                        $phpgw->link('/squirrelmail/read_body.php',
                                
"mailbox=$urlMailbox&passed_id=".$msg["ID"]."&startMessage=$startMessage&show_more=0$search_stuff")
 .
                                "\" title=\"$htmlSubject\" ";
               do_hook("subject_link");
               echo ">$flag";
               if (strlen($subject) > 55)
                   echo substr($subject, 0, 50) . '...';
               else
                      echo $subject;
               echo "$flag_end</a>$bold_end</td>\n";
               break;
            case 5: # flags
               $stuff = false;
               echo "   <td bgcolor=$hlt_color align=center width=1% 
nowrap><b><small>\n";
               if (isset($msg['FLAG_ANSWERED']) &&
                   $msg['FLAG_ANSWERED'] == true) {
                  echo "A\n";
                  $stuff = true;
               }
               if ($msg['TYPE0'] == 'multipart') {
                  echo "+\n";
                  $stuff = true;
               }
               if (ereg('(1|2)',substr($msg['PRIORITY'],0,1))) {
                  echo "<font color=$color[1]>!</font>\n";
                  $stuff = true;
               }
               if (isset($msg['FLAG_DELETED']) && $msg['FLAG_DELETED']) {
                  echo "<font color=\"$color[1]\">D</font>\n";
                  $stuff = true;
               }

               if (!$stuff) echo "&nbsp;\n";
               echo "</small></b></td>\n";
               break;
            case 6: # size
               echo "   <td bgcolor=$hlt_color 
width=1%>$bold$fontstr".show_readable_size($msg['SIZE'])."$fontstr_end$bold_end</td>\n";
               break;
         }
      }


      echo "</tr>\n";
   }

        /**
         ** This function loops through a group of messages in the mailbox and 
shows them
         **/
        function showMessagesForMailbox($imapConnection, $mailbox, 
$numMessages, $startMessage, $sort, $color,$show_num, $use_cache)
        {
                global $msgs, $msort;
                global $sent_folder;
                global $mailboxStatus, $username, $key, $imapServerAddress, 
$imapPort;
                global $auto_expunge;
                global $phpgw, $phpgw_info;

                switch($sort)
                {
                        case "0":
                                $imapSort = SORTARRIVAL;
                                $reverse  = 1;
                                break;
                        case "1":
                                $imapSort = SORTARRIVAL;
                                $reverse  = 0;
                                break;
                        case "2":
                                $imapSort = SORTFROM;
                                $reverse  = 1;
                                break;
                        case "3":
                                $imapSort = SORTFROM;
                                $reverse  = 0;
                                break;
                        case "4":
                                $imapSort = SORTSUBJECT;
                                $reverse  = 1;
                                break;
                        case "5":
                                $imapSort = SORTSUBJECT;
                                $reverse  = 0;
                                break;
                        default:
                                $imapSort = SORTDATE;
                                $reverse  = 1;
                                break;
                }


                $mbox = imap_open 
("{".$imapServerAddress.":$imapPort}$mailbox", $username, $key);
                $status = imap_status ($mbox, 
"{".$imapServerAddress.":$imapPort}$mailbox", SA_ALL);

                if(($status->uidnext != $mailboxStatus["$mailbox"]["uidnext"]) 
||
                   ($sort != $mailboxStatus["$mailbox"]["sort"]) ||
                   ($status->messages != 
$mailboxStatus["$mailbox"]["messages"]))
                {
                        //address@hidden: next line prevents non-sorting (bug) 
in php-4.0.6
                        imap_mailboxmsginfo($mbox);
                        $sortedList = imap_sort($mbox,$imapSort,$reverse);
                        $mailboxStatus["$mailbox"]["sortedList"] = $sortedList;
                        #print "get new messagelist<br>";
                }
                else
                {
                        $sortedList = $mailboxStatus["$mailbox"]["sortedList"];
                        #print "reuse messagelist<br>";
                }

                $mailboxStatus["$mailbox"]["uidnext"] = $status->uidnext;
                $mailboxStatus["$mailbox"]["messages"] = $status->messages;
                $mailboxStatus["$mailbox"]["unseen"] = $status->unseen;
                $mailboxStatus["$mailbox"]["sort"] = $sort;

                $phpgw->session->register("mailboxStatus");

                if ($startMessage+$show_num > $numMessages) 
$show_num=$numMessages-$startMessage+1;

                for ($i=$startMessage-1;$i<($startMessage+$show_num)-1;$i++)
                {
                        $header = imap_header ($mbox,$sortedList[$i]);
#                       while(list($key, $value) = each($header))
#                       {
#                               print "$key: $value<br>";
#                       }

                        if (isset($header->date))
                        {
                                $header->date = ereg_replace('  ', ' ', 
$header->date);
                                $tmpdate = explode(' ', trim($header->date));
                        }
                        else
                        {
                                $tmpdate = $date = array("","","","","","");
                        }

                        if ($header->Deleted == "D")            
$msgs[$i]['FLAG_DELETED'] = true;
                        if ($header->Answered == "A")           
$msgs[$i]['FLAG_ANSWERED'] = true;
                        if ($header->Unseen != "U")     $msgs[$i]['FLAG_SEEN'] 
= true;
                        if ($header->Flagged == "F")            
$msgs[$i]['FLAG_FLAGGED'] = true;

                        $msgs[$i]['TIME_STAMP'] = getTimeStamp($tmpdate);
                        $msgs[$i]['DATE_STRING'] = 
$phpgw->common->show_date($msgs[$i]['TIME_STAMP']);
                        $msgs[$i]['ID'] = trim($header->Msgno);
                        $msgs[$i]['FROM'] = decodeHeader($header->fromaddress);
                        #print "$i: ";
                        $msgs[$i]['SUBJECT'] = decodeHeader($header->subject);
                        #print "<br>";
                        $msgs[$i]['TO'] = decodeHeader($header->toaddress);
                        $msgs[$i]['CC'] = decodeHeader($header->ccaddress);
                        $msgs[$i]['SIZE'] = $header->Size;

                        /*
                            i think these are not needed

                            $messages[$j]['FROM-SORT'] = 
strtolower(sqimap_find_displayable_name(decodeHeader($from[$j])));
                            $messages[$j]['SUBJECT-SORT'] = 
strtolower(decodeHeader($subject[$j]));
                            $messages[$j]['PRIORITY'] = $priority[$j];
                            $messages[$j]['TYPE0'] = $type[$j];
                        */

                }
                imap_close($mbox);


                displayMessageArray($imapConnection, $numMessages, 
$startMessage, $msgs, $msort, $mailbox, $sort, $color,$show_num);

        }



   // generic function to convert the msgs array into an HTML table
   function displayMessageArray($imapConnection, $numMessages, $startMessage, 
&$msgs, $msort, $mailbox, $sort, $color,$show_num)
   {
      global $folder_prefix, $sent_folder, $imapServerAddress, $index_order, 
$real_endMessage,
             $real_startMessage, $checkall, $enablePHPGW, $phpgw, $phpgw_info;

      if ($startMessage + ($show_num - 1) < $numMessages) {
         $endMessage = $startMessage + ($show_num-1);
      } else {
         $endMessage = $numMessages;
      }

      if ($endMessage < $startMessage) {
         $startMessage = $startMessage - $show_num;
         if ($startMessage < 1)
            $startMessage = 1;
      }

      $nextGroup = $startMessage + $show_num;
      $prevGroup = $startMessage - $show_num;
      $urlMailbox = urlencode($mailbox);

      do_hook('mailbox_index_before');

      $Message = '';
      if ($startMessage < $endMessage) {
         $Message = lang("Viewing messages") ." <B>$startMessage</B> - 
<B>$endMessage</B> ($numMessages " . lang("total") . ")\n";
      } elseif ($startMessage == $endMessage) {
         $Message = lang("Viewing message") ." <B>$startMessage</B> 
($numMessages " . lang("total") . ")\n";
      }

      $More = '';
      if ($sort == 6) {
         $use = 0;
      } else {
         $use = 1;
      }

      $target="TARGET=\"_self\"";

      if (($nextGroup <= $numMessages) && ($prevGroup >= 0)) {
         $More = "<A HREF=\"" . 
$phpgw->link('/squirrelmail/index.php',"use_mailbox_cache=$use&startMessage=$prevGroup&mailbox=$urlMailbox")
 . "\" $target>". lang("Previous") ."</A> | \n";
         $More .= "<A HREF=\"" . 
$phpgw->link('/squirrelmail/index.php',"use_mailbox_cache=$use&&startMessage=$nextGroup&mailbox=$urlMailbox")
 . "\" $target>". lang("Next") ."</A>\n";
      }
      elseif (($nextGroup > $numMessages) && ($prevGroup >= 0)) {
         $More = "<A HREF=\"" . 
$phpgw->link('/squirrelmail/index.php',"use_mailbox_cache=$use&startMessage=$prevGroup&mailbox=$urlMailbox")
 . "\" $target>". lang("Previous") ."</A> | \n";
         $More .= "<FONT COLOR=\"$color[9]\">".lang("Next")."</FONT>\n";
      }
      elseif (($nextGroup <= $numMessages) && ($prevGroup < 0)) {
         $More = "<FONT COLOR=\"$color[9]\">".lang("Previous")."</FONT> | \n";
         $More .= "<A HREF=\"" . 
$phpgw->link('/squirrelmail/index.php',"use_mailbox_cache=$use&startMessage=$nextGroup&mailbox=$urlMailbox")
 . "\" $target>". lang("Next") ."</A>\n";
      }

      if (! isset($msg))
          $msg = "";
      
mail_message_listing_beginning($imapConnection,$phpgw->link('/squirrelmail/src/move_messages.php',"msg=$msg&mailbox=$urlMailbox&startMessage=$startMessage"),
          $mailbox, $sort, $Message, $More, $startMessage);

      $groupNum = $startMessage % ($show_num - 1);
      $real_startMessage = $startMessage;

      $endVar = $endMessage + 1;

      // loop through and display the info for each message.
      $t = 0; // $t is used for the checkbox number
      if ($numMessages == 0) { // if there's no messages in this folder
         echo "<TR><TD BGCOLOR=\"$color[4]\" COLSPAN=" . count($index_order);
         echo "><CENTER><BR><B>". lang("THIS FOLDER IS EMPTY") 
."</B><BR>&nbsp;</CENTER></TD></TR>";
      } else if ($startMessage == $endMessage) { // if there's only one message 
in the box, handle it different.
//address@hidden: I do not see any reason for making this a special case
//address@hidden: $key should relate to startMessage ...
         $key = $startMessage-1;
         printMessageInfo($imapConnection, $t, $i, $msgs[$key], $mailbox, 
$sort, $real_startMessage, 0, 0);
      } else {
        for ($key=$startMessage-1;$key<($startMessage+$show_num)-1;$key++)
        {
#               print "k$key: ".$msgs[$key]['SUBJECT']."<br>";
                printMessageInfo($imapConnection, $t, $i, $msgs[$key], 
$mailbox, $sort, $real_startMessage, 0, 0);
                $t++;
        }
      }
      echo '</TABLE>';

      echo "</td></tr>\n";

      echo "<TR BGCOLOR=\"$color[4]\"><TD>";
      echo '<table width="100%" cellpadding="0" cellspacing="0" 
border="0"><tr><td>';
      echo "$More</td><td align=right>\n";
      if (!$startMessage) $startMessage=1;
      if ( $checkall == '1')
         echo "\n<A HREF=\"" . 
$phpgw->link('/squirrelmail/index.php',"mailbox=$urlMailbox&startMessage=$real_startMessage&sort=$sort")
 . "\">" . lang("Unselect All") . "</A>\n";
      else
         echo "\n<A HREF=\"" . 
$phpgw->link('/squirrelmail/index.php',"mailbox=$urlMailbox&startMessage=$real_startMessage&sort=$sort&checkall=1")
 . "\">" . lang("Select All") . "</A>\n";

      echo '</td></tr></table>';
      echo '</td></tr>';
      echo '</table>'; /** End of message-list table */

      do_hook('mailbox_index_after');
   }

        /* Displays the standard message list header.
        * To finish the table, you need to do a "</table></table>";
        * $moveURL is the URL to submit the delete/move form to
        * $mailbox is the current mailbox
        * $sort is the current sorting method (-1 for no sorting available 
[searches])
        * $Message is a message that is centered on top of the list
        * $More is a second line that is left aligned
        */
        function mail_message_listing_beginning($imapConnection, $moveURL,
                $mailbox = '', $sort = -1, $Message = '', $More = '', 
$startMessage = 1)
        {
                global $color, $index_order, $auto_expunge, $move_to_trash, 
$checkall, $sent_folder,
                $phpgw, $phpgw_info, $trash_folder;

                $urlMailbox = urlencode($mailbox);

                $t = CreateObject('phpgwapi.Template',PHPGW_APP_TPL);
                #$t->set_unknowns('remove');

                $t->set_file(array('header' => 'view_main.tpl'));
                $t->set_block('header','main_navbar','main_navbar');

                $t->set_var('row_on',$phpgw_info['theme']['row_on']);
                $t->set_var('row_off',$phpgw_info['theme']['row_off']);
                $t->set_var('more',$More);
                if ($Message)
                {
                        $t->set_var('message',$Message);
                }
                else
                {
                        $t->set_var('message','&nbsp;');
                }

                if ($mailbox == $trash_folder && $move_to_trash)
                {
                        $t->set_var('trash_link',
                                '<a 
href="'.$phpgw->link('/squirrelmail/index.php',"mailbox=$urlMailbox&startMessage=$startMessage&sort=$sort&expunge=1").'">'.lang("empty
 trash").'</a>');
                }
                else
                {
                        $t->set_var('trash_link','&nbsp;');
                }

                if ($checkall == '1')
                {
                        $t->set_var('select_all_link',
                                "<A HREF=\"" . 
$phpgw->link('/squirrelmail/index.php',"mailbox=$urlMailbox&startMessage=$startMessage&sort=$sort")
 . "\">" . lang("Unselect All") . "</A>");
                }
                else
                {
                        $t->set_var('select_all_link',
                                "<A HREF=\"" . 
$phpgw->link('/squirrelmail/index.php',"mailbox=$urlMailbox&startMessage=$startMessage&sort=$sort&checkall=1")
 . "\">" . lang("Select All") . "</A>");
                }

                $t->set_var('moveURL',$moveURL);
                $t->set_var('lang_move_selected_to',lang("move selected to"));

                $boxes = sqimap_mailbox_list($imapConnection);
                for ($i = 0; $i < count($boxes); $i++)
                {
                        if (!in_array("noselect", $boxes[$i]["flags"]))
                        {
                                $box = $boxes[$i]['unformatted'];
                                $box2 = 
replace_spaces($boxes[$i]['unformatted-disp']);
                                $options_targetMailbox .= "<OPTION 
VALUE=\"$box\">$box2</option>\n";
                        }
                }
                $t->set_var('options_target_mailbox',$options_targetMailbox);

                $t->set_var('lang_move',lang("move"));
                $t->set_var('lang_follow',lang("follow"));
                if (! $auto_expunge)
                {
                        $t->set_var('expunge',
                                '<NOBR><SMALL><INPUT TYPE=SUBMIT 
NAME="expungeButton" VALUE="'. lang("Expunge") .'">&nbsp;'. lang("mailbox") 
."</SMALL></NOBR>&nbsp;&nbsp;");
                }
                else
                {
                        $t->set_var('expunge','');
                }
                $t->set_var('image_path',PHPGW_IMAGES);
                $t->set_var('desc_read',lang("mark selected as read"));
                $t->set_var('desc_unread',lang("mark selected as unread"));
                $t->set_var('desc_important',lang("mark selected as flagged"));
                $t->set_var('desc_unimportant',lang("mark selected as 
unflagged"));
                $t->set_var('desc_deleted',lang("delete selected"));


                $t->pparse('out','main_navbar');

                // what to do with these hooks

                //echo "</TABLE>\n";
                // this is before the header line (date, subject, from, size)
                //do_hook('mailbox_form_before');
                //echo '</TD></TR>';

                echo "<TR><TD BGCOLOR=\"$color[0]\">";
                echo "<TABLE WIDTH=100% BORDER=0 CELLPADDING=2 CELLSPACING=1 
BGCOLOR=\"$color[0]\">";
                echo "<TR BGCOLOR=\"$color[5]\" ALIGN=\"center\">";

                $urlMailbox=urlencode($mailbox);

                $up_pointer_gif = 
$GLOBALS['phpgw']->common->image('squirrelmail','up_pointer.gif');
                $down_pointer_gif = 
$GLOBALS['phpgw']->common->image('squirrelmail','down_pointer.gif');
                $sort_none_gif = 
$GLOBALS['phpgw']->common->image('squirrelmail','sort_none.gif');

                // Print the headers
                for ($i=1; $i <= count($index_order); $i++)
                {
                        switch ($index_order[$i])
                        {
                                case 1: # checkbox
                                case 5: # flags
                                        echo '   <TD 
WIDTH="1%"><B>&nbsp;</B></TD>';
                                        break;

                                case 2: # from
                                        if ($mailbox == $sent_folder)
                                                echo '   <TD WIDTH="30%"><B>'. 
lang("To") .'</B>';
                                        else
                                                echo '   <TD WIDTH="30%"><B>'. 
lang("From") .'</B>';

                                        if ($sort == 2)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/index.php',"newsort=3&startMessage=1&mailbox=$urlMailbox")
 . "\"><IMG SRC=\"$up_pointer_gif\" BORDER=0></A></TD>\n";
                                        elseif ($sort == 3)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/index.php',"newsort=2&startMessage=1&mailbox=$urlMailbox")
 . "\"><IMG SRC=\"$down_pointer_gif\" BORDER=0></A></TD>\n";
                                        elseif ($sort != -1)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/index.php',"newsort=3&startMessage=1&mailbox=$urlMailbox")
 . "\"><IMG SRC=\"$sort_none_gif\" BORDER=0></A></TD>\n";
                                        echo "</TD>";
                                        break;

                                case 3: # date
                                        echo '   <TD nowrap WIDTH="1%"><B>'. 
lang("Date") .'</B>';
                                        if ($sort == 0)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/index.php',"newsort=1&startMessage=1&mailbox=$urlMailbox")
 . "\"><IMG SRC=\"$up_pointer_gif\" BORDER=0></A></TD>\n";
                                        elseif ($sort == 1)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/index.php',"newsort=6&startMessage=1&mailbox=$urlMailbox")
 . "\"><IMG SRC=\"$down_pointer_gif\" BORDER=0></A></TD>\n";
                                        elseif ($sort == 6)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/index.php',"newsort=0&startMessage=1&mailbox=$urlMailbox")
 . "\"><IMG SRC=\"$sort_none_gif\" BORDER=0></A></TD>\n";
                                        elseif ($sort != -1)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/index.php',"newsort=0&startMessage=1&mailbox=$urlMailbox")
 . "\"><IMG SRC=\"$sort_none_gif\" BORDER=0></A></TD>\n";
                                        echo '</TD>';
                                        break;

                                case 4: # subject
                                        echo '   <TD WIDTH=%><B>'. 
lang("Subject") ."</B>\n";
                                        if ($sort == 4)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/index.php',"newsort=5&startMessage=1&mailbox=$urlMailbox")
 . "\"><IMG SRC=\"$up_pointer_gif\" BORDER=0></A></TD>\n";
                                        elseif ($sort == 5)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/index.php',"newsort=4&startMessage=1&mailbox=$urlMailbox")
 . "\"><IMG SRC=\"$down_pointer_gif\" BORDER=0></A></TD>\n";
                                        elseif ($sort != -1)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/index.php',"newsort=5&startMessage=1&mailbox=$urlMailbox")
 . "\"><IMG SRC=\"$sort_none_gif\" BORDER=0></A></TD>\n";
                                        echo "</TD>";
                                        break;

                                case 6: # size
                                        echo '   <TD WIDTH="1%"><b>' . 
lang("Size")."</b></TD>\n";
                                        break;
                        }
                }
                echo "</TR>\n";
        }

// new listing for search form

        /* Displays the standard message list header.
        * To finish the table, you need to do a "</table></table>";
        * $moveURL is the URL to submit the delete/move form to
        * $mailbox is the current mailbox
        * $sort is the current sorting method (-1 for no sorting available 
[searches])
        * $Message is a message that is centered on top of the list
        * $More is a second line that is left aligned
        */
        function mail_message_search_listing_beginning($imapConnection,
                $moveURL, $mailbox = '', $sort = -1,
                $Message = '', $More = '', $startMessage = 1,
                $where = '', $what = '')
        {
                global $color, $index_order, $auto_expunge, $move_to_trash, 
$checkall, $sent_folder,
                $phpgw, $phpgw_info, $trash_folder;

                $urlMailbox = urlencode($mailbox);

                $t = CreateObject('phpgwapi.Template',PHPGW_APP_TPL);
                #$t->set_unknowns('remove');

                $t->set_file(array('header' => 'view_main.tpl'));
                $t->set_block('header','main_navbar','main_navbar');

                $t->set_var('row_on',$phpgw_info['theme']['row_on']);
                $t->set_var('row_off',$phpgw_info['theme']['row_off']);
                $t->set_var('more',$More);
                if ($Message)
                {
                        $t->set_var('message',$Message);
                }
                else
                {
                        $t->set_var('message','&nbsp;');
                }

                if ($mailbox == $trash_folder && $move_to_trash)
                {
                        $t->set_var('trash_link',
                                '<a 
href="'.$phpgw->link('/squirrelmail/search.php',"mailbox=$urlMailbox&what=".urlencode($what)."&where=".urlencode($where)."&sort=$sort&expunge=1").'">'.lang("empty
 trash").'</a>');
                }
                else
                {
                        $t->set_var('trash_link','&nbsp;');
                }

                if ($checkall == '1')
                {
                        $t->set_var('select_all_link',
                                '<a 
HREF="'.$phpgw->link('/squirrelmail/search.php',"mailbox=$urlMailbox&what=".urlencode($what)."&where=".urlencode($where)."&sort=$sort").'">'.lang("Unselect
 All").'</a>');
                }
                else
                {
                        $t->set_var('select_all_link',
                                '<a 
HREF="'.$phpgw->link('/squirrelmail/search.php',"mailbox=$urlMailbox&what=".urlencode($what)."&where=".urlencode($where)."&sort=$sort&checkall=1").'">'.lang("Select
 All").'</a>');
                }

                $t->set_var('moveURL',$moveURL);
                $t->set_var('lang_move_selected_to',lang("move selected to"));

                $boxes = sqimap_mailbox_list($imapConnection);
                for ($i = 0; $i < count($boxes); $i++)
                {
                        if (!in_array("noselect", $boxes[$i]["flags"]))
                        {
                                $box = $boxes[$i]['unformatted'];
                                $box2 = 
replace_spaces($boxes[$i]['unformatted-disp']);
                                $options_targetMailbox .= "<OPTION 
VALUE=\"$box\">$box2</option>\n";
                        }
                }
                $t->set_var('options_target_mailbox',$options_targetMailbox);

                $t->set_var('lang_move',lang("move"));
                $t->set_var('lang_follow',lang("follow"));
                if (! $auto_expunge)
                {
                        $t->set_var('expunge',
                                '<NOBR><SMALL><INPUT TYPE=SUBMIT 
NAME="expungeButton" VALUE="'. lang("Expunge") .'">&nbsp;'. lang("mailbox") 
."</SMALL></NOBR>&nbsp;&nbsp;");
                }
                else
                {
                        $t->set_var('expunge','');
                }

                $t->set_var('image_path',PHPGW_IMAGES);
                $t->set_var('desc_read',lang("mark selected as read"));
                $t->set_var('desc_unread',lang("mark selected as unread"));
                $t->set_var('desc_important',lang("mark selected as flagged"));
                $t->set_var('desc_unimportant',lang("mark selected as 
unflagged"));


                $t->pparse('out','main_navbar');

                // what to do with these hooks

                //echo "</TABLE>\n";
                // this is before the header line (date, subject, from, size)
                //do_hook('mailbox_form_before');
                //echo '</TD></TR>';

                echo "<TR><TD BGCOLOR=\"$color[0]\">";
                echo "<TABLE WIDTH=100% BORDER=0 CELLPADDING=2 CELLSPACING=1 
BGCOLOR=\"$color[0]\">";
                echo "<TR BGCOLOR=\"$color[5]\" ALIGN=\"center\">";

                $urlMailbox=urlencode($mailbox);

                // Print the headers
                for ($i=1; $i <= count($index_order); $i++)
                {
                        switch ($index_order[$i])
                        {
                                case 1: # checkbox
                                case 5: # flags
                                        echo '   <TD 
WIDTH="1%"><B>&nbsp;</B></TD>';
                                        break;

                                case 2: # from
                                        if ($mailbox == $sent_folder)
                                                echo '   <TD WIDTH="30%"><B>'. 
lang("To") .'</B>';
                                        else
                                                echo '   <TD WIDTH="30%"><B>'. 
lang("From") .'</B>';

                                        if ($sort == 2)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/search.php',"newsort=3&startMessage=1&mailbox=$urlMailbox&where=$where&what=$what")
 . "\"><IMG SRC=\"images/up_pointer.gif\" BORDER=0></A></TD>\n";
                                        elseif ($sort == 3)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/search.php',"newsort=2&startMessage=1&mailbox=$urlMailbox&where=$where&what=$what")
 . "\"><IMG SRC=\"images/down_pointer.gif\" BORDER=0></A></TD>\n";
                                        elseif ($sort != -1)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/search.php',"newsort=3&startMessage=1&mailbox=$urlMailbox&where=$where&what=$what")
 . "\"><IMG SRC=\"images/sort_none.gif\" BORDER=0></A></TD>\n";
                                        echo "</TD>";
                                        break;

                                case 3: # date
                                        echo '   <TD nowrap WIDTH="1%"><B>'. 
lang("Date") .'</B>';
                                        if ($sort == 0)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/search.php',"newsort=1&startMessage=1&mailbox=$urlMailbox&where=$where&what=$what")
 . "\"><IMG SRC=\"images/up_pointer.gif\" BORDER=0></A></TD>\n";
                                        elseif ($sort == 1)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/search.php',"newsort=6&startMessage=1&mailbox=$urlMailbox&where=$where&what=$what")
 . "\"><IMG SRC=\"images/down_pointer.gif\" BORDER=0></A></TD>\n";
                                        elseif ($sort == 6)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/search.php',"newsort=0&startMessage=1&mailbox=$urlMailbox&where=$where&what=$what")
 . "\"><IMG SRC=\"images/sort_none.gif\" BORDER=0></A></TD>\n";
                                        elseif ($sort != -1)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/search.php',"newsort=0&startMessage=1&mailbox=$urlMailbox&where=$where&what=$what")
 . "\"><IMG SRC=\"images/sort_none.gif\" BORDER=0></A></TD>\n";
                                        echo '</TD>';
                                        break;

                                case 4: # subject
                                        echo '   <TD WIDTH=%><B>'. 
lang("Subject") ."</B>\n";
                                        if ($sort == 4)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/search.php',"newsort=5&startMessage=1&mailbox=$urlMailbox&where=$where&what=$what")
 . "\"><IMG SRC=\"images/up_pointer.gif\" BORDER=0></A></TD>\n";
                                        elseif ($sort == 5)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/search.php',"newsort=4&startMessage=1&mailbox=$urlMailbox&where=$where&what=$what")
 . "\"><IMG SRC=\"images/down_pointer.gif\" BORDER=0></A></TD>\n";
                                        elseif ($sort != -1)
                                                echo "   <A HREF=\"" . 
$phpgw->link('/squirrelmail/search.php',"newsort=5&startMessage=1&mailbox=$urlMailbox&where=$where&what=$what")
 . "\"><IMG SRC=\"images/sort_none.gif\" BORDER=0></A></TD>\n";
                                        echo "</TD>";
                                        break;

                                case 6: # size
                                        echo '   <TD WIDTH="1%"><b>' . 
lang("Size")."</b></TD>\n";
                                        break;
                        }
                }
                echo "</TR>\n";
        }
?>

====================================================
Index: i18n.php
<?php

/**
 ** i18n.php
 **
 ** This file contains variuos functions that are needed to do
 ** internationalization of SquirrelMail.
 **
 ** Internally the output character set is used. Other characters are
 ** encoded using Unicode entities according to HTML 4.0.
 **
 ** $Id: i18n.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $
 **/

   $i18n_php = true;
   if (! isset($squirrelmail_language)) { $squirrelmail_language = ''; }

   // This array specifies the available languages.
   $languages['en']['NAME']    = 'English';
   $languages['en']['CHARSET'] = 'iso-8859-1';

   $languages['ca']['NAME']    = 'Catalan';
   $languages['ca']['CHARSET'] = 'iso-8859-1';

   $languages['cs_CZ']['NAME']    = 'Czech';
   $languages['cs_CZ']['CHARSET'] = 'iso-8859-2';

   $languages['da']['NAME']    = 'Danish';
   $languages['da']['CHARSET'] = 'iso-8859-1';

   $languages['de']['NAME']    = 'Deutsch';
   $languages['de']['CHARSET'] = 'iso-8859-1';

   $languages['nl']['NAME']    = 'Dutch';
   $languages['nl']['CHARSET'] = 'iso-8859-1';

   $languages['fr']['NAME']    = 'French';
   $languages['fr']['CHARSET'] = 'iso-8859-1';

   $languages['fi']['NAME']    = 'Finnish';
   $languages['fi']['CHARSET'] = 'iso-8859-1';

   $languages['it']['NAME']    = 'Italian';
   $languages['it']['CHARSET'] = 'iso-8859-1';

   $languages['ko']['NAME']    = 'Korean';
   $languages['ko']['CHARSET'] = 'euc-KR';

   $languages['no']['NAME']    = 'Norwegian (Bokm&aring;l)';
   $languages['no']['CHARSET'] = 'iso-8859-1';

   $languages['no_NO_ny']['NAME']    = 'Norwegian (Nynorsk)';
   $languages['no_NO_ny']['CHARSET'] = 'iso-8859-1';

   $languages['pl']['NAME']    = 'Polish';
   $languages['pl']['CHARSET'] = 'iso-8859-2';

   $languages['pt_BR']['NAME']    = 'Portuguese (Brazil)';
   $languages['pt_BR']['CHARSET'] = 'iso-8859-1';

   $languages['ru']['NAME']    = 'Russian KOI8-R';
   $languages['ru']['CHARSET'] = 'koi8-r';

   $languages['sr']['NAME']    = 'Serbian';
   $languages['sr']['CHARSET'] = 'iso-8859-2';

   $languages['es']['NAME']    = 'Spanish';
   $languages['es']['CHARSET'] = 'iso-8859-1';

   $languages['sv']['NAME']    = 'Swedish';
   $languages['sv']['CHARSET'] = 'iso-8859-1';

   $languages['tw']['NAME']    = 'Taiwan';
   $languages['tw']['CHARSET'] = 'big5';


   // Decodes a string to the internal encoding from the given charset
   function charset_decode ($charset, $string) {
      global $debug_mime;

      // All HTML special characters are 7 bit and can be replaced first
      $string = htmlspecialchars ($string);

      $charset = strtolower($charset);

      if ($debug_mime) $string = $charset . ':' . $string;

      if (ereg('iso-8859-([[:digit:]]+)', $charset, $res)) {
         if ($res[1] == '1')
            return charset_decode_iso_8859_1 ($string);
         else if ($res[1] == '2')
            return charset_decode_iso_8859_2 ($string);
         else if ($res[1] == '7')
            return charset_decode_iso_8859_7 ($string);
         else if ($res[1] == '15')
            return charset_decode_iso_8859_15 ($string);
         else
            return charset_decode_iso_8859_default ($string);
      } else if ($charset == 'ns_4551-1') {
         return charset_decode_ns_4551_1 ($string);
      } else if ($charset == 'koi8-r') {
        return charset_decode_koi8r ($string);
      } else
         return $string;
   }

   // iso-8859-1 is the same as Latin 1 and is normally used
   // in western europe.
   function charset_decode_iso_8859_1 ($string) {
      global $default_charset;

      if (strtolower($default_charset) == 'iso-8859-1') {
         return $string;
      } else {
         // Only do the slow convert if there are 8-bit characters
         if (ereg("[\200-\377]", $string)) {
            $string = str_replace("\201", '&#129;', $string);
            $string = str_replace("\202", '&#130;', $string);
            $string = str_replace("\203", '&#131;', $string);
            $string = str_replace("\204", '&#132;', $string);
            $string = str_replace("\205", '&#133;', $string);
            $string = str_replace("\206", '&#134;', $string);
            $string = str_replace("\207", '&#135;', $string);
            $string = str_replace("\210", '&#136;', $string);
            $string = str_replace("\211", '&#137;', $string);
            $string = str_replace("\212", '&#138;', $string);
            $string = str_replace("\213", '&#139;', $string);
            $string = str_replace("\214", '&#140;', $string);
            $string = str_replace("\215", '&#141;', $string);
            $string = str_replace("\216", '&#142;', $string);
            $string = str_replace("\217", '&#143;', $string);
            $string = str_replace("\220", '&#144;', $string);
            $string = str_replace("\221", '&#145;', $string);
            $string = str_replace("\222", '&#146;', $string);
            $string = str_replace("\223", '&#147;', $string);
            $string = str_replace("\224", '&#148;', $string);
            $string = str_replace("\225", '&#149;', $string);
            $string = str_replace("\226", '&#150;', $string);
            $string = str_replace("\227", '&#151;', $string);
            $string = str_replace("\230", '&#152;', $string);
            $string = str_replace("\231", '&#153;', $string);
            $string = str_replace("\232", '&#154;', $string);
            $string = str_replace("\233", '&#155;', $string);
            $string = str_replace("\234", '&#156;', $string);
            $string = str_replace("\235", '&#157;', $string);
            $string = str_replace("\236", '&#158;', $string);
            $string = str_replace("\237", '&#159;', $string);
            $string = str_replace("\240", '&#160;', $string);
            $string = str_replace("\241", '&#161;', $string);
            $string = str_replace("\242", '&#162;', $string);
            $string = str_replace("\243", '&#163;', $string);
            $string = str_replace("\244", '&#164;', $string);
            $string = str_replace("\245", '&#165;', $string);
            $string = str_replace("\246", '&#166;', $string);
            $string = str_replace("\247", '&#167;', $string);
            $string = str_replace("\250", '&#168;', $string);
            $string = str_replace("\251", '&#169;', $string);
            $string = str_replace("\252", '&#170;', $string);
            $string = str_replace("\253", '&#171;', $string);
            $string = str_replace("\254", '&#172;', $string);
            $string = str_replace("\255", '&#173;', $string);
            $string = str_replace("\256", '&#174;', $string);
            $string = str_replace("\257", '&#175;', $string);
            $string = str_replace("\260", '&#176;', $string);
            $string = str_replace("\261", '&#177;', $string);
            $string = str_replace("\262", '&#178;', $string);
            $string = str_replace("\263", '&#179;', $string);
            $string = str_replace("\264", '&#180;', $string);
            $string = str_replace("\265", '&#181;', $string);
            $string = str_replace("\266", '&#182;', $string);
            $string = str_replace("\267", '&#183;', $string);
            $string = str_replace("\270", '&#184;', $string);
            $string = str_replace("\271", '&#185;', $string);
            $string = str_replace("\272", '&#186;', $string);
            $string = str_replace("\273", '&#187;', $string);
            $string = str_replace("\274", '&#188;', $string);
            $string = str_replace("\275", '&#189;', $string);
            $string = str_replace("\276", '&#190;', $string);
            $string = str_replace("\277", '&#191;', $string);
            $string = str_replace("\300", '&#192;', $string);
            $string = str_replace("\301", '&#193;', $string);
            $string = str_replace("\302", '&#194;', $string);
            $string = str_replace("\303", '&#195;', $string);
            $string = str_replace("\304", '&#196;', $string);
            $string = str_replace("\305", '&#197;', $string);
            $string = str_replace("\306", '&#198;', $string);
            $string = str_replace("\307", '&#199;', $string);
            $string = str_replace("\310", '&#200;', $string);
            $string = str_replace("\311", '&#201;', $string);
            $string = str_replace("\312", '&#202;', $string);
            $string = str_replace("\313", '&#203;', $string);
            $string = str_replace("\314", '&#204;', $string);
            $string = str_replace("\315", '&#205;', $string);
            $string = str_replace("\316", '&#206;', $string);
            $string = str_replace("\317", '&#207;', $string);
            $string = str_replace("\320", '&#208;', $string);
            $string = str_replace("\321", '&#209;', $string);
            $string = str_replace("\322", '&#210;', $string);
            $string = str_replace("\323", '&#211;', $string);
            $string = str_replace("\324", '&#212;', $string);
            $string = str_replace("\325", '&#213;', $string);
            $string = str_replace("\326", '&#214;', $string);
            $string = str_replace("\327", '&#215;', $string);
            $string = str_replace("\330", '&#216;', $string);
            $string = str_replace("\331", '&#217;', $string);
            $string = str_replace("\332", '&#218;', $string);
            $string = str_replace("\333", '&#219;', $string);
            $string = str_replace("\334", '&#220;', $string);
            $string = str_replace("\335", '&#221;', $string);
            $string = str_replace("\336", '&#222;', $string);
            $string = str_replace("\337", '&#223;', $string);
            $string = str_replace("\340", '&#224;', $string);
            $string = str_replace("\341", '&#225;', $string);
            $string = str_replace("\342", '&#226;', $string);
            $string = str_replace("\343", '&#227;', $string);
            $string = str_replace("\344", '&#228;', $string);
            $string = str_replace("\345", '&#229;', $string);
            $string = str_replace("\346", '&#230;', $string);
            $string = str_replace("\347", '&#231;', $string);
            $string = str_replace("\350", '&#232;', $string);
            $string = str_replace("\351", '&#233;', $string);
            $string = str_replace("\352", '&#234;', $string);
            $string = str_replace("\353", '&#235;', $string);
            $string = str_replace("\354", '&#236;', $string);
            $string = str_replace("\355", '&#237;', $string);
            $string = str_replace("\356", '&#238;', $string);
            $string = str_replace("\357", '&#239;', $string);
            $string = str_replace("\360", '&#240;', $string);
            $string = str_replace("\361", '&#241;', $string);
            $string = str_replace("\362", '&#242;', $string);
            $string = str_replace("\363", '&#243;', $string);
            $string = str_replace("\364", '&#244;', $string);
            $string = str_replace("\365", '&#245;', $string);
            $string = str_replace("\366", '&#246;', $string);
            $string = str_replace("\367", '&#247;', $string);
            $string = str_replace("\370", '&#248;', $string);
            $string = str_replace("\371", '&#249;', $string);
            $string = str_replace("\372", '&#250;', $string);
            $string = str_replace("\373", '&#251;', $string);
            $string = str_replace("\374", '&#252;', $string);
            $string = str_replace("\375", '&#253;', $string);
            $string = str_replace("\376", '&#254;', $string);
            $string = str_replace("\377", '&#255;', $string);
         }
      }

      return ($string);
   }

   // iso-8859-2 is used for some eastern European languages
   function charset_decode_iso_8859_2 ($string) {
      global $default_charset;

      if (strtolower($default_charset) == 'iso-8859-2') {
         return $string;
      } else {
         // Only do the slow convert if there are 8-bit characters
         if (ereg("[\200-\377]", $string)) {
            // NO-BREAK SPACE
            $string = str_replace("\240", '&#160;', $string);
            // LATIN CAPITAL LETTER A WITH OGONEK
            $string = str_replace("\241", '&#260;', $string);
            // BREVE
            $string = str_replace("\242", '&#728;', $string);
            // LATIN CAPITAL LETTER L WITH STROKE
            $string = str_replace("\243", '&#321;', $string);
            // CURRENCY SIGN
            $string = str_replace("\244", '&#164;', $string);
            // LATIN CAPITAL LETTER L WITH CARON
            $string = str_replace("\245", '&#317;', $string);
            // LATIN CAPITAL LETTER S WITH ACUTE
            $string = str_replace("\246", '&#346;', $string);
            // SECTION SIGN
            $string = str_replace("\247", '&#167;', $string);
            // DIAERESIS
            $string = str_replace("\250", '&#168;', $string);
            // LATIN CAPITAL LETTER S WITH CARON
            $string = str_replace("\251", '&#352;', $string);
            // LATIN CAPITAL LETTER S WITH CEDILLA
            $string = str_replace("\252", '&#350;', $string);
            // LATIN CAPITAL LETTER T WITH CARON
            $string = str_replace("\253", '&#356;', $string);
            // LATIN CAPITAL LETTER Z WITH ACUTE
            $string = str_replace("\254", '&#377;', $string);
            // SOFT HYPHEN
            $string = str_replace("\255", '&#173;', $string);
            // LATIN CAPITAL LETTER Z WITH CARON
            $string = str_replace("\256", '&#381;', $string);
            // LATIN CAPITAL LETTER Z WITH DOT ABOVE
            $string = str_replace("\257", '&#379;', $string);
            // DEGREE SIGN
            $string = str_replace("\260", '&#176;', $string);
            // LATIN SMALL LETTER A WITH OGONEK
            $string = str_replace("\261", '&#261;', $string);
            // OGONEK
            $string = str_replace("\262", '&#731;', $string);
            // LATIN SMALL LETTER L WITH STROKE
            $string = str_replace("\263", '&#322;', $string);
            // ACUTE ACCENT
            $string = str_replace("\264", '&#180;', $string);
            // LATIN SMALL LETTER L WITH CARON
            $string = str_replace("\265", '&#318;', $string);
            // LATIN SMALL LETTER S WITH ACUTE
            $string = str_replace("\266", '&#347;', $string);
            // CARON
            $string = str_replace("\267", '&#711;', $string);
            // CEDILLA
            $string = str_replace("\270", '&#184;', $string);
            // LATIN SMALL LETTER S WITH CARON
            $string = str_replace("\271", '&#353;', $string);
            // LATIN SMALL LETTER S WITH CEDILLA
            $string = str_replace("\272", '&#351;', $string);
            // LATIN SMALL LETTER T WITH CARON
            $string = str_replace("\273", '&#357;', $string);
            // LATIN SMALL LETTER Z WITH ACUTE
            $string = str_replace("\274", '&#378;', $string);
            // DOUBLE ACUTE ACCENT
            $string = str_replace("\275", '&#733;', $string);
            // LATIN SMALL LETTER Z WITH CARON
            $string = str_replace("\276", '&#382;', $string);
            // LATIN SMALL LETTER Z WITH DOT ABOVE
            $string = str_replace("\277", '&#380;', $string);
            // LATIN CAPITAL LETTER R WITH ACUTE
            $string = str_replace("\300", '&#340;', $string);
            // LATIN CAPITAL LETTER A WITH ACUTE
            $string = str_replace("\301", '&#193;', $string);
            // LATIN CAPITAL LETTER A WITH CIRCUMFLEX
            $string = str_replace("\302", '&#194;', $string);
            // LATIN CAPITAL LETTER A WITH BREVE
            $string = str_replace("\303", '&#258;', $string);
            // LATIN CAPITAL LETTER A WITH DIAERESIS
            $string = str_replace("\304", '&#196;', $string);
            // LATIN CAPITAL LETTER L WITH ACUTE
            $string = str_replace("\305", '&#313;', $string);
            // LATIN CAPITAL LETTER C WITH ACUTE
            $string = str_replace("\306", '&#262;', $string);
            // LATIN CAPITAL LETTER C WITH CEDILLA
            $string = str_replace("\307", '&#199;', $string);
            // LATIN CAPITAL LETTER C WITH CARON
            $string = str_replace("\310", '&#268;', $string);
            // LATIN CAPITAL LETTER E WITH ACUTE
            $string = str_replace("\311", '&#201;', $string);
            // LATIN CAPITAL LETTER E WITH OGONEK
            $string = str_replace("\312", '&#280;', $string);
            // LATIN CAPITAL LETTER E WITH DIAERESIS
            $string = str_replace("\313", '&#203;', $string);
            // LATIN CAPITAL LETTER E WITH CARON
            $string = str_replace("\314", '&#282;', $string);
            // LATIN CAPITAL LETTER I WITH ACUTE
            $string = str_replace("\315", '&#205;', $string);
            // LATIN CAPITAL LETTER I WITH CIRCUMFLEX
            $string = str_replace("\316", '&#206;', $string);
            // LATIN CAPITAL LETTER D WITH CARON
            $string = str_replace("\317", '&#270;', $string);
            // LATIN CAPITAL LETTER D WITH STROKE
            $string = str_replace("\320", '&#272;', $string);
            // LATIN CAPITAL LETTER N WITH ACUTE
            $string = str_replace("\321", '&#323;', $string);
            // LATIN CAPITAL LETTER N WITH CARON
            $string = str_replace("\322", '&#327;', $string);
            // LATIN CAPITAL LETTER O WITH ACUTE
            $string = str_replace("\323", '&#211;', $string);
            // LATIN CAPITAL LETTER O WITH CIRCUMFLEX
            $string = str_replace("\324", '&#212;', $string);
            // LATIN CAPITAL LETTER O WITH DOUBLE ACUTE
            $string = str_replace("\325", '&#336;', $string);
            // LATIN CAPITAL LETTER O WITH DIAERESIS
            $string = str_replace("\326", '&#214;', $string);
            // MULTIPLICATION SIGN
            $string = str_replace("\327", '&#215;', $string);
            // LATIN CAPITAL LETTER R WITH CARON
            $string = str_replace("\330", '&#344;', $string);
            // LATIN CAPITAL LETTER U WITH RING ABOVE
            $string = str_replace("\331", '&#366;', $string);
            // LATIN CAPITAL LETTER U WITH ACUTE
            $string = str_replace("\332", '&#218;', $string);
            // LATIN CAPITAL LETTER U WITH DOUBLE ACUTE
            $string = str_replace("\333", '&#368;', $string);
            // LATIN CAPITAL LETTER U WITH DIAERESIS
            $string = str_replace("\334", '&#220;', $string);
            // LATIN CAPITAL LETTER Y WITH ACUTE
            $string = str_replace("\335", '&#221;', $string);
            // LATIN CAPITAL LETTER T WITH CEDILLA
            $string = str_replace("\336", '&#354;', $string);
            // LATIN SMALL LETTER SHARP S
            $string = str_replace("\337", '&#223;', $string);
            // LATIN SMALL LETTER R WITH ACUTE
            $string = str_replace("\340", '&#341;', $string);
            // LATIN SMALL LETTER A WITH ACUTE
            $string = str_replace("\341", '&#225;', $string);
            // LATIN SMALL LETTER A WITH CIRCUMFLEX
            $string = str_replace("\342", '&#226;', $string);
            // LATIN SMALL LETTER A WITH BREVE
            $string = str_replace("\343", '&#259;', $string);
            // LATIN SMALL LETTER A WITH DIAERESIS
            $string = str_replace("\344", '&#228;', $string);
            // LATIN SMALL LETTER L WITH ACUTE
            $string = str_replace("\345", '&#314;', $string);
            // LATIN SMALL LETTER C WITH ACUTE
            $string = str_replace("\346", '&#263;', $string);
            // LATIN SMALL LETTER C WITH CEDILLA
            $string = str_replace("\347", '&#231;', $string);
            // LATIN SMALL LETTER C WITH CARON
            $string = str_replace("\350", '&#269;', $string);
            // LATIN SMALL LETTER E WITH ACUTE
            $string = str_replace("\351", '&#233;', $string);
            // LATIN SMALL LETTER E WITH OGONEK
            $string = str_replace("\352", '&#281;', $string);
            // LATIN SMALL LETTER E WITH DIAERESIS
            $string = str_replace("\353", '&#235;', $string);
            // LATIN SMALL LETTER E WITH CARON
            $string = str_replace("\354", '&#283;', $string);
            // LATIN SMALL LETTER I WITH ACUTE
            $string = str_replace("\355", '&#237;', $string);
            // LATIN SMALL LETTER I WITH CIRCUMFLEX
            $string = str_replace("\356", '&#238;', $string);
            // LATIN SMALL LETTER D WITH CARON
            $string = str_replace("\357", '&#271;', $string);
            // LATIN SMALL LETTER D WITH STROKE
            $string = str_replace("\360", '&#273;', $string);
            // LATIN SMALL LETTER N WITH ACUTE
            $string = str_replace("\361", '&#324;', $string);
            // LATIN SMALL LETTER N WITH CARON
            $string = str_replace("\362", '&#328;', $string);
            // LATIN SMALL LETTER O WITH ACUTE
            $string = str_replace("\363", '&#243;', $string);
            // LATIN SMALL LETTER O WITH CIRCUMFLEX
            $string = str_replace("\364", '&#244;', $string);
            // LATIN SMALL LETTER O WITH DOUBLE ACUTE
            $string = str_replace("\365", '&#337;', $string);
            // LATIN SMALL LETTER O WITH DIAERESIS
            $string = str_replace("\366", '&#246;', $string);
            // DIVISION SIGN
            $string = str_replace("\367", '&#247;', $string);
            // LATIN SMALL LETTER R WITH CARON
            $string = str_replace("\370", '&#345;', $string);
            // LATIN SMALL LETTER U WITH RING ABOVE
            $string = str_replace("\371", '&#367;', $string);
            // LATIN SMALL LETTER U WITH ACUTE
            $string = str_replace("\372", '&#250;', $string);
            // LATIN SMALL LETTER U WITH DOUBLE ACUTE
            $string = str_replace("\373", '&#369;', $string);
            // LATIN SMALL LETTER U WITH DIAERESIS
            $string = str_replace("\374", '&#252;', $string);
            // LATIN SMALL LETTER Y WITH ACUTE
            $string = str_replace("\375", '&#253;', $string);
            // LATIN SMALL LETTER T WITH CEDILLA
            $string = str_replace("\376", '&#355;', $string);
            // DOT ABOVE
            $string = str_replace("\377", '&#729;', $string);
         }
      }
      return $string;
   }

   // iso-8859-7 is Greek.
   function charset_decode_iso_8859_7 ($string) {
      global $default_charset;

      if (strtolower($default_charset) == 'iso-8859-7') {
         return $string;
      } else {
         // Only do the slow convert if there are 8-bit characters
         if (ereg("[\200-\377]", $string)) {
            // Some diverse characters in the beginning
            $string = str_replace("\240", '&#160;', $string);
            $string = str_replace("\241", '&#8216;', $string);
            $string = str_replace("\242", '&#8217;', $string);
            $string = str_replace("\243", '&#163;', $string);
            $string = str_replace("\246", '&#166;', $string);
            $string = str_replace("\247", '&#167;', $string);
            $string = str_replace("\250", '&#168;', $string);
            $string = str_replace("\251", '&#169;', $string);
            $string = str_replace("\253", '&#171;', $string);
            $string = str_replace("\254", '&#172;', $string);
            $string = str_replace("\255", '&#173;', $string);
            $string = str_replace("\257", '&#8213;', $string);
            $string = str_replace("\260", '&#176;', $string);
            $string = str_replace("\261", '&#177;', $string);
            $string = str_replace("\262", '&#178;', $string);
            $string = str_replace("\263", '&#179;', $string);

            // Horizontal bar (parentheki pavla)
            $string = str_replace ("\257", '&#8213;', $string);

            // ISO-8859-7 characters from 11/04 (0xB4) to 11/06 (0xB6)
            // These are Unicode 900-902
            while (ereg("([\264-\266])", $string, $res)) {
               $replace = '&#' . (ord($res[1])+720) . ';';
               $string = str_replace($res[1], $replace, $string);
            }

            // 11/07 (0xB7) Middle dot is the same in iso-8859-1
            $string = str_replace("\267", '&#183;', $string);

            // ISO-8859-7 characters from 11/08 (0xB8) to 11/10 (0xBA)
            // These are Unicode 900-902
            while (ereg("([\270-\272])", $string, $res)) {
               $replace = '&#' . (ord($res[1])+720) . ";";
               $string = str_replace($res[1], $replace, $string);
            }

            // 11/11 (0xBB) Right angle quotation mark is the same as in
            // iso-8859-1
            $string = str_replace("\273", '&#187;', $string);

            // And now the rest of the charset
            while (ereg("([\274-\376])", $string, $res)) {
               $replace = '&#' . (ord($res[1])+720) . ';';
               $string = str_replace($res[1], $replace, $string);
            }
         }
      }

      return $string;
   }

   // iso-8859-15 is Latin 9 and has very much the same use as Latin 1
   // but has the Euro symbol and some characters needed for French.
   function charset_decode_iso_8859_15 ($string) {
      // Euro sign
      $string = str_replace ("\244", '&#8364;', $string);
      // Latin capital letter S with caron
      $string = str_replace ("\244", '&#352;', $string);
      // Latin small letter s with caron
      $string = str_replace ("\250", '&#353;', $string);
      // Latin capital letter Z with caron
      $string = str_replace ("\264", '&#381;', $string);
      // Latin small letter z with caron
      $string = str_replace ("\270", '&#382;', $string);
      // Latin capital ligature OE
      $string = str_replace ("\274", '&#338;', $string);
      // Latin small ligature oe
      $string = str_replace ("\275", '&#339;', $string);
      // Latin capital letter Y with diaeresis
      $string = str_replace ("\276", '&#376;', $string);

      return (charset_decode_iso_8859_1($string));
   }

   // ISO-8859-15 is Cyrillic
   function charset_decode_iso_8859_5 ($string) {
      // Convert to KOI8-R, then return this decoded.
      $string = convert_cyr_string($string, 'i', 'k');
      return charset_decode_koi8r($string);
   }

   // Remove all 8 bit characters from all other ISO-8859 character sets
   function charset_decode_iso_8859_default ($string) {
      return (strtr($string, "\240\241\242\243\244\245\246\247".
                    "\250\251\252\253\254\255\256\257".
                    "\260\261\262\263\264\265\266\267".
                    "\270\271\272\273\274\275\276\277".
                    "\300\301\302\303\304\305\306\307".
                    "\310\311\312\313\314\315\316\317".
                    "\320\321\322\323\324\325\326\327".
                    "\330\331\332\333\334\335\336\337".
                    "\340\341\342\343\344\345\346\347".
                    "\350\351\352\353\354\355\356\357".
                    "\360\361\362\363\364\365\366\367".
                    "\370\371\372\373\374\375\376\377",
                    "????????????????????????????????????????".
                    "????????????????????????????????????????".
                    "????????????????????????????????????????".
                    "????????"));

   }

   // This is the same as ISO-646-NO and is used by some
   // Microsoft programs when sending Norwegian characters
   function charset_decode_ns_4551_1 ($string) {
      // These characters are:
      // Latin capital letter AE
      // Latin capital letter O with stroke
      // Latin capital letter A with ring above
      // and the same as small letters
      return strtr ($string, "[\\]{|}", "ÆØÅæøå");
   }

   // KOI8-R is used to encode Russian mail (Cyrrilic). Defined in RFC
   // 1489.
   function charset_decode_koi8r ($string) {
      global $default_charset;

      if ($default_charset == 'koi8-r') {
         return $string;
      } else {
         // Convert to Unicode HTML entities.
         // This code is rather ineffective.
         $string = str_replace("\200", '&#9472;', $string);
         $string = str_replace("\201", '&#9474;', $string);
         $string = str_replace("\202", '&#9484;', $string);
         $string = str_replace("\203", '&#9488;', $string);
         $string = str_replace("\204", '&#9492;', $string);
         $string = str_replace("\205", '&#9496;', $string);
         $string = str_replace("\206", '&#9500;', $string);
         $string = str_replace("\207", '&#9508;', $string);
         $string = str_replace("\210", '&#9516;', $string);
         $string = str_replace("\211", '&#9524;', $string);
         $string = str_replace("\212", '&#9532;', $string);
         $string = str_replace("\213", '&#9600;', $string);
         $string = str_replace("\214", '&#9604;', $string);
         $string = str_replace("\215", '&#9608;', $string);
         $string = str_replace("\216", '&#9612;', $string);
         $string = str_replace("\217", '&#9616;', $string);
         $string = str_replace("\220", '&#9617;', $string);
         $string = str_replace("\221", '&#9618;', $string);
         $string = str_replace("\222", '&#9619;', $string);
         $string = str_replace("\223", '&#8992;', $string);
         $string = str_replace("\224", '&#9632;', $string);
         $string = str_replace("\225", '&#8729;', $string);
         $string = str_replace("\226", '&#8730;', $string);
         $string = str_replace("\227", '&#8776;', $string);
         $string = str_replace("\230", '&#8804;', $string);
         $string = str_replace("\231", '&#8805;', $string);
         $string = str_replace("\232", '&#160;', $string);
         $string = str_replace("\233", '&#8993;', $string);
         $string = str_replace("\234", '&#176;', $string);
         $string = str_replace("\235", '&#178;', $string);
         $string = str_replace("\236", '&#183;', $string);
         $string = str_replace("\237", '&#247;', $string);
         $string = str_replace("\240", '&#9552;', $string);
         $string = str_replace("\241", '&#9553;', $string);
         $string = str_replace("\242", '&#9554;', $string);
         $string = str_replace("\243", '&#1105;', $string);
         $string = str_replace("\244", '&#9555;', $string);
         $string = str_replace("\245", '&#9556;', $string);
         $string = str_replace("\246", '&#9557;', $string);
         $string = str_replace("\247", '&#9558;', $string);
         $string = str_replace("\250", '&#9559;', $string);
         $string = str_replace("\251", '&#9560;', $string);
         $string = str_replace("\252", '&#9561;', $string);
         $string = str_replace("\253", '&#9562;', $string);
         $string = str_replace("\254", '&#9563;', $string);
         $string = str_replace("\255", '&#9564;', $string);
         $string = str_replace("\256", '&#9565;', $string);
         $string = str_replace("\257", '&#9566;', $string);
         $string = str_replace("\260", '&#9567;', $string);
         $string = str_replace("\261", '&#9568;', $string);
         $string = str_replace("\262", '&#9569;', $string);
         $string = str_replace("\263", '&#1025;', $string);
         $string = str_replace("\264", '&#9570;', $string);
         $string = str_replace("\265", '&#9571;', $string);
         $string = str_replace("\266", '&#9572;', $string);
         $string = str_replace("\267", '&#9573;', $string);
         $string = str_replace("\270", '&#9574;', $string);
         $string = str_replace("\271", '&#9575;', $string);
         $string = str_replace("\272", '&#9576;', $string);
         $string = str_replace("\273", '&#9577;', $string);
         $string = str_replace("\274", '&#9578;', $string);
         $string = str_replace("\275", '&#9579;', $string);
         $string = str_replace("\276", '&#9580;', $string);
         $string = str_replace("\277", '&#169;', $string);
         $string = str_replace("\300", '&#1102;', $string);
         $string = str_replace("\301", '&#1072;', $string);
         $string = str_replace("\302", '&#1073;', $string);
         $string = str_replace("\303", '&#1094;', $string);
         $string = str_replace("\304", '&#1076;', $string);
         $string = str_replace("\305", '&#1077;', $string);
         $string = str_replace("\306", '&#1092;', $string);
         $string = str_replace("\307", '&#1075;', $string);
         $string = str_replace("\310", '&#1093;', $string);
         $string = str_replace("\311", '&#1080;', $string);
         $string = str_replace("\312", '&#1081;', $string);
         $string = str_replace("\313", '&#1082;', $string);
         $string = str_replace("\314", '&#1083;', $string);
         $string = str_replace("\315", '&#1084;', $string);
         $string = str_replace("\316", '&#1085;', $string);
         $string = str_replace("\317", '&#1086;', $string);
         $string = str_replace("\320", '&#1087;', $string);
         $string = str_replace("\321", '&#1103;', $string);
         $string = str_replace("\322", '&#1088;', $string);
         $string = str_replace("\323", '&#1089;', $string);
         $string = str_replace("\324", '&#1090;', $string);
         $string = str_replace("\325", '&#1091;', $string);
         $string = str_replace("\326", '&#1078;', $string);
         $string = str_replace("\327", '&#1074;', $string);
         $string = str_replace("\330", '&#1100;', $string);
         $string = str_replace("\331", '&#1099;', $string);
         $string = str_replace("\332", '&#1079;', $string);
         $string = str_replace("\333", '&#1096;', $string);
         $string = str_replace("\334", '&#1101;', $string);
         $string = str_replace("\335", '&#1097;', $string);
         $string = str_replace("\336", '&#1095;', $string);
         $string = str_replace("\337", '&#1098;', $string);
         $string = str_replace("\340", '&#1070;', $string);
         $string = str_replace("\341", '&#1040;', $string);
         $string = str_replace("\342", '&#1041;', $string);
         $string = str_replace("\343", '&#1062;', $string);
         $string = str_replace("\344", '&#1044;', $string);
         $string = str_replace("\345", '&#1045;', $string);
         $string = str_replace("\346", '&#1060;', $string);
         $string = str_replace("\347", '&#1043;', $string);
         $string = str_replace("\350", '&#1061;', $string);
         $string = str_replace("\351", '&#1048;', $string);
         $string = str_replace("\352", '&#1049;', $string);
         $string = str_replace("\353", '&#1050;', $string);
         $string = str_replace("\354", '&#1051;', $string);
         $string = str_replace("\355", '&#1052;', $string);
         $string = str_replace("\356", '&#1053;', $string);
         $string = str_replace("\357", '&#1054;', $string);
         $string = str_replace("\360", '&#1055;', $string);
         $string = str_replace("\361", '&#1071;', $string);
         $string = str_replace("\362", '&#1056;', $string);
         $string = str_replace("\363", '&#1057;', $string);
         $string = str_replace("\364", '&#1058;', $string);
         $string = str_replace("\365", '&#1059;', $string);
         $string = str_replace("\366", '&#1046;', $string);
         $string = str_replace("\367", '&#1042;', $string);
         $string = str_replace("\370", '&#1068;', $string);
         $string = str_replace("\371", '&#1067;', $string);
         $string = str_replace("\372", '&#1047;', $string);
         $string = str_replace("\373", '&#1064;', $string);
         $string = str_replace("\374", '&#1069;', $string);
         $string = str_replace("\375", '&#1065;', $string);
         $string = str_replace("\376", '&#1063;', $string);
         $string = str_replace("\377", '&#1066;', $string);

         return $string;
      }
   }


   global $use_gettext;

   // Detect whether gettext is installed.
   // If it is, set the flag so we can use it.
   if (! function_exists('_') ||
       ! function_exists('bindtextdomain') ||
       ! function_exists('textdomain'))
       $use_gettext = false;
   else
       $use_gettext = true;


   if (! function_exists('bindtextdomain')) {
      function bindtextdomain() { return; }
   }
   if (! function_exists('textdomain')) {
      function textdomain() { return; }
   }


   // Set up the language to be output
   // if $do_search is true, then scan the browser information
   // for a possible language that we know
   function set_up_language($sm_language, $do_search = false)
   {
      static $SetupAlready = 0;
                global $HTTP_ACCEPT_LANGUAGE, $use_gettext, $languages, 
$squirrelmail_language;

      if ($SetupAlready)
         return;
      $SetupAlready = 1;

      if ($do_search && ! $sm_language && isset($HTTP_ACCEPT_LANGUAGE)) {
         $sm_language = substr($HTTP_ACCEPT_LANGUAGE, 0, 2);
      }

      if (isset($sm_language) && $use_gettext &&
         $squirrelmail_language != '' &&
         $languages[$sm_language]['CHARSET']) {
         if ((ini_get('safe_mode') == FALSE) && (getenv('LC_ALL') != 
$sm_language)) {
           putenv('LC_ALL=' . $sm_language);
         }
         setlocale('LC_ALL', $sm_language);
         bindtextdomain('squirrelmail', '../locale/');
         textdomain('squirrelmail');
         header ('Content-Type: text/html; charset=' . 
$languages[$sm_language]['CHARSET']);
      }
   }
?>

====================================================
Index: hook_preferences.inc.php
<?php
  /**************************************************************************\
  * phpGroupWare                                                             *
  * http://www.phpgroupware.org                                              *
  * Written by Joseph Engo <address@hidden>                          *
  * --------------------------------------------                             *
  *  This program is free software; you can redistribute it and/or modify it *
  *  under the terms of the GNU General Public License as published by the   *
  *  Free Software Foundation; either version 2 of the License, or (at your  *
  *  option) any later version.                                              *
  \**************************************************************************/

  /* $Id: hook_preferences.inc.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $ */
{
// Only Modify the $file and $title variables.....

                $title = $appname;
                $file = Array
                (
                        'Mail Settings' => 
$GLOBALS['phpgw']->link('/squirrelmail/preferences_email.php'),
                        'Message Highlighting'  => 
$GLOBALS['phpgw']->link('/squirrelmail/preferences_highlight.php'),
                        'Index Order'           => 
$GLOBALS['phpgw']->link('/squirrelmail/preferences_index_order.php'),
                        'Translation Preferences'       => 
$GLOBALS['phpgw']->link('/squirrelmail/preferences_translate.php'),
                        'Display Preferences'   => 
$GLOBALS['phpgw']->link('/squirrelmail/preferences_display.php'),
                        'Folder Preferences'    => 
$GLOBALS['phpgw']->link('/squirrelmail/preferences_folder.php'),
                        'Manage Folders'        => 
$GLOBALS['phpgw']->link('/squirrelmail/folders.php')
                );
//Do not modify below this line
                display_section($appname,$title,$file);
        }
?>

====================================================
Index: hook_home.inc.php
<?php
  /**************************************************************************\
  * phpGroupWare - E-Mail                                                    *
  * http://www.phpgroupware.org                                              *
  * --------------------------------------------                             *
  *  This program is free software; you can redistribute it and/or modify it *
  *  under the terms of the GNU General Public License as published by the   *
  *  Free Software Foundation; either version 2 of the License, or (at your  *
  *  option) any later version.                                              *
  \**************************************************************************/

        /* $Id: hook_home.inc.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $ */

        $d1 = strtolower(substr($phpgw_info['server']['app_inc'],0,3));
        if($d1 == 'htt' || $d1 == 'ftp' )
        {
                echo "Failed attempt to break in via an old Security 
Hole!<br>\n";
                $GLOBALS['phpgw']->common->phpgw_exit();
        }
        unset($d1);

        $tmp_app_inc = $GLOBALS['phpgw']->common->get_inc_dir('squirrelmail');

        if 
($GLOBALS['phpgw_info']['user']['preferences']['squirrelmail']['mainscreen_showmail']
 == True)
        {
                // ----  Create the base email Msg Class    -----
                $GLOBALS['phpgw']->msg = CreateObject("email.mail_msg");
                $args_array = Array();
                $args_array['folder'] = 'INBOX';
                $args_array['do_login'] = True;
                $GLOBALS['phpgw']->msg->begin_request($args_array);

                if (!$GLOBALS['phpgw']->msg->mailsvr_stream)
                {
                        $extra_data = '<b>Mail error:</b> Can not open 
connection to mail server';
                }
                else
                {
                        /*  class mail_msg "new_message_check()"
                          // this is the structure you will get
                          $inbox_data['is_imap'] boolean - pop3 server do not 
know what is "new" or not
                          $inbox_data['folder_checked'] string - the folder 
checked, as processed by the msg class
                          $inbox_data['alert_string'] string - what to show the 
user about this inbox check
                          $inbox_data['number_new'] integer - for IMAP is 
number "unseen"; for pop3 is number messages
                          $inbox_data['number_all'] integer - for IMAP and pop3 
is total number messages in that inbox
                        */
                        $inbox_data = Array();
                        $inbox_data = 
$GLOBALS['phpgw']->msg->new_message_check();

                        if($inbox_data['number_all'] >= 5)
                        {
                                $check_msgs = 5;
                        }
                        else
                        {
                                $check_msgs = $inbox_data['number_all'];
                        }

                        if ($inbox_data['number_all'] > 0)
                        {
                                $msg_nums_array = array();
                                $msg_nums_array = 
$GLOBALS['phpgw']->msg->get_message_list();
                        }

                        $app_id = 
$GLOBALS['phpgw']->applications->name2id('email');
                        $GLOBALS['portal_order'][] = $app_id;
                        $GLOBALS['phpgw']->portalbox->set_params(array('app_id' 
=> $app_id,
                                                                                
                                'title' => lang('email')));
                        $GLOBALS['phpgw']->portalbox->draw($extra_data);
                        for($i=0; $i<$check_msgs; $i++)
                        {
                                //$msg_headers = 
$GLOBALS['phpgw']->dcom->header($GLOBALS['phpgw']->msg->mailsvr_stream,$msg_nums_array[$i]);
                                $msg_headers = 
$GLOBALS['phpgw']->msg->phpgw_header($msg_nums_array[$i]);
                                $subject = 
$GLOBALS['phpgw']->msg->get_subject($msg_headers,'');
                                if (strlen($subject) > 65)
                                {
                                        $subject = substr($subject,0,65).' ...';
                                }

                                $linkData = array
                                (
                                        'mailbox'       => 
$GLOBALS['phpgw']->msg->prep_folder_out(''),
                                        'passed_id'     => $msg_nums_array[$i],
                                        'startMessage'  => 1,
                                        'show_more'     => 0
                                );

                                $GLOBALS['phpgw']->portalbox->data[$i] = array
                                (
                                        'text'=>$subject,
                                        
'link'=>$GLOBALS['phpgw']->link('/squirrelmail/read_body.php',$linkData)
                                );
                        }
                        // ADD FOLDER LISTBOX TO HOME PAGE (Needs to be 
TEMPLATED)
                        // Does This Mailbox Support Folders (i.e. more than 
just INBOX)?
                        if 
($GLOBALS['phpgw']->msg->get_mailsvr_supports_folders() == False)
                        {
                                $extra_data = '';
                        }
                        else
                        {
                                // FUTURE: this will pick up the user option to 
show num unseen msgs in dropdown list
                                //$listbox_show_unseen = True;
                                $listbox_show_unseen = False;
                                // build the $feed_args array for the 
all_folders_listbox function
                                // anything not specified will be replace with 
a default value if the function has one for that param
                                $feed_args = Array(
                                        'mailsvr_stream'        => '',
                                        'pre_select_folder'     => '',
                                        'skip_folder'           => '',
                                        'show_num_new'          => 
$listbox_show_unseen,
                                        //'widget_name'         => 'mailbox',
                                        'widget_name'           => 'folder',
                                        'on_change'             => 
'document.switchbox.submit()',
                                        'first_line_txt'        => lang('switch 
current folder to')
                                );
                                // get you custom built HTML listbox (a.k.a. 
selectbox) widget
                                $switchbox_listbox = 
$GLOBALS['phpgw']->msg->all_folders_listbox($feed_args);
                                // make it another TR we can insert into the 
home page portal object
                                // and surround it in FORM tage so the submit 
will work
                                $switchbox_action = 
$GLOBALS['phpgw']->link('/squirrelmail/index.php');
                                $extra_data =
                                        '<form name="switchbox" 
action="'.$switchbox_action.'" method="post">'."\r\n"
                                                .'<td align="left">'."\r\n"
                                                        .'&nbsp;<strong>E-Mail 
Folders:</strong>&nbsp;'.$switchbox_listbox
                                                .'</td>'."\r\n"
                                        .'</form>'."\r\n";
                        }
                        $GLOBALS['phpgw']->msg->end_request();
                }
                $GLOBALS['phpgw']->portalbox->draw($extra_data);
        }
?>

====================================================
Index: imap.php
<?php
   /**  This just includes the different sections of the imap functions.
    **  They have been organized into these sections for simplicity sake.
    **
    **  $Id: imap.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $
    **/

   $imap_php = true;
   $imap_backend = 'imap';

   include(PHPGW_APP_ROOT . '/inc/' . $imap_backend . '_mailbox.php');
   include(PHPGW_APP_ROOT . '/inc/' . $imap_backend . '_messages.php');
   include(PHPGW_APP_ROOT . '/inc/' . $imap_backend . '_general.php');
   include(PHPGW_APP_ROOT . '/inc/' . $imap_backend . '_search.php');
?>

====================================================
Index: imap_general.php
<?php
   /**
    **  imap.php
    **
    **  This implements all functions that do general imap functions.
    **
    **  $Id: imap_general.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $
    **/

   $imap_general_debug = false;

   
/******************************************************************************
    **  Reads the output from the IMAP stream.  If handle_errors is set to true,
    **  this will also handle all errors that are received.  If it is not set,
    **  the errors will be sent back through $response and $message
    
******************************************************************************/
   function sqimap_read_data ($imap_stream, $pre, $handle_errors, &$response, 
&$message) {
      global $color, $squirrelmail_language, $imap_general_debug;

      $read = fgets($imap_stream, 9096);

      if (ereg("^\\* [0-9]+ FETCH.*\\{([0-9]+)\\}", $read, $regs)) {
         $size = $regs[1];
      } else {
         $size = 0;
      }

      $data = array();
      $total_size = 0;
      $continue = true;
      while ($continue) {
         // Continue if needed for this single line
         while (strpos($read, "\n") === false) {
            $read .= fgets($imap_stream, 9096);
         }
         // For debugging purposes
         if ($imap_general_debug) {
            echo "<small><tt><font 
color=\"#CC0000\">$read</font></tt></small><br>\n";
            flush();
         }


         // If we know the size, no need to look at the end parameters
         if ($size > 0) {
            if ($total_size == $size) {
               $data[] = $read;
               $read = fgets($imap_stream, 9096);
               while (!ereg("^$pre (OK|BAD|NO)(.*)$", $read, $regs)) {
                  $read = fgets($imap_stream, 9096);
               }
               $continue = false;
            } else if ($total_size > $size) {
               $difference = $total_size - $size;
               $total_size = $total_size - strlen($read);
               $read = substr ($read, 0, strlen($read)-$difference);
               $data[] = $read;
               $junk = fgets($imap_stream, 9096);
               $continue = false;
            } else {
               $data[] = $read;
               $read = fgets($imap_stream, 9096);
            }
            $total_size += strlen($read);
         } else {
            if (ereg("^$pre (OK|BAD|NO)(.*)$", $read, $regs)) {
               $continue = false;
            } else {
               $data[] = $read;
               $read = fgets ($imap_stream, 9096);
            }
         }
      }

      $response = $regs[1];
      $message = trim($regs[2]);

      if ($imap_general_debug) echo '--<br>';

      if ($handle_errors == false)
          return $data;

      if ($response == 'NO') {
         // ignore this error from m$ exchange, it is not fatal (aka bug)
         if (!ereg('command resulted in',$message)) {
            set_up_language($squirrelmail_language);
            echo "<br><b><font color=$color[2]>\n";
            echo lang("ERROR : Could not complete request.");
            echo "</b><br>\n";
            echo lang("Reason Given: ");
            echo $message . "</font><br>\n";
            exit;
         }
      } else if ($response == 'BAD') {
         set_up_language($squirrelmail_language);
         echo "<br><b><font color=$color[2]>\n";
         echo lang("ERROR : Bad or malformed request.");
         echo "</b><br>\n";
         echo lang("Server responded: ");
         echo $message . "</font><br>\n";
         exit;
      }

      return $data;
   }

        
/******************************************************************************
         **  Logs the user into the imap server.  If $hide is set, no error 
messages
         **  will be displayed.  This function returns the imap connection 
handle.
         
******************************************************************************/
        function sqimap_login ($username, $password, $imap_server_address, 
$imap_port, $hide)
        {
                //echo 'username: ' . $username;
                //echo '<br>password: ' . $password;
                //echo '<br>imap_server_address: ' . $imap_server_address;
                //echo '<br>imap_port: ' . $imap_port;
                global $color, $squirrelmail_language, $HTTP_ACCEPT_LANGUAGE, 
$phpgw;

                $imap_stream = fsockopen ($imap_server_address, $imap_port, 
$error_number, $error_string, 15);
                $server_info = fgets ($imap_stream, 1024);

                /** Do some error correction **/
                if (!$imap_stream)
                {
                        if (!$hide)
                        {
                                set_up_language($squirrelmail_language, true);
                                printf (lang("Error connecting to IMAP server: 
%1.")."<br>\r\n", $imap_server_address);
                                echo "$error_number : $error_string<br>\r\n";
                        }
                        $phpgw->common->phpgw_exit(True);
                }

                fputs ($imap_stream, "a001 LOGIN \"" . quotemeta($username) . 
'" "' . quotemeta($password) . "\"\r\n");
                $read = sqimap_read_data ($imap_stream, 'a001', false, 
$response, $message);

                /** If the connection was not successful, lets see why **/
                if ($response != "OK")
                {
                        if (!$hide)
                        {
                                if ($response != 'NO')
                                {
                                        // "BAD" and anything else gets 
reported here.
                                        set_up_language($squirrelmail_language, 
true);
                                        if ($response == 'BAD')
                                        {
                                                printf (lang("Bad request: 
%1")."<br>\r\n", $message);
                                        }
                                        else
                                        {
                                                printf (lang("Unknown error: 
%1") . "<br>\n", $message);
                                                echo '<br>';
                                        }
                                        echo lang("Read data:") . "<br>\n";

                                        if (is_array($read))
                                        {
                                                foreach ($read as $line)
                                                {
                                                        echo 
htmlspecialchars($line) . "<br>\n";
                                                }
                                        }
                                        $phpgw->common->phpgw_exit(True);

                      } else {
                        echo '<b>' . lang('Invalid user name or password') . 
'</b>';
                                        $phpgw->common->phpgw_exit(True);
            }
         } else {
            $phpgw->common->phpgw_exit(True);
         }
      }

      return $imap_stream;
   }




   
/******************************************************************************
    **  Simply logs out the imap session
    
******************************************************************************/
   function sqimap_logout ($imap_stream) {
      fputs ($imap_stream, "a001 LOGOUT\r\n");
   }

function sqimap_capability($imap_stream, $capability) {
        global $sqimap_capabilities;
        global $imap_general_debug;

        if (!is_array($sqimap_capabilities)) {
                fputs ($imap_stream, "a001 CAPABILITY\r\n");
                $read = sqimap_read_data($imap_stream, 'a001', true, $a, $b);

                $c = explode(' ', $read[0]);
                for ($i=2; $i < count($c); $i++) {
                        $cap_list = explode('=', $c[$i]);
                        if (isset($cap_list[1]))
                            $sqimap_capabilities[$cap_list[0]] = $cap_list[1];
                        else
                            $sqimap_capabilities[$cap_list[0]] = TRUE;
                }
        }
        return $sqimap_capabilities[$capability];
}

   
/******************************************************************************
    **  Returns the delimeter between mailboxes:  INBOX/Test, or INBOX.Test...
    
******************************************************************************/
function sqimap_get_delimiter ($imap_stream = false) {
   global $imap_general_debug;
   global $sqimap_delimiter;
   global $optional_delimiter;

   /* Use configured delimiter if set */
   if((!empty($optional_delimiter)) && $optional_delimiter != "detect") {
      return $optional_delimiter;
   }

        /* Do some caching here */
    if (!$sqimap_delimiter) {
                if (sqimap_capability($imap_stream, "NAMESPACE")) {
                        /* According to something that I can't find, this is 
supposed to work on all systems
                           OS: This won't work in Courier IMAP.
                           OS:  According to rfc2342 response from NAMESPACE 
command is:
                           OS:  * NAMESPACE (PERSONAL NAMESPACES) (OTHER_USERS 
NAMESPACE) (SHARED NAMESPACES)
                           OS:  We want to lookup all personal NAMESPACES...
                        */
                        fputs ($imap_stream, "a001 NAMESPACE\r\n");
                        $read = sqimap_read_data($imap_stream, 'a001', true, 
$a, $b);
                        if (eregi('\* NAMESPACE +(\( *\(.+\) *\)|NIL) +(\( 
*\(.+\) *\)|NIL) +(\( *\(.+\) *\)|NIL)', $read[0], $data)) {
                                if (eregi('^\( *\((.*)\) *\)', $data[1], 
$data2))
                                        $pn = $data2[1];
                                $pna = explode(')(', $pn);
                                while (list($k, $v) = each($pna))
                                {
                    $lst = explode('"', $v);
                    if (isset($lst[3])) {
                        $pn[$lst[1]] = $lst[3];
                    } else {
                        $pn[$lst[1]] = '';
                    }
                                }
                        }
                        $sqimap_delimiter = $pn[0];
                } else {
                        fputs ($imap_stream, ". LIST \"INBOX\" \"\"\r\n");
                        $read = sqimap_read_data($imap_stream, '.', true, $a, 
$b);
                        $quote_position = strpos ($read[0], '"');
                        $sqimap_delimiter = substr ($read[0], 
$quote_position+1, 1);
                }
        }
        return $sqimap_delimiter;
}


   
/******************************************************************************
    **  Gets the number of messages in the current mailbox.
    
******************************************************************************/
   function sqimap_get_num_messages ($imap_stream, $mailbox) {
      fputs ($imap_stream, "a001 EXAMINE \"$mailbox\"\r\n");
      $read_ary = sqimap_read_data ($imap_stream, 'a001', true, $result, 
$message);
      for ($i = 0; $i < count($read_ary); $i++) {
         if (ereg("[^ ]+ +([^ ]+) +EXISTS", $read_ary[$i], $regs)) {
            return $regs[1];
         }
      }
      return "BUG!  Couldn't get number of messages in $mailbox!";
   }


   
/******************************************************************************
    **  Returns a displayable email address
    
******************************************************************************/
   function sqimap_find_email ($string) {
      /** Luke Ehresman <address@hidden>
       ** <address@hidden>
       ** address@hidden
       **
       ** What about
       **    address@hidden (Luke Ehresman)
       **/

      if (ereg("<([^>]+)>", $string, $regs)) {
          $string = $regs[1];
      }
      return trim($string);
   }


   
/******************************************************************************
    **  Takes the From: field, and creates a displayable name.
    **    Luke Ehresman <address@hidden>
    **           becomes:   Luke Ehresman
    **    <address@hidden>
    **           becomes:   address@hidden
    
******************************************************************************/
   function sqimap_find_displayable_name ($string) {
      $string = ' '.trim($string);
      $orig_string = $string;
      if (strpos($string, '<') && strpos($string, '>')) {
         if (strpos($string, '<') == 1) {
            $string = sqimap_find_email($string);
         } else {
            $string = trim($string);
            $string = substr($string, 0, strpos($string, '<'));
            $string = ereg_replace ('"', '', $string);
         }

         if (trim($string) == '') {
            $string = sqimap_find_email($orig_string);
         }
      }
      return $string;
   }


   
/******************************************************************************
    **  Returns the number of unseen messages in this folder
    
******************************************************************************/
   function sqimap_unseen_messages ($imap_stream, &$num_unseen, $mailbox) {
      //fputs ($imap_stream, "a001 SEARCH UNSEEN NOT DELETED\r\n");
      fputs ($imap_stream, "a001 STATUS \"$mailbox\" (UNSEEN)\r\n");
      $read_ary = sqimap_read_data ($imap_stream, 'a001', true, $result, 
$message);
      ereg("UNSEEN ([0-9]+)", $read_ary[0], $regs);
      return $regs[1];
   }


   
/******************************************************************************
    **  Saves a message to a given folder -- used for saving sent messages
    
******************************************************************************/
   function sqimap_append ($imap_stream, $sent_folder, $length) {
      fputs ($imap_stream, "a001 APPEND \"$sent_folder\" (\\Seen) 
\{$length}\r\n");
      $tmp = fgets ($imap_stream, 1024);
   }

   function sqimap_append_done ($imap_stream) {
      fputs ($imap_stream, "\r\n");
      $tmp = fgets ($imap_stream, 1024);
   }
?>

====================================================
Index: imap_search.php
<?php
/******************************************************************
 ** IMAP SEARCH ROUTIES
 ** $Id: imap_search.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $
 *****************************************************************/
        if (!isset($imap_php))
        {
                include(PHPGW_APP_ROOT . '/inc/imap.php');
        }

        if (!isset($date_php))
        {
                include(PHPGW_APP_ROOT . '/inc/date.php');
        }

        if (!isset($array_php))
        {
                include(PHPGW_APP_ROOT . '/inc/array.php');
        }

        if (!isset($mailbox_display_php))
        {
                include(PHPGW_APP_ROOT . '/inc/mailbox_display.php');
        }

        if (!isset($mime_php))
        {
                include(PHPGW_APP_ROOT . '/inc/mime.php');
        }

   $imap_search_php = true;

function 
sqimap_search($imapConnection,$search_where,$search_what,$mailbox,$color) {
   global $msgs, $message_highlight_list, $squirrelmail_language, $languages, 
$index_order;
//address@hidden: added global phpgw;
   global $phpgw;
   $urlMailbox = urlencode($mailbox);

   # Construct the Search QuERY

   if (isset($languages[$squirrelmail_language]["CHARSET"]) && 
$languages[$squirrelmail_language]["CHARSET"]) {
      $ss = "a001 SEARCH CHARSET 
".$languages[$squirrelmail_language]["CHARSET"]." ALL $search_where 
\"$search_what\"\r\n";
   } else {
      $ss = "a001 SEARCH ALL $search_where \"$search_what\"\r\n";
   }
   fputs($imapConnection,$ss);

   # Read Data Back From IMAP
   $readin = sqimap_read_data ($imapConnection, "a001", false, $result, 
$message);
   if (isset($languages[$squirrelmail_language]["CHARSET"]) && 
strtolower($result) == "no") {
      $ss = "a001 SEARCH CHARSET \"US-ASCII\" ALL $search_where 
\"$search_what\"\r\n";
      fputs ($imapConnection, $ss);
      $readin = sqimap_read_data ($imapConnection, "a001", true, $result, 
$message);
   }
   unset($messagelist); $msgs=""; $c = 0;

   #Keep going till we find the SEARCH responce
   while ($c < count($readin)) {

      #Check to see if a SEARCH Responce was recived
      if (substr($readin[$c],0,9) == "* SEARCH ")
         $messagelist = explode(" ",substr($readin[$c],9));
      else if (isset($errors))
         $errors = $errors.$readin[$c];
      else
         $errors = $readin[$c];
      $c++;
   }

   #If nothing is found * SEARCH should be the first error else echo errors
   if (isset($errors) && strstr($errors,"* SEARCH")) {
      echo "<br><CENTER>No Messages Found</CENTER>";
      return;
   } else if (isset($errors)) {
      echo "<!-- ".$errors." -->";
   }

   # HACKED CODED FROM ANOTHER FUNCTION, Could Probably dump this and mondify
   # exsitising code with a search true/false varible.


   global $sent_folder;
   for ($q = 0; $q < count($messagelist); $q++) {
      $messagelist[$q] = trim($messagelist[$q]);
      if ($mailbox == $sent_folder)
         $hdr = sqimap_get_small_header ($imapConnection, $messagelist[$q], 
true);
      else
         $hdr = sqimap_get_small_header ($imapConnection, $messagelist[$q], 
false);

         $from[$q] = $hdr->from;
         $date[$q] = $hdr->date;
         $subject[$q] = $hdr->subject;
         $to[$q] = $hdr->to;
         $priority[$q] = $hdr->priority;
         $cc[$q] = $hdr->cc;
                 $size[$q] = $hdr->size;
                 $type[$q] = $hdr->type0;
         $id[$q] = $messagelist[$q];
         $flags[$q] = sqimap_get_flags ($imapConnection, $messagelist[$q]);
      }

      $j = 0;
      while ($j < count($messagelist)) {
         $date[$j] = ereg_replace("  ", " ", $date[$j]);
         $tmpdate = explode(" ", trim($date[$j]));

         $messages[$j]["TIME_STAMP"] = getTimeStamp($tmpdate);
         $messages[$j]["DATE_STRING"] = 
getDateString($messages[$j]["TIME_STAMP"]);
         $messages[$j]["ID"] = $id[$j];
         $messages[$j]["FROM"] = decodeHeader($from[$j]);
         $messages[$j]["FROM-SORT"] = 
strtolower(sqimap_find_displayable_name(decodeHeader($from[$j])));
         $messages[$j]["SUBJECT"] = decodeHeader($subject[$j]);
         $messages[$j]["SUBJECT-SORT"] = strtolower(decodeHeader($subject[$j]));
         $messages[$j]["TO"] = decodeHeader($to[$j]);
         $messages[$j]["PRIORITY"] = $priority[$j];
         $messages[$j]["CC"] = $cc[$j];
                 $messages[$j]["SIZE"] = $size[$j];
                 $messages[$j]["TYPE0"] = $type[$j];

         $num = 0;
         while ($num < count($flags[$j])) {
            if ($flags[$j][$num] == "Deleted") {
               $messages[$j]["FLAG_DELETED"] = true;
            }
            else if ($flags[$j][$num] == "Answered") {
               $messages[$j]["FLAG_ANSWERED"] = true;
            }
            else if ($flags[$j][$num] == "Seen") {
               $messages[$j]["FLAG_SEEN"] = true;
            }
            else if ($flags[$j][$num] == "Flagged") {
               $messages[$j]["FLAG_FLAGGED"] = true;
            }
            $num++;
         }
         $j++;
      }

      /** Find and remove the ones that are deleted */
      $i = 0;
      $j = 0;
      while ($j < count($messagelist)) {
         if (isset($messages[$j]["FLAG_DELETED"]) && 
$messages[$j]["FLAG_DELETED"] == true) {
            $j++;
            continue;
         }
         $msgs[$i] = $messages[$j];

         $i++;
         $j++;
      }
      $numMessages = $i;

      // There's gotta be messages in the array for it to sort them.

      if (count($messagelist) > 0) {
         $j=0;
                 if (!isset ($msg)) { $msg = ""; }
//address@hidden: new function mail_message_SEARCH_listing_beginning
         mail_message_search_listing_beginning($imapConnection,
                $phpgw->link('/squirrelmail/src/move_messages.php',
                        "msg=$msg&mailbox=$urlMailbox&where="
                        .urlencode($search_where)."&what="
                        .urlencode($search_what)),
                $mailbox,
                -1,
                '<b>' . lang("Found") . ' '
                        . count($messagelist) . ' '
                        . lang("messages") . '</b>',
                '&nbsp;',
                '',
                urlencode($search_where),
                urlencode($search_what));
/*
//address@hidden: 'Select all', or better 'Invert Selection' is much quicker in 
Javacript ...
        $sel='function inv_sel() {
             for (i=0; i<document.delmov.elements.length; i++) {
                if (document.delmov.elements[i].type == "checkbox") {
                       if (document.delmov.elements[i].checked) {
                      document.delmov.elements[i].checked = false;
                   } else {
                      document.delmov.elements[i].checked = true;
                   }
                }
             }
         }';
*/


         while ($j < count($msgs)) {
            printMessageInfo($imapConnection, $msgs[$j]["ID"], 0, $msgs[$j], 
$mailbox, "", 0, $search_where, $search_what);
            $j++;
         }
         echo "</table>";
         echo "</tr></td></table>";
      }
   }

?>

====================================================
Index: imap_messages.php
<?php
   /**
    **  imap_messages.php
    **
    **  This implements functions that manipulate messages
    **
    **  $Id: imap_messages.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $
    **/

        if (! isset($mime_php))
   {
                include(PHPGW_APP_ROOT . '/inc/mime.php');
        }

   
/******************************************************************************
    **  Copies specified messages to specified folder
    
******************************************************************************/
   function sqimap_messages_copy ($imap_stream, $start, $end, $mailbox) {
      fputs ($imap_stream, "a001 COPY $start:$end \"$mailbox\"\r\n");
      $read = sqimap_read_data ($imap_stream, "a001", true, $response, 
$message);
   }

   
/******************************************************************************
    **  Deletes specified messages and moves them to trash if possible
    
******************************************************************************/
   function sqimap_messages_delete ($imap_stream, $start, $end, $mailbox) {
      global $move_to_trash, $trash_folder, $auto_expunge;

      if (($move_to_trash == true) && (sqimap_mailbox_exists($imap_stream, 
$trash_folder) && ($mailbox != $trash_folder))) {
         sqimap_messages_copy ($imap_stream, $start, $end, $trash_folder);
         sqimap_messages_flag ($imap_stream, $start, $end, "Deleted");
      } else {
         sqimap_messages_flag ($imap_stream, $start, $end, "Deleted");
      }
   }

   
/******************************************************************************
    **  Sets the specified messages with specified flag
    
******************************************************************************/
   function sqimap_messages_flag ($imap_stream, $start, $end, $flag) {
      fputs ($imap_stream, "a001 STORE $start:$end +FLAGS (\\$flag)\r\n");
      $read = sqimap_read_data ($imap_stream, "a001", true, $response, 
$message);
   }


   
/******************************************************************************
    **  Remove specified flag from specified messages
    
******************************************************************************/
   function sqimap_messages_remove_flag ($imap_stream, $start, $end, $flag) {
      fputs ($imap_stream, "a001 STORE $start:$end -FLAGS (\\$flag)\r\n");
      $read = sqimap_read_data ($imap_stream, "a001", true, $response, 
$message);
   }


   
/******************************************************************************
    **  Returns some general header information -- FROM, DATE, and SUBJECT
    
******************************************************************************/
   class small_header {
      var $from = '', $subject = '', $date = '', $to = '',
          $priority = 0, $message_id = 0, $cc = '';
   }

   function sqimap_get_small_header ($imap_stream, $id, $sent) {

      fputs ($imap_stream, "a001 FETCH $id BODY.PEEK[HEADER.FIELDS (Date To 
From Cc Subject Message-Id X-Priority Content-Type)]\r\n");
      $read = sqimap_read_data ($imap_stream, "a001", true, $response, 
$message);

      $subject = lang("(no subject)");
      $from = lang("Unknown Sender");
      $priority = "0";
      $messageid = "<>";
      $cc = "";
      $to = "";
      $date = "";
      $type[0] = "";
      $type[1] = "";

      $g = 0;
      for ($i = 0; $i < count($read); $i++) {
         if (eregi ("^to:(.*)$", $read[$i], $regs)) {
            //$to = sqimap_find_displayable_name(substr($read[$i], 3));
            $to = $regs[1];
         } else if (eregi ("^from:(.*)$", $read[$i], $regs)) {
            //$from = sqimap_find_displayable_name(substr($read[$i], 5));
            $from = $regs[1];
         } else if (eregi ("^x-priority:(.*)$", $read[$i], $regs)) {
            $priority = trim($regs[1]);
         } else if (eregi ("^message-id:(.*)$", $read[$i], $regs)) {
            $messageid = trim($regs[1]);
         } else if (eregi ("^cc:(.*)$", $read[$i], $regs)) {
            $cc = $regs[1];
         } else if (eregi ("^date:(.*)$", $read[$i], $regs)) {
            $date = $regs[1];
         } else if (eregi ("^subject:(.*)$", $read[$i], $regs)) {
            $subject = htmlspecialchars(trim($regs[1]));
            if ($subject == "")
               $subject = lang("(no subject)");
         } else if (eregi ("^content-type:(.*)$", $read[$i], $regs)) {
            $type = strtolower(trim($regs[1]));
            if ($pos = strpos($type, ";"))
               $type = substr($type, 0, $pos);
            $type = explode("/", $type);
         }

      }

      // If there isn't a date, it takes the internal date and uses
      // that as the normal date.
      if (trim($date) == "") {
         fputs ($imap_stream, "a002 FETCH $id INTERNALDATE\r\n");
         $internal_read = sqimap_read_data ($imap_stream, "a002", true, $r, $m);

         // * 22 FETCH (INTERNALDATE " 8-Sep-2000 13:17:07 -0500")
         $date = $internal_read[0];
         $date = eregi_replace(".*internaldate \"", "", $date);
         $date = eregi_replace("\".*", "", $date);
         $date_ary = explode(" ", trim($date));
         $date_ary[0] = str_replace("-", " ", $date_ary[0]);
         $date = implode (" ", $date_ary);
      }

      fputs ($imap_stream, "a003 FETCH $id RFC822.SIZE\r\n");
      $read = sqimap_read_data($imap_stream, "a003", true, $r, $m);
      preg_match("/([0-9]+)\)\s*$/i", $read[0], $regs);
      $size = $regs[1];

      $header = new small_header;
      if ($sent == true)
         $header->from = (trim($to) != '')? $to : lang("(only Cc/Bcc)");
      else
         $header->from = $from;

      $header->date = $date;
      $header->subject = $subject;
      $header->to = $to;
      $header->priority = $priority;
      $header->message_id = $messageid;
      $header->cc = $cc;
      $header->size = $size;
      $header->type0 = $type[0];
      $header->type1 = $type[1];

      return $header;
   }

   
/******************************************************************************
    **  Returns the flags for the specified messages
    
******************************************************************************/
   function sqimap_get_flags ($imap_stream, $i) {
      fputs ($imap_stream, "a001 FETCH $i:$i FLAGS\r\n");
      $read = sqimap_read_data ($imap_stream, "a001", true, $response, 
$message);
      if (ereg("FLAGS(.*)", $read[0], $regs))
          return explode(" ", trim(ereg_replace('[\(\)\\]', '', $regs[1])));
      return Array('None');
   }

   
/******************************************************************************
    **  Returns a message array with all the information about a message.  See
    **  the documentation folder for more information about this array.
    
******************************************************************************/
   function sqimap_get_message ($imap_stream, $id, $mailbox) {
        global $header;
      $header = sqimap_get_message_header($imap_stream, $id, $mailbox);
      return sqimap_get_message_body($imap_stream, $header);
   }

   
/******************************************************************************
    **  Wrapper function that reformats the header information.
    
******************************************************************************/
   function sqimap_get_message_header ($imap_stream, $id, $mailbox) {
      fputs ($imap_stream, "a001 FETCH $id:$id BODY[HEADER]\r\n");
      $read = sqimap_read_data ($imap_stream, "a001", true, $response, 
$message);

      $header = sqimap_get_header($imap_stream, $read);
      $header->id = $id;
      $header->mailbox = $mailbox;

      return $header;
   }

   
/******************************************************************************
    **  Wrapper function that returns entity headers for use by decodeMime
    
******************************************************************************/
    /*
   function sqimap_get_entity_header ($imap_stream, &$read, &$type0, &$type1, 
&$bound, &$encoding, &$charset, &$filename) {
      $header = sqimap_get_header($imap_stream, $read);
      $type0 = $header["TYPE0"];
      $type1 = $header["TYPE1"];
      $bound = $header["BOUNDARY"];
      $encoding = $header["ENCODING"];
      $charset = $header["CHARSET"];
      $filename = $header["FILENAME"];
   }
    */

   
/******************************************************************************
    **  Queries the IMAP server and gets all header information.
    
******************************************************************************/
   function sqimap_get_header ($imap_stream, $read) {
      global $where, $what;

      $hdr = new msg_header();
      $i = 0;
      // Set up some defaults
      $hdr->type0 = "text";
      $hdr->type1 = "plain";
      $hdr->charset = "us-ascii";

      preg_match("/\{([0-9]+)\}/", $read[$i], $regs);
      preg_match("/[0-9]+/", $regs[0], $regs);

      while ($i < count($read)) {
         if (substr($read[$i], 0, 17) == "MIME-Version: 1.0") {
            $hdr->mime = true;
            $i++;
         }

         /** ENCODING TYPE **/
         else if (substr(strtolower($read[$i]), 0, 26) == 
"content-transfer-encoding:") {
            $hdr->encoding = strtolower(trim(substr($read[$i], 26)));
            $i++;
         }

         /** CONTENT-TYPE **/
         else if (strtolower(substr($read[$i], 0, 13)) == "content-type:") {
            $cont = strtolower(trim(substr($read[$i], 13)));
            if (strpos($cont, ";"))
               $cont = substr($cont, 0, strpos($cont, ";"));


            if (strpos($cont, "/")) {
               $hdr->type0 = substr($cont, 0, strpos($cont, "/"));
               $hdr->type1 = substr($cont, strpos($cont, "/")+1);
            } else {
               $hdr->type0 = $cont;
            }


            $line = $read[$i];
            $i++;
            while ( (substr(substr($read[$i], 0, strpos($read[$i], " ")), -1) 
!= ":") && (trim($read[$i]) != "") && (trim($read[$i]) != ")")) {
               str_replace("\n", "", $line);
               str_replace("\n", "", $read[$i]);
               $line = "$line $read[$i]";
               $i++;
            }

            /** Detect the boundary of a multipart message **/
            if (eregi("boundary=\"([^\"]+)\"", $line, $regs)) {
               $hdr->boundary = $regs[1];
            }

            /** Detect the charset **/
            if (strpos(strtolower(trim($line)), "charset=")) {
               $pos = strpos($line, "charset=") + 8;
               $charset = trim($line);
               if (strpos($line, ";", $pos) > 0) {
                  $charset = substr($charset, $pos, strpos($line, ";", 
$pos)-$pos);
               } else {
                  $charset = substr($charset, $pos);
               }
               $charset = str_replace("\"", "", $charset);
               $hdr->charset = $charset;
            } else {
               $hdr->charset = "us-ascii";
            }

         }

         else if (strtolower(substr($read[$i], 0, 20)) == 
"content-disposition:") {
            /** Add better dontent-disposition support **/

            $line = $read[$i];
            $i++;
            while ( (substr(substr($read[$i], 0, strpos($read[$i], " ")), -1) 
!= ":") && (trim($read[$i]) != "") && (trim($read[$i]) != ")")) {
               str_replace("\n", "", $line);
               str_replace("\n", "", $read[$i]);
               $line = "$line $read[$i]";
               $i++;
            }

            /** Detects filename if any **/
            if (strpos(strtolower(trim($line)), "filename=")) {
               $pos = strpos($line, "filename=") + 9;
               $name = trim($line);
               if (strpos($line, " ", $pos) > 0) {
                  $name = substr($name, $pos, strpos($line, " ", $pos));
               } else {
                  $name = substr($name, $pos);
               }
               $name = str_replace("\"", "", $name);
               $hdr->filename = $name;
            }
         }

         /** REPLY-TO **/
         else if (strtolower(substr($read[$i], 0, 9)) == "reply-to:") {
            $hdr->replyto = trim(substr($read[$i], 9, strlen($read[$i])));
            $i++;
         }

         /** FROM **/
         else if (strtolower(substr($read[$i], 0, 5)) == "from:") {
            $hdr->from = trim(substr($read[$i], 5, strlen($read[$i]) - 6));
            if (! isset($hdr->replyto) || $hdr->replyto == "")
               $hdr->replyto = $hdr->from;
            $i++;
         }
         /** DATE **/
         else if (strtolower(substr($read[$i], 0, 5)) == "date:") {
            $d = substr($read[$i], 5);
            $d = trim($d);
            $d = ereg_replace("  ", " ", $d);
            $d = explode(" ", $d);
            $hdr->date = getTimeStamp($d);
            $i++;
         }
         /** SUBJECT **/
         else if (strtolower(substr($read[$i], 0, 8)) == "subject:") {
            $hdr->subject = trim(substr($read[$i], 8, strlen($read[$i]) - 9));
            if (strlen(Chop($hdr->subject)) == 0)
               $hdr->subject = lang("(no subject)");

            if ($where == "SUBJECT") {
               $hdr->subject = eregi_replace($what, "<b>\\0</b>", 
$hdr->subject);
            }
            $i++;
         }
         /** CC **/
         else if (strtolower(substr($read[$i], 0, 3)) == "cc:") {
            $pos = 0;
            $hdr->cc[$pos] = trim(substr($read[$i], 4));
            $i++;
            while (((substr($read[$i], 0, 1) == " ") || (substr($read[$i], 0, 
1) == "\t"))  && (trim($read[$i]) != "")){
               $pos++;
               $hdr->cc[$pos] = trim($read[$i]);
               $i++;
            }
         }
         /** TO **/
         else if (strtolower(substr($read[$i], 0, 3)) == "to:") {
            $pos = 0;
            $hdr->to[$pos] = trim(substr($read[$i], 4));
            $i++;
            while (((substr($read[$i], 0, 1) == " ") || (substr($read[$i], 0, 
1) == "\t"))  && (trim($read[$i]) != "")){
               $pos++;
               $hdr->to[$pos] = trim($read[$i]);
               $i++;
            }
         }
         /** MESSAGE ID **/
         else if (strtolower(substr($read[$i], 0, 11)) == "message-id:") {
            $hdr->message_id = trim(substr($read[$i], 11));
            $i++;
         }
         /** PHPGW TYPE **/
         else if (substr(strtolower($read[$i]), 0, 13) == "x-phpgw-type:") {
            $temp = strtolower(trim(substr($read[$i], 13)));
            $temp_str = explode(';',$temp);
            $hdr->phpgw_type['type'] = 
substr(trim($temp_str[0]),1,strlen(trim($temp_str[0])) - 2);
            for($k=1;$k<count($temp_str);$k++) {
                $temp_type = explode('=',trim($temp_str[$k]));
                $hdr->phpgw_type[trim($temp_type[0])] = 
substr(trim($temp_type[1]),1,strlen(trim($temp_type[1])) - 2);
//              echo "!".trim($temp_type[0])."! = 
!".$hdr->phpgw_type[trim($temp_type[0])]."!<br>\n";
            }
            $i++;
         }


         /** ERROR CORRECTION **/
         else if (substr($read[$i], 0, 1) == ")") {
            if (strlen(trim($hdr->subject)) == 0)
                $hdr->subject = lang("(no subject)");

            if (strlen(trim($hdr->from)) == 0)
                $hdr->from = lang("(unknown sender)");

            if (strlen(trim($hdr->date)) == 0)
                $hdr->date = time();
            $i++;
         }
         else {
            $i++;
         }
      }
      return $hdr;
   }


   
/******************************************************************************
    **  Returns the body of a message.
    
******************************************************************************/
   function sqimap_get_message_body ($imap_stream, &$header) {
      $id = $header->id;
      return decodeMime($imap_stream, $header);
   }


   
/******************************************************************************
    **  Returns an array with the body structure
    
******************************************************************************/
?>

====================================================
Index: imap_mailbox.php
<?php
   /**
    **  imap_mailbox.php
    **
    **  This impliments all functions that manipulate mailboxes
    **
    **  $Id: imap_mailbox.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $
    **/

   
/******************************************************************************
    **  Expunges a mailbox
    
******************************************************************************/
   function sqimap_mailbox_expunge ($imap_stream, $mailbox,$handle_errors = 
true) {
      sqimap_mailbox_select ($imap_stream, $mailbox);
      fputs ($imap_stream, "a001 EXPUNGE\r\n");
      $read = sqimap_read_data($imap_stream, "a001", $handle_errors, $response, 
$message);
   }


   
/******************************************************************************
    **  Checks whether or not the specified mailbox exists
    
******************************************************************************/
   function sqimap_mailbox_exists ($imap_stream, $mailbox) {
      fputs ($imap_stream, "a001 LIST \"\" \"$mailbox\"\r\n");
      $mbx = sqimap_read_data($imap_stream, "a001", true, $response, $message);
      if (isset($mailbox) && !empty($mailbox) && isset($mbx[0])) {
         return !!(ereg ("$mailbox", $mbx[0]));  // To force into true/false
      }
   }

   
/******************************************************************************
    **  Selects a mailbox
    
******************************************************************************/
   function sqimap_mailbox_select ($imap_stream, $mailbox, $hide=true, 
$recent=false) {
      global $auto_expunge;

      fputs ($imap_stream, "a001 SELECT \"$mailbox\"\r\n");
             $read = sqimap_read_data($imap_stream, "a001", true, $response, 
$message);
      if ($recent) {
         for ($i=0; $i<count($read); $i++) {
            if (strpos(strtolower($read[$i]), "recent")) {
               $r = explode(" ", $read[$i]);
            }
         }
         return $r[1];
      }
      if ($auto_expunge) {
         fputs ($imap_stream, "a001 EXPUNGE\r\n");
         $tmp = sqimap_read_data($imap_stream, "a001", false, $a, $b);
      }
   }



   
/******************************************************************************
    **  Creates a folder
    
******************************************************************************/
   function sqimap_mailbox_create ($imap_stream, $mailbox, $type) {
      if (strtolower($type) == "noselect") {
         $dm = sqimap_get_delimiter($imap_stream);
         $mailbox = $mailbox.$dm;
      }
      fputs ($imap_stream, "a001 CREATE \"$mailbox\"\r\n");
      $read_ary = sqimap_read_data($imap_stream, "a001", true, $response, 
$message);

      sqimap_subscribe ($imap_stream, $mailbox);
   }



   
/******************************************************************************
    **  Subscribes to an existing folder
    
******************************************************************************/
   function sqimap_subscribe ($imap_stream, $mailbox) {
      fputs ($imap_stream, "a001 SUBSCRIBE \"$mailbox\"\r\n");
      $read_ary = sqimap_read_data($imap_stream, "a001", true, $response, 
$message);
   }




   
/******************************************************************************
    **  Unsubscribes to an existing folder
    
******************************************************************************/
   function sqimap_unsubscribe ($imap_stream, $mailbox) {
                global $imap_server_type;

      fputs ($imap_stream, "a001 UNSUBSCRIBE \"$mailbox\"\r\n");
      $read_ary = sqimap_read_data($imap_stream, "a001", true, $response, 
$message);
   }




   
/******************************************************************************
    **  This function simply deletes the given folder
    
******************************************************************************/
   function sqimap_mailbox_delete ($imap_stream, $mailbox) {
      fputs ($imap_stream, "a001 DELETE \"$mailbox\"\r\n");
      $read_ary = sqimap_read_data($imap_stream, "a001", true, $response, 
$message);
      sqimap_unsubscribe ($imap_stream, $mailbox);
   }


   
/******************************************************************************
    **  Formats a mailbox into 4 parts for the $boxes array
    **
    **  The four parts are:
    **
    **    raw            - Raw LIST/LSUB response from the IMAP server
    **    formatted      - nicely formatted folder name
    **    unformatted    - unformatted, but with delimiter at end removed
    **    unformatted-dm - folder name as it appears in raw response
    **    unformatted-disp - unformatted without $folder_prefix
    **
    
******************************************************************************/
   function sqimap_mailbox_parse ($line, $line_lsub, $dm) {
      global $folder_prefix;

      // Process each folder line
      for ($g=0; $g < count($line); $g++) {

         // Store the raw IMAP reply
         if (isset($line[$g]))
            $boxes[$g]["raw"] = $line[$g];
         else
            $boxes[$g]["raw"] = "";


         // Count number of delimiters ($dm) in folder name
         $mailbox = trim($line_lsub[$g]);
         $dm_count = countCharInString($mailbox, $dm);
         if (substr($mailbox, -1) == $dm)
            $dm_count--;  // If name ends in delimiter - decrement count by one

         // Format folder name, but only if it's a INBOX.* or have
         // a parent.
         $boxesbyname[$mailbox] = $g;
         $parentfolder = readMailboxParent($mailbox, $dm);
         if((eregi("^inbox".quotemeta($dm), $mailbox)) ||
            (ereg("^".$folder_prefix, $mailbox)) ||
            ( isset($boxesbyname[$parentfolder]) && (strlen($parentfolder) > 0) 
) ) {
            $indent = $dm_count - (countCharInString($folder_prefix, $dm));
            if ($indent)
                $boxes[$g]["formatted"]  = str_repeat("&nbsp;&nbsp;", $indent);
            else
                $boxes[$g]["formatted"] = '';
            $boxes[$g]["formatted"] .= readShortMailboxName($mailbox, $dm);
         } else {
            $boxes[$g]["formatted"]  = $mailbox;
         }

         $boxes[$g]["unformatted-dm"] = $mailbox;
         if (substr($mailbox, -1) == $dm)
            $mailbox = substr($mailbox, 0, strlen($mailbox) - 1);
         $boxes[$g]["unformatted"] = $mailbox;
         $boxes[$g]["unformatted-disp"] = ereg_replace("^" . $folder_prefix, 
"", $mailbox);
         $boxes[$g]["id"] = $g;

         if (isset($line[$g]))
         ereg("\(([^)]*)\)",$line[$g],$regs);
         $flags = trim(strtolower(str_replace("\\", "",$regs[1])));
         if ($flags) {
            $boxes[$g]["flags"] = explode(" ", $flags);
         }
      }

      return $boxes;
   }

   /* Apparently you must call a user function with usort instead
    * of calling a built-in directly.  Stupid.
    * Patch from address@hidden
    * Allows case insensitivity when sorting folders
    */
   function user_strcasecmp($a, $b)
   {
       return strcasecmp($a, $b);
   }


   
/******************************************************************************
    **  Returns sorted mailbox lists in several different ways.
    **  See comment on sqimap_mailbox_parse() for info about the returned array.
    
******************************************************************************/
   function sqimap_mailbox_list ($imap_stream) {
      global $load_prefs_php, $prefs_php, $config_php;
      global $data_dir, $username, $list_special_folders_first;
      global $trash_folder, $sent_folder;
      global $move_to_trash, $move_to_sent;

      $inbox_in_list = false;
      $inbox_subscribed = false;

      if (!isset($load_prefs_php)) include (PHPGW_APP_ROOT . 
"/src/load_prefs.php");
      else global $folder_prefix;
      if (!function_exists ("ary_sort")) include (PHPGW_APP_ROOT . 
"/inc/array.php");
      $dm = sqimap_get_delimiter ($imap_stream);

      /** LSUB array **/
      $inbox_subscribed = false;
      fputs ($imap_stream, "a001 LSUB \"\" \"*\"\r\n");
      $lsub_ary = sqimap_read_data ($imap_stream, "a001", true, $response, 
$message);

      /** OS: we don't want to parse last element of array, 'cause it is OK 
command, so we unset it **/
      /** LUKE:  This introduced errors.. do a check first **/
      if (substr($lsub_ary[count($lsub_ary)-1], 0, 4) == "* OK") {
        unset($lsub_ary[count($lsub_ary)-1]);
      }

      for ($i=0;$i < count($lsub_ary); $i++) {
         $sorted_lsub_ary[$i] = find_mailbox_name($lsub_ary[$i]);
         if ($sorted_lsub_ary[$i] == "INBOX")
            $inbox_subscribed = true;
      }
      $new_ary = array();
      for ($i=0; $i < count($sorted_lsub_ary); $i++) {
         if (!in_array($sorted_lsub_ary[$i], $new_ary)) {
            $new_ary[] = $sorted_lsub_ary[$i];
         }
      }
      $sorted_lsub_ary = $new_ary;
      if (isset($sorted_lsub_ary)) {
         usort($sorted_lsub_ary, "user_strcasecmp");
         //sort($sorted_lsub_ary);
      }

      /** LIST array **/
      for ($i=0; $i < count($sorted_lsub_ary); $i++) {
         if (substr($sorted_lsub_ary[$i], -1) == $dm)
            $mbx = substr($sorted_lsub_ary[$i], 0, 
strlen($sorted_lsub_ary[$i])-1);
         else
            $mbx = $sorted_lsub_ary[$i];

         fputs ($imap_stream, "a001 LIST \"\" \"$mbx\"\r\n");
         $read = sqimap_read_data ($imap_stream, "a001", true, $response, 
$message);
         if (isset($sorted_list_ary[$i]))
            $sorted_list_ary[$i] = "";
         if (isset($read[0]))
         $sorted_list_ary[$i] = $read[0];
         else
         $sorget_list_ary[$i] = "";
         if (isset($sorted_list_ary[$i]) && 
find_mailbox_name($sorted_list_ary[$i]) == "INBOX")
            $inbox_in_list = true;
      }

      /** Just in case they're not subscribed to their inbox, we'll get it for 
them anyway **/
      if ($inbox_subscribed == false || $inbox_in_list == false) {
         fputs ($imap_stream, "a001 LIST \"\" \"INBOX\"\r\n");
         $inbox_ary = sqimap_read_data ($imap_stream, "a001", true, $response, 
$message);

         $pos = count($sorted_list_ary);
         $sorted_list_ary[$pos] = $inbox_ary[0];

         $pos = count($sorted_lsub_ary);
         $sorted_lsub_ary[$pos] = find_mailbox_name($inbox_ary[0]);
      }

      $boxes = sqimap_mailbox_parse ($sorted_list_ary, $sorted_lsub_ary, $dm);


      /** Now, lets sort for special folders **/

      $boxesnew = Array();

      // Find INBOX
      for ($i = 0; $i < count($boxes); $i++) {
         if (strtolower($boxes[$i]["unformatted"]) == "inbox") {
            $boxesnew[] = $boxes[$i];
            $used[$i] = true;
            $i = count($boxes);
         }
      }

      if ($list_special_folders_first == true) {

         // Then list special folders and their subfolders
         for ($i = 0 ; $i < count($boxes) ; $i++) {
            if ($move_to_trash &&
                eregi("^" . quotemeta($trash_folder) . "(" .
                quotemeta($dm) . ".*)?$", $boxes[$i]["unformatted"])) {
               $boxesnew[] = $boxes[$i];
               $used[$i] = true;
            }
            elseif ($move_to_sent &&
                eregi("^" . quotemeta($sent_folder) . "(" .
                quotemeta($dm) . ".*)?$", $boxes[$i]["unformatted"])) {
               $boxesnew[] = $boxes[$i];
               $used[$i] = true;
            }
         }

         // Put INBOX.* folders ahead of the rest
         for ($i = 0; $i < count($boxes); $i++) {
            if (eregi("^inbox\.", $boxes[$i]["unformatted"]) &&
                (!isset($used[$i]) || $used[$i] == false)) {
               $boxesnew[] = $boxes[$i];
               $used[$i] = true;
            }
         }

      }

      // Rest of the folders
      for ($i = 0; $i < count($boxes); $i++) {
         if ((strtolower($boxes[$i]["unformatted"]) != "inbox") &&
             (!isset($used[$i]) || $used[$i] == false))  {
            $boxesnew[] = $boxes[$i];
            $used[$i] = true;
         }
      }

      return $boxesnew;
   }

   
/******************************************************************************
    **  Returns a list of all folders, subscribed or not
    
******************************************************************************/
   function sqimap_mailbox_list_all ($imap_stream) {
      global $list_special_folders_first, $folder_prefix;

      if (!function_exists ("ary_sort"))
         include (PHPGW_APP_ROOT . "/inc/array.php");

      $dm = sqimap_get_delimiter ($imap_stream);

      fputs ($imap_stream, "a001 LIST \"$folder_prefix\" *\r\n");
      $read_ary = sqimap_read_data ($imap_stream, "a001", true, $response, 
$message);
      $g = 0;
      $phase = "inbox";

      for ($i = 0; $i < count($read_ary); $i++) {
         if (substr ($read_ary[$i], 0, 4) != "a001") {

            // Store the raw IMAP reply
            $boxes[$g]["raw"] = $read_ary[$i];

            // Count number of delimiters ($dm) in folder name
            $mailbox = find_mailbox_name($read_ary[$i]);
            $dm_count = countCharInString($mailbox, $dm);
            if (substr($mailbox, -1) == $dm)
               $dm_count--;  // If name ends in delimiter - decrement count by 
one

            // Format folder name, but only if it's a INBOX.* or have
            // a parent.
            $boxesbyname[$mailbox] = $g;
            $parentfolder = readMailboxParent($mailbox, $dm);
            if((eregi("^inbox".quotemeta($dm), $mailbox)) ||
               (ereg("^".$folder_prefix, $mailbox)) ||
               ( isset($boxesbyname[$parentfolder]) && (strlen($parentfolder) > 
0) ) ) {
               if ($dm_count)
                   $boxes[$g]["formatted"]  = str_repeat("&nbsp;&nbsp;", 
$dm_count);
               else
                   $boxes[$g]["formatted"] = '';
               $boxes[$g]["formatted"] .= readShortMailboxName($mailbox, $dm);
            } else {
               $boxes[$g]["formatted"]  = $mailbox;
            }

            $boxes[$g]["unformatted-dm"] = $mailbox;
            if (substr($mailbox, -1) == $dm)
               $mailbox = substr($mailbox, 0, strlen($mailbox) - 1);
            $boxes[$g]["unformatted"] = $mailbox;
            $boxes[$g]["unformatted-disp"] = ereg_replace("^" . $folder_prefix, 
"", $mailbox);
            $boxes[$g]["id"] = $g;

            /** Now lets get the flags for this mailbox **/
            fputs ($imap_stream, "a002 LIST \"\" \"$mailbox\"\r\n");
            $read_mlbx = sqimap_read_data ($imap_stream, "a002", true, 
$response, $message);

            $flags = substr($read_mlbx[0], strpos($read_mlbx[0], "(")+1);
            $flags = substr($flags, 0, strpos($flags, ")"));
            $flags = str_replace("\\", "", $flags);
            $flags = trim(strtolower($flags));
            if ($flags) {
               $boxes[$g]["flags"] = explode(" ", $flags);
            }
         }
         $g++;
      }
      if(is_array($boxes)) {
         $boxes = ary_sort ($boxes, "unformatted", 1);
      }

      return $boxes;
   }

?>

====================================================
Index: hook_admin.inc.php
<?php
        
/**************************************************************************\
        * phpGroupWare                                                          
   *
        * http://www.phpgroupware.org                                           
   *
        * --------------------------------------------                          
   *
        *  This program is free software; you can redistribute it and/or modify 
it *
        *  under the terms of the GNU General Public License as published by 
the   *
        *  Free Software Foundation; either version 2 of the License, or (at 
your  *
        *  option) any later version.                                           
   *
        
\**************************************************************************/
        /* $Id: hook_admin.inc.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $ */
        {
                $file = Array
                (
                        'Site Configuration' => 
$GLOBALS['phpgw']->link('/index.php','menuaction=admin.uiconfig.index&appname=' 
. $appname)
                );
//Do not modify below this line
                $GLOBALS['phpgw']->common->display_mainscreen($appname,$file);
        }
?>

====================================================
Index: functions.inc.php
<?php
/**************************************************************************\
* phpGroupWare - session data class                                        *
* http://www.phpgroupware.org                                              *
* writen by Lars Kneschke <address@hidden>                      *
*          http://www.kneschke.de/                                         *
* --------------------------------------------                             *
*  This program is free software; you can redistribute it and/or modify it *
*  under the terms of the GNU General Public License as published by the   *
*  Free Software Foundation; either version 2 of the License, or (at your  *
*  option) any later version.                                              *
\**************************************************************************/

        class phpgwSessionData
        {
                var $variableNames;

                // restore the values of the variables
#               function restore()
#               {
#                       global $phpgw;
#
#                       $serializedData = 
$phpgw->session->appsession('session');
#                       $sessionData = unserialize($serializedData);
#
#                       if (is_array($sessionData))
#                       {
#                               reset($sessionData);
#                               while(list($key,$value) = each($sessionData))
#                               {
#                                       global $$key;
#                                       $$key = $value;
#                                       $this->variableNames[$key]="registered";
#                                       print "restored: ".$key.", $value<br>";
#                               }
#                       }
#               }

#               // save the current values of the variables
#               function save()
#               {
#                       global $phpgw;
#
#                       if (is_array($this->variableNames))
#                       {
#                               reset($this->variableNames);
#                               while(list($key, $value) = 
each($this->variableNames))
#                               {
#                                       if ($value == "registered")
#                                       {
#                                               global $$key;
#                                               $sessionData[$key] = $$key;
#                                       }
#                               }
#                               
$phpgw->session->appsession('default','',$sessionData);
#                       }
#               }

#               // create a list a variable names, wich data need's to be 
restored
#               function register($_variableName)
#               {
#                       $this->variableNames[$_variableName]="registered";
#                       #print "registered $_variableName<br>";
#               }

#               // mark variable as unregistered
#               function unregister($_variableName)
#               {
#                       $this->variableNames[$_variableName]="unregistered";
#                       #print "unregistered $_variableName<br>";
#               }

#               // check if we have a variable registred already
#               function is_registered($_variableName)
#               {
#                       if ($this->variableNames[$_variableName] == 
"registered")
#                       {
#                               return True;
#                       }
#                       else
#                       {
#                               return False;
#                       }
#               }
        }


?>

====================================================
Index: class.bopreferences.inc.php
<?php
        
/***************************************************************************\
        * phpGroupWare - Squirrelmail                                           
    *
        * http://www.phpgroupware.org                                           
    *
        * http://www.linux-at-work.de                                           
    *
        * Written by : Lars Kneschke address@hidden                   *
        * -------------------------------------------------                     
    *
        * This program is free software; you can redistribute it and/or modify 
it   *
        * under the terms of the GNU General Public License as published by the 
    *
        * Free Software Foundation; either version 2 of the License, or (at 
your    *
        * option) any later version.                                            
    *
        
\***************************************************************************/
        /* $Id: class.bopreferences.inc.php,v 1.1 2005/05/05 00:56:40 skwashd 
Exp $ */

        class bopreferences
        {
                var $public_functions = array
                (
                        'getPreferences'        => True,
                        'none'  => True
                );

                function bopreferences()
                {
                        #$this->bocompose       = 
CreateObject('squirrelmail.bocompose');
                }

                function getPreferences()
                {
/*                      while(list($key,$value) = 
each($GLOBALS['phpgw_info']['server']) )
                        {
                                print ". $key: $value<br>";
                                if (is_array($value))
                                {
                                        while(list($key1,$value1) = 
each($value) )
                                        {
                                                print ".. &nbsp;$mbsp;-$key1: 
$value1<br>";
                                        }
                                }
                        }
*/
                        if 
($GLOBALS['phpgw_info']['user']['preferences']['email']['use_custom_settings'] 
== 'True')
                        {
                                $data['imapServerAddress']      = 
$GLOBALS['phpgw_info']['user']['preferences']['email']['mail_server'];

                                $data['key']                    = 
$GLOBALS['phpgw_info']['user']['preferences']['email']['passwd'];
                                $data['username']               = 
$GLOBALS['phpgw_info']['user']['preferences']['email']['userid'];
                                $data['emailAddress']           = 
$GLOBALS['phpgw_info']['user']['preferences']['email']['address'];

                                $data['imap_server_type']       = 
strtolower($GLOBALS['phpgw_info']['user']['preferences']['email']['imap_server_type']);
                        }
                        else
                        {
                                $data['imapServerAddress']      = 
$GLOBALS['phpgw_info']['server']['mail_server'];

                                $data['key']                    = 
$GLOBALS['phpgw_info']['user']['passwd'];
                                $data['username']               = 
$GLOBALS['phpgw_info']['user']['userid'];
                                $data['emailAddress']           = 
$GLOBALS['phpgw_info']['user']['userid']."@".$GLOBALS['phpgw_info']['server']['mail_suffix'];

                                $data['imap_server_type']       = 
strtolower($GLOBALS['phpgw_info']['server']['imap_server_type']);
                        }

                        // global settings
                        $data['realname']               = 
$GLOBALS['phpgw_info']['user']['fullname'];
                        $data['defaultDomainname']      = 
$GLOBALS['phpgw_info']["server"]["mail_suffix"];

                        $data['smtpServerAddress']      = 
$GLOBALS['phpgw_info']["server"]["smtp_server"];
                        $data['smtpPort']               = 
$GLOBALS['phpgw_info']["server"]["smtp_port"];

                        $data['imapPort']               = 143;

                        // preferences
                        $data['trash_folder']           = 
$GLOBALS['phpgw_info']['user']['preferences']['squirrelmail']['trash_folder'];
                        $data['sent_folder']            = 
$GLOBALS['phpgw_info']['user']['preferences']['squirrelmail']['sent_folder'];
                        if (!empty($data['trash_folder']))
                                $data['move_to_trash']  = "true";
                        if (!empty($data['sent_folder']))
                                $data['move_to_sent']   = "true";
                        $data['signature']              = 
$GLOBALS['phpgw_info']['user']['preferences']['email']['email_sig'];

                        return $data;
                }
}

====================================================
Index: class.bocompose.inc.php
<?php
        
/***************************************************************************\
        * phpGroupWare - Squirrelmail                                           
    *
        * http://www.phpgroupware.org                                           
    *
        * http://www.linux-at-work.de                                           
    *
        * Written by : Lars Kneschke address@hidden                   *
        * -------------------------------------------------                     
    *
        * This program is free software; you can redistribute it and/or modify 
it   *
        * under the terms of the GNU General Public License as published by the 
    *
        * Free Software Foundation; either version 2 of the License, or (at 
your    *
        * option) any later version.                                            
    *
        
\***************************************************************************/
        /* $Id: class.bocompose.inc.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $ 
*/

        class bocompose
        {
                var $public_functions = array
                (
                        'addAtachment'  => True,
                        'action'        => True
                );

                var $attachments;       // Array of attachments
                var $preferences;       // the prefenrences(emailserver, 
username, ...)

                function bocompose($_composeID = '')
                {
                        $this->bopreferences    = 
CreateObject('squirrelmail.bopreferences');
                        $this->preferences = 
$this->bopreferences->getPreferences();

                        if (!empty($_composeID))
                        {
                                $this->composeID = $_composeID;
                                $this->restoreSessionData();
                        }
                }

                function addAttachment($_formData)
                {
                        $this->sessionData['to']        = $_formData['to'];
                        $this->sessionData['cc']        = $_formData['cc'];
                        $this->sessionData['bcc']       = $_formData['bcc'];
                        $this->sessionData['reply_to']  = 
$_formData['reply_to'];
                        $this->sessionData['subject']   = $_formData['subject'];
                        $this->sessionData['body']      = $_formData['body'];
                        $this->sessionData['priority']  = 
$_formData['priority'];
                        $this->sessionData['signature'] = 
$_formData['signature'];

                        #while(list($key,$value) = 
each($GLOBALS['phpgw_info']['user']))
                        #{
                        #       print "$key: $value<br>";
                        #}

                        if ($_formData['size'] != 0)
                        {
                                // ensure existance of PHPGROUPWARE temp dir
                                // note: this is different from apache temp dir,
                                // and different from any other temp file 
location set in php.ini
                                if 
(!file_exists($GLOBALS['phpgw_info']['server']['temp_dir']))
                                {
                                        
@mkdir($GLOBALS['phpgw_info']['server']['temp_dir'],0700);
                                }

                                // if we were NOT able to create this temp 
directory, then make an ERROR report
                                if 
(!file_exists($GLOBALS['phpgw_info']['server']['temp_dir']))
                                {
                                        $alert_msg .= 'Error:'.'<br>'
                                                .'Server is unable to access 
phpgw tmp directory'.'<br>'
                                                
.$phpgw_info['server']['temp_dir'].'<br>'
                                                .'Please check your 
configuration'.'<br>'
                                                .'<br>';
                                }

                                // sometimes PHP is very clue-less about MIME 
types, and gives NO file_type
                                // rfc default for unknown MIME type is:
                                $mime_type_default = 'application/octet-stream';
                                // so if PHP did not pass any file_type info, 
then substitute the rfc default value
                                if (trim($_formData['type']) == '')
                                {
                                        $_formData['type'] = $mime_type_default;
                                }

                                $tmpFileName = 
$GLOBALS['phpgw_info']['server']['temp_dir'].
                                        SEP.
                                        
$GLOBALS['phpgw_info']['user']['account_id'].
                                        $this->composeID.
                                        basename($_formData['file']);

                                copy($_formData['file'],$tmpFileName);

                                $this->sessionData['attachments'][]=array
                                (
                                        'name'  => $_formData['name'],
                                        'type'  => $_formData['type'],
                                        'file'  => $tmpFileName,
                                        'size'  => $_formData['size']
                                );
                        }

                        $this->saveSessionData();
                }

                function getAttachmentList()
                {
                }

                // create a hopefully unique id, to keep track of different 
compose windows
                // if you do this, you are creating a new email
                function getComposeID()
                {
                        mt_srand((float) microtime() * 1000000);
                        $this->composeID = mt_rand (100000, 999999);

                        $this->setDefaults();

                        return $this->composeID;
                }

                function getSessionData()
                {
                        return $this->sessionData;
                }

                function removeAttachment($_formData)
                {
                        $this->sessionData['to']        = $_formData['to'];
                        $this->sessionData['cc']        = $_formData['cc'];
                        $this->sessionData['bcc']       = $_formData['bcc'];
                        $this->sessionData['reply_to']  = 
$_formData['reply_to'];
                        $this->sessionData['subject']   = $_formData['subject'];
                        $this->sessionData['body']      = $_formData['body'];
                        $this->sessionData['priority']  = 
$_formData['priority'];
                        $this->sessionData['signature'] = 
$_formData['signature'];

                        while(list($key,$value) = 
each($_formData['removeAttachments']))
                        {
                                #print "$key: $value<br>";
                                
unlink($this->sessionData['attachments'][$key]['file']);
                                unset($this->sessionData['attachments'][$key]);
                        }
                        reset($this->sessionData['attachments']);

                        // if it's empty, clear it totaly
                        if (count($this->sessionData['attachments']) == 0)
                        {
                                $this->sessionData['attachments'] = '';
                        }

                        $this->saveSessionData();
                }

                function restoreSessionData()
                {
                        $this->sessionData = 
$GLOBALS['phpgw']->session->appsession('compose_session_data_'.$this->composeID);
                }

                function saveSessionData()
                {
                        
$GLOBALS['phpgw']->session->appsession('compose_session_data_'.$this->composeID,'',$this->sessionData);
                }

                function send($_formData)
                {
                        $this->sessionData['to']        = $_formData['to'];
                        $this->sessionData['cc']        = $_formData['cc'];
                        $this->sessionData['bcc']       = $_formData['bcc'];
                        $this->sessionData['reply_to']  = 
$_formData['reply_to'];
                        $this->sessionData['subject']   = $_formData['subject'];
                        $this->sessionData['body']      = $_formData['body'];
                        $this->sessionData['priority']  = 
$_formData['priority'];
                        $this->sessionData['signature'] = 
$_formData['signature'];

                        $mail = CreateObject('squirrelmail.phpmailer');

                        include(PHPGW_APP_ROOT . "/config/config.php");

                        $mail->IsSMTP();
                        $mail->From     = $this->preferences['emailAddress'];
                        $mail->FromName = $this->preferences['realname'];
                        $mail->Host     = 
$this->preferences['smtpServerAddress'];
                        $mail->Priority = $this->sessionData['priority'];
                        $mail->Encoding = '8bit';

                        if (!empty($this->sessionData['to']))
                        {
                                $address = split(";",$this->sessionData['to']);
                                while (list($key,$value) = each($address))
                                {
                                        $mail->AddAddress($value);
                                }
                        }

                        if (!empty($this->sessionData['cc']))
                        {
                                $address = split(";",$this->sessionData['cc']);
                                while (list($key,$value) = each($address))
                                {
                                        $mail->AddCC($value);
                                }
                        }

                        if (!empty($this->sessionData['bcc']))
                        {
                                $address = split(";",$this->sessionData['bcc']);
                                while (list($key,$value) = each($address))
                                {
                                        $mail->AddBCC($value);
                                }
                        }

                        if (!empty($this->sessionData['reply_to']))
                        {
                                $address = 
split(";",$this->sessionData['reply_to']);
                                while (list($key,$value) = each($address))
                                {
                                        $mail->AddReplyTo($value);
                                }
                        }

                        $mail->WordWrap = 76;
                        $mail->Subject = $this->sessionData['subject'];
                        $mail->IsHTML(false);
                        $mail->Body    = $this->sessionData['body'];
                        if (!empty($this->sessionData['signature']))
                        {
                                $mail->Body     .= "\r\n--\r\n";
                                $mail->Body     .= 
$this->sessionData['signature'];
                        }
                        if (is_array($this->sessionData['attachments']))
                        {
                                while(list($key,$value) = 
each($this->sessionData['attachments']))
                                {
                                        $mail->AddAttachment
                                        (
                                                $value['file'],
                                                $value['name'],
                                                'base64',
                                                $value['type']
                                        );
                                }
                        }
                        #$mail->AltBody = $this->sessionData['body'];

                        if(!$mail->Send())
                        {
                                echo "Message could not be sent. <p>";
                                echo "Mailer Error: " . $mail->ErrorInfo;
                                exit;
                        }

                        if ($this->preferences['move_to_sent'] == "true")
                        {
                                $username               = 
$this->preferences['username'];
                                $key                    = 
$this->preferences['key'];
                                $imapServerAddress      = 
$this->preferences['imapServerAddress'];
                                $imapPort               = 
$this->preferences['imapPort'];
                                $sent_folder            = 
$this->preferences['sent_folder'];

                                include(PHPGW_APP_ROOT . 
"/inc/imap_general.php");
                                include(PHPGW_APP_ROOT . 
"/inc/imap_mailbox.php");
                                include(PHPGW_APP_ROOT . "/inc/smtp.php");

                                $imap_stream = sqimap_login($username, $key, 
$imapServerAddress, $imapPort, 1);
                                $sent_folder = trim($sent_folder);
                                if (sqimap_mailbox_exists ($imap_stream, 
$sent_folder))
                                {
                                        sqimap_append ($imap_stream, 
$sent_folder,
                                                
strlen($mail->create_header())+strlen($mail->create_body()));
                                        fputs ($imap_stream, 
$mail->create_header());
                                        fputs ($imap_stream, 
$mail->create_body());
                                        sqimap_append_done ($imap_stream);
                                }
                                sqimap_logout($imap_stream);
                        }
                        while(list($key,$value) = 
@each($this->sessionData['attachments']))
                        {
                                #print "$key: $value<br>";
                                unlink($value['file']);
                        }

                        $this->sessionData = '';
                        $this->saveSessionData();
                }

                function setDefaults()
                {
                        $this->sessionData['signature'] = 
$this->preferences['signature'];

                        $this->saveSessionData();
                }

                function stripSlashes($_string)
                {
                        if (get_magic_quotes_gpc())
                        {
                                $string = stripslashes($_string);
                        }
                        return $string;
                }


}

====================================================
Index: auth.php
<?php

/**
 ** auth.php
 **
 ** Contains functions used to do authentication.
 **
 ** $Id: auth.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $
 **/

   $auth_php = true;

   function is_logged_in () {
      if (!session_is_registered('user_is_logged_in')) {
         echo lang("You must login first.");
         echo "</body></html>\n\n";
         exit;
      } else {
         return true;
      }
   }

?>

====================================================
Index: class.phpmailer.inc.php
<?php
////////////////////////////////////////////////////
// phpmailer - PHP email class
//
// Version 1.41, Created 08/12/2001
//
// Class for sending email using either
// sendmail, PHP mail(), or SMTP.  Methods are
// based upon the standard AspEmail(tm) classes.
//
// Author: Brent R. Matzelle <address@hidden>
//
// License: LGPL, see LICENSE
////////////////////////////////////////////////////

/**
 * phpmailer - PHP email transport class
 * @author Brent R. Matzelle
 */
class phpmailer
{
   /////////////////////////////////////////////////
   // PUBLIC VARIABLES
   /////////////////////////////////////////////////

   /**
    * Email priority (1 = High, 3 = Normal, 5 = low). Default value is 3.
    * @public
    * @type int
    */
   var $Priority         = 3;

   /**
    * Sets the CharSet of the message. Default value is "iso-8859-1".
    * @public
    * @type string
    */
   var $CharSet          = "iso-8859-1";

   /**
    * Sets the Content-type of the message. Default value is "text/plain".
    * @public
    * @type string
    */
   var $ContentType      = "text/plain";

   /**
    * Sets the Encoding of the message. Options for this are "8bit" (default),
    * "7bit", "binary", "base64", and "quoted-printable".
    * @public
    * @type string
    */
   var $Encoding         = "8bit";

   /**
    * Holds the most recent mailer error message. Default value is "".
    * @public
    * @type string
    */
   var $ErrorInfo        = "";

   /**
    * Sets the From email address for the message. Default value is 
"address@hidden".
    * @public
    * @type string
    */
   var $From             = "address@hidden";

   /**
    * Sets the From name of the message. Default value is "Root User".
    * @public
    * @type string
    */
   var $FromName         = "Root User";

   /**
    * Sets the Sender email of the message. If not empty, will be sent via -f 
to sendmail
    * or as 'MAIL FROM' in smtp mode. Default value is "".
    * @public
    * @type string
    */
   var $Sender           = "";

   /**
    * Sets the Subject of the message. Default value is "".
    * @public
    * @type string
    */
   var $Subject          = "";

   /**
    * Sets the Body of the message.  This can be either an HTML or text body.
    * If HTML then run IsHTML(true). Default value is "".
    * @public
    * @type string
    */
   var $Body             = "";

   /**
    * Sets the text-only body of the message.  This automatically sets the
    * email to multipart/alternative.  This body can be read by mail
    * clients that do not have HTML email capability such as mutt. Clients
    * that can read HTML will view the normal Body.
    * Default value is "".
    * @public
    * @type string
    */
   var $AltBody          = "";

   /**
    * Sets word wrapping on the message. Default value is false (off).
    * @public
    * @type string
    */
   var $WordWrap         = false;

   /**
    * Method to send mail: ("mail", "sendmail", or "smtp").
    * Default value is "mail".
    * @public
    * @type string
    */
   var $Mailer           = "mail";

   /**
    * Sets the path of the sendmail program. Default value is
    * "/usr/sbin/sendmail".
    * @public
    * @type string
    */
   var $Sendmail         = "/usr/sbin/sendmail";

   /**
    *  Turns Microsoft mail client headers on and off. Default value is false 
(off).
    *  @public
    *  @type bool
    */
   var $UseMSMailHeaders = false;

   /**
    *  Holds phpmailer version.
    *  @public
    *  @type string
    */
   var $Version          = "1.41";


   /////////////////////////////////////////////////
   // SMTP VARIABLES
   /////////////////////////////////////////////////

   /**
    *  Sets the SMTP hosts.  All hosts must be separated by a
    *  semicolon (e.g. Host("smtp1.domain.com;smtp2.domain.com").
    *  Hosts will be tried in order.
    *  Default value is "localhost".
    *  @public
    *  @type string
    */
   var $Host        = "localhost";

   /**
    *  Sets the SMTP server port. Default value is 25.
    *  @public
    *  @type int
    */
   var $Port        = 25;

   /**
    *  Sets the CharSet of the message.
    *  Default value is "localhost.localdomain".
    *  @public
    *  @type string
    */
   var $Helo        = "localhost.localdomain";

   /**
    *  Sets SMTP authentication. Remember to set the Username and Password.
    *  Default value is false (off).
    *  @public
    *  @type bool
    */
   var $SMTPAuth    = false;

   /**
    *  Sets SMTP username. Default value is "".
    *  @public
    *  @type string
    */
   var $Username    = "";

   /**
    *  Sets SMTP password. Default value is "".
    *  @public
    *  @type string
    */
   var $Password    = "";

   /**
    *  Sets the SMTP server timeout in seconds. Does not function at this time
    *  because PHP for win32 does not support it. Default value is 10.
    *  @public
    *  @type int
    */
   var $Timeout     = 10;

   /**
    *  Sets SMTP class debugging on or off. Default value is false (off).
    *  @public
    *  @type bool
    */
   var $SMTPDebug   = false;


   /////////////////////////////////////////////////
   // PRIVATE VARIABLES
   /////////////////////////////////////////////////

   /**
    *  Holds all "To" addresses.
    *  @type array
    */
   var $to            = array();

   /**
    *  Holds all "CC" addresses.
    *  @type array
    */
   var $cc            = array();

   /**
    *  Holds all "BCC" addresses.
    *  @type array
    */
   var $bcc           = array();

   /**
    *  Holds all "Reply-To" addresses.
    *  @type array
    */
   var $ReplyTo       = array();

   /**
    *  Holds all string and binary attachments.
    *  @type array
    */
   var $attachment    = array();

   /**
    *  Holds all custom headers.
    *  @type array
    */
   var $CustomHeader  = array();

   /**
    *  Holds the message boundary. Default is false.
    *  @type string
    */
   var $boundary      = false;

   /**
    *  Holds the message boundary. This is used specifically
    *  when multipart/alternative messages are sent. Default is false.
    *  @type string
    */
   var $subboundary      = false;

   /////////////////////////////////////////////////
   // VARIABLE METHODS
   /////////////////////////////////////////////////

   /**
    * Sets message type to HTML.  Returns void.
    * @public
    * @returns void
    */
   function IsHTML($bool) {
      if($bool == true)
         $this->ContentType = "text/html";
      else
         $this->ContentType = "text/plain";
   }

   /**
    * Sets Mailer to send message using SMTP.
    * Returns void.
    * @public
    * @returns void
    */
   function IsSMTP() {
      $this->Mailer = "smtp";
   }

   /**
    * Sets Mailer to send message using PHP mail() function.
    * Returns void.
    * @public
    * @returns void
    */
   function IsMail() {
      $this->Mailer = "mail";
   }

   /**
    * Sets Mailer to send message using the $Sendmail program.
    * Returns void.
    * @public
    * @returns void
    */
   function IsSendmail() {
      $this->Mailer = "sendmail";
   }

   /**
    * Sets Mailer to send message using the qmail MTA.  Returns void.
    * @public
    * @returns void
    */
   function IsQmail() {
      //$this->Sendmail = "/var/qmail/bin/qmail-inject";
      $this->Sendmail = "/var/qmail/bin/sendmail";
      $this->Mailer = "sendmail";
   }


   /////////////////////////////////////////////////
   // RECIPIENT METHODS
   /////////////////////////////////////////////////

   /**
    * Adds a "To" address.  Returns void.
    * @public
    * @returns void
    */
   function AddAddress($address, $name = "") {
      $cur = count($this->to);
      if (ereg("(.*)<(.*)>",$address,$data) && empty($name))
      {
        $this->to[$cur][0] = trim($data[2]);
        $this->to[$cur][1] = $data[1];
      }
      else
      {
        $this->to[$cur][0] = trim($address);
        $this->to[$cur][1] = $name;
      }
   }

   /**
    * Adds a "Cc" address. Note: this function works
    * with the SMTP mailer on win32, not with the "mail"
    * mailer.  This is a PHP bug that has been submitted
    * on the Zend web site. The UNIX version of PHP
    * functions correctly. Returns void.
    * @public
    * @returns void
    */
   function AddCC($address, $name = "") {
      $cur = count($this->cc);
      if (ereg("(.*)<(.*)>",$address,$data) && empty($name))
      {
        $this->cc[$cur][0] = trim($data[2]);
        $this->cc[$cur][1] = $data[1];
      }
      else
      {
        $this->cc[$cur][0] = trim($address);
        $this->cc[$cur][1] = $name;
      }
   }

   /**
    * Adds a "Bcc" address. Note: this function works
    * with the SMTP mailer on win32, not with the "mail"
    * mailer.  This is a PHP bug that has been submitted
    * on the Zend web site. The UNIX version of PHP
    * functions correctly.
    * Returns void.
    * @public
    * @returns void
    */
   function AddBCC($address, $name = "") {
      $cur = count($this->bcc);
      if (ereg("(.*)<(.*)>",$address,$data) && empty($name))
      {
        $this->bcc[$cur][0] = trim($data[2]);
        $this->bcc[$cur][1] = $data[1];
      }
      else
      {
        $this->bcc[$cur][0] = trim($address);
        $this->bcc[$cur][1] = $name;
      }
   }

   /**
    * Adds a "Reply-to" address.  Returns void.
    * @public
    * @returns void
    */
   function AddReplyTo($address, $name = "") {
      $cur = count($this->ReplyTo);
      if (ereg("(.*)<(.*)>",$address,$data) && empty($name))
      {
        $this->ReplyTo[$cur][0] = trim($data[2]);
        $this->ReplyTo[$cur][1] = $data[1];
      }
      else
      {
        $this->ReplyTo[$cur][0] = trim($address);
        $this->ReplyTo[$cur][1] = $name;
      }
   }


   /////////////////////////////////////////////////
   // MAIL SENDING METHODS
   /////////////////////////////////////////////////

   /**
    * Creates message and assigns Mailer. If the message is
    * not sent successfully then it returns false.  Returns bool.
    * @public
    * @returns bool
    */
   function Send() {
      if(count($this->to) < 1)
      {
         $this->error_handler("You must provide at least one recipient email 
address");
         return false;
      }

      // Set whether the message is multipart/alternative
      if(!empty($this->AltBody))
         $this->ContentType = "multipart/alternative";

      $header = $this->create_header();
      if(!$body = $this->create_body())
         return false;

      // echo "<pre>".$header . $body . "</pre>"; // debugging

      // Choose the mailer
      if($this->Mailer == "sendmail")
      {
         if(!$this->sendmail_send($header, $body))
            return false;
      }
      elseif($this->Mailer == "mail")
      {
         if(!$this->mail_send($header, $body))
            return false;
      }
      elseif($this->Mailer == "smtp")
      {
         if(!$this->smtp_send($header, $body))
            return false;
      }
      else
      {
         $this->error_handler(sprintf("%s mailer is not supported", 
$this->Mailer));
         return false;
      }

      return true;
   }

   /**
    * Sends mail using the $Sendmail program.  Returns bool.
    * @private
    * @returns bool
    */
   function sendmail_send($header, $body) {
      if ($this->Sender != "")
         $sendmail = sprintf("%s -f %s -t", $this->Sendmail, $this->Sender);
      else
         $sendmail = sprintf("%s -t", $this->Sendmail);

      if(address@hidden = popen($sendmail, "w"))
      {
         $this->error_handler(sprintf("Could not execute %s", $this->Sendmail));
         return false;
      }

      fputs($mail, $header);
      fputs($mail, $body);
      pclose($mail);

      return true;
   }

   /**
    * Sends mail using the PHP mail() function.  Returns bool.
    * @private
    * @returns bool
    */
   function mail_send($header, $body) {
      //$to = substr($this->addr_append("To", $this->to), 4, -2);

      // Cannot add Bcc's to the $to
      $to = $this->to[0][0]; // no extra comma
      for($i = 1; $i < count($this->to); $i++)
         $to .= sprintf(",%s", $this->to[$i][0]);

      if ($this->Sender != "" && PHP_VERSION >= "4.0")
      {
         $old_from = ini_get("sendmail_from");
         ini_set("sendmail_from", $this->Sender);
      }

      if ($this->Sender != "" && PHP_VERSION >= "4.0.5")
      {
         // The fifth parameter to mail is only available in PHP >= 4.0.5
         $params = sprintf("-f %s", $this->Sender);
         $rt = @mail($to, $this->Subject, $body, $header, $params);
      }
      else
      {
         $rt = @mail($to, $this->Subject, $body, $header);
      }

      if (isset($old_from))
         ini_set("sendmail_from", $old_from);

      if(!$rt)
      {
         $this->error_handler("Could not instantiate mail()");
         return false;
      }

      return true;
   }

   /**
    * Sends mail via SMTP using PhpSMTP (Author:
    * Chris Ryan).  Returns bool.
    * @private
    * @returns bool
    */
   function smtp_send($header, $body) {
      // Include SMTP class code, but not twice
      include_once(PHPGW_APP_ROOT . "/inc/class.smtp.php"); // Load code only 
if asked

      $smtp = new SMTP;

      $smtp->do_debug = $this->SMTPDebug;

      // Try to connect to all SMTP servers
      $hosts = explode(";", $this->Host);
      $index = 0;
      $connection = false;

      // Retry while there is no connection
      while($index < count($hosts) && $connection == false)
      {
         if($smtp->Connect($hosts[$index], $this->Port, $this->Timeout))
            $connection = true;
         //printf("%s host could not connect<br>", $hosts[$index]); //debug only
         $index++;
      }
      if(!$connection)
      {
         $this->error_handler("SMTP Error: could not connect to SMTP host 
server(s)");
         return false;
      }

      // Must perform HELO before authentication
      $smtp->Hello($this->Helo);

      // If user requests SMTP authentication
      if($this->SMTPAuth)
      {
         if(!$smtp->Authenticate($this->Username, $this->Password))
         {
            $this->error_handler("SMTP Error: Could not authenticate");
            return false;
         }
      }

      if ($this->Sender == "")
         $smtp->Mail(sprintf("<%s>", $this->From));
      else
         $smtp->Mail(sprintf("<%s>", $this->Sender));

      for($i = 0; $i < count($this->to); $i++)
         $smtp->Recipient(sprintf("<%s>", $this->to[$i][0]));
      for($i = 0; $i < count($this->cc); $i++)
         $smtp->Recipient(sprintf("<%s>", $this->cc[$i][0]));
      for($i = 0; $i < count($this->bcc); $i++)
         $smtp->Recipient(sprintf("<%s>", $this->bcc[$i][0]));

      if(!$smtp->Data(sprintf("%s%s", $header, $body)))
      {
         $this->error_handler("SMTP Error: Data not accepted");
         return false;
      }
      $smtp->Quit();

      return true;
   }


   /////////////////////////////////////////////////
   // MESSAGE CREATION METHODS
   /////////////////////////////////////////////////

   /**
    * Creates recipient headers.  Returns string.
    * @private
    * @returns string
    */
   function addr_append($type, $addr) {
      $addr_str = "";
      $addr_str .= sprintf("%s: %s <%s>", $type, $addr[0][1], $addr[0][0]);
      if(count($addr) > 1)
      {
         for($i = 1; $i < count($addr); $i++)
         {
            $addr_str .= sprintf(", %s <%s>", $addr[$i][1], $addr[$i][0]);
         }
         $addr_str .= "\r\n";
      }
      else
         $addr_str .= "\r\n";

      return($addr_str);
   }

   /**
    * Wraps message for use with mailers that do not
    * automatically perform wrapping and for quoted-printable.
    * Original written by philippe.  Returns string.
    * @private
    * @returns string
    */
   function wordwrap($message, $length, $qp_mode = false) {
      if ($qp_mode)
        $soft_break = " =\r\n";
      else
        $soft_break = "\r\n";

      $message = $this->fix_eol($message);
      if (substr($message, -1) == "\r\n")
        $message = substr($message, 0, -2);

      $line = explode("\r\n", $message);
      $message = "";
      for ($i=0 ;$i < count($line); $i++)
      {
         $line_part = explode(" ", trim($line[$i]));
         $buf = "";
         for ($e = 0; $e<count($line_part); $e++)
         {
            $word = $line_part[$e];
            if ($qp_mode and (strlen($word) > $length))
            {
               $space_left = $length - strlen($buf) - 1;
               if ($e != 0)
               {
                  if ($space_left > 20)
                  {
                     $len = $space_left;
                     if (substr($word, $len - 1, 1) == "=")
                        $len--;
                     elseif (substr($word, $len - 2, 1) == "=")
                        $len -= 2;
                     $part = substr($word, 0, $len);
                     $word = substr($word, $len);
                     $buf .= " " . $part;
                     $message .= $buf . "=\r\n";
                  }
                  else
                  {
                     $message .= $buf . $soft_break;
                  }
                  $buf = "";
               }
               while (strlen($word) > 0)
               {
                  $len = $length;
                  if (substr($word, $len - 1, 1) == "=")
                     $len--;
                  elseif (substr($word, $len - 2, 1) == "=")
                     $len -= 2;
                  $part = substr($word, 0, $len);
                  $word = substr($word, $len);

                  if (strlen($word) > 0)
                     $message .= $part . "=\r\n";
                  else
                     $buf = $part;
               }
            }
            else
            {
               $buf_o = $buf;
               if ($e == 0)
                  $buf .= $word;
               else
                  $buf .= " " . $word;
               if (strlen($buf) > $length and $buf_o != "")
               {
                  $message .= $buf_o . $soft_break;
                  $buf = $word;
               }
            }
         }
         $message .= $buf . "\r\n";
      }

      return ($message);
   }

   /**
    * Assembles message header.  Returns a string if successful
    * or false if unsuccessful.
    * @private
    * @returns string
    */
   function create_header() {
      $header = array();
      $header[] = sprintf("Date: %s\r\n", $this->rfc_date());

      // To be created automatically by mail()
      if($this->Mailer != "mail")
         $header[] = $this->addr_append("To", $this->to);

      $header[] = sprintf("From: %s <%s>\r\n", $this->FromName, 
trim($this->From));
      if(count($this->cc) > 0)
         $header[] = $this->addr_append("Cc", $this->cc);

      // sendmail and mail() extract Bcc from the header before sending
      if((($this->Mailer == "sendmail") || ($this->Mailer == "mail")) && 
(count($this->bcc) > 0))
         $header[] = $this->addr_append("Bcc", $this->bcc);

      if(count($this->ReplyTo) > 0)
         $header[] = $this->addr_append("Reply-to", $this->ReplyTo);

      // mail() sets the subject itself
      if($this->Mailer != "mail")
         $header[] = sprintf("Subject: %s\r\n", trim($this->Subject));

      $header[] = sprintf("X-Priority: %d\r\n", $this->Priority);
      $header[] = sprintf("X-Mailer: phpmailer [version %s]\r\n", 
$this->Version);
      $header[] = sprintf("Return-Path: %s\r\n", trim($this->From));

      // Add custom headers
      for($index = 0; $index < count($this->CustomHeader); $index++)
         $header[] = sprintf("%s\r\n", $this->CustomHeader[$index]);

      if($this->UseMSMailHeaders)
         $header[] = $this->AddMSMailHeaders();

      $header[] = "MIME-Version: 1.0\r\n";

      // Add all attachments
      if(count($this->attachment) > 0 || !empty($this->AltBody))
      {
         // Set message boundary
         $this->boundary = "_b" . md5(uniqid(time()));
         // Set message subboundary for multipart/alternative
         $this->subboundary = "_sb" . md5(uniqid(time()));

         $header[] = "Content-Type: Multipart/Mixed;\r\n";
         $header[] = sprintf(" boundary=\"Boundary-=%s\"\r\n\r\n", 
$this->boundary);
      }
      else
      {
         $header[] = sprintf("Content-Transfer-Encoding: %s\r\n", 
$this->Encoding);
         $header[] = sprintf("Content-Type: %s; charset = \"%s\"\r\n\r\n",
                             $this->ContentType, $this->CharSet);
      }

      return(join("", $header));
   }

   /**
    * Assembles the message body.  Returns a string if successful
    * or false if unsuccessful.
    * @private
    * @returns string
    */
   function create_body() {
      // wordwrap the message body if set
      if($this->WordWrap)
         $this->Body = $this->wordwrap($this->Body, $this->WordWrap);

      // If content type is multipart/alternative set body like this:
      if ((!empty($this->AltBody)) && (count($this->attachment) < 1))
      {
         // Return text of body
         $mime = array();
         $mime[] = "This is a MIME message. If you are reading this text, 
you\r\n";
         $mime[] = "might want to consider changing to a mail reader that\r\n";
         $mime[] = "understands how to properly display MIME multipart 
messages.\r\n\r\n";
         $mime[] = sprintf("--Boundary-=%s\r\n", $this->boundary);

         // Insert body. If multipart/alternative, insert both html and plain
         $mime[] = sprintf("Content-Type: %s; charset = \"%s\"; boundary = 
\"Boundary-=%s\";\r\n",
                           $this->ContentType, $this->CharSet, 
$this->subboundary);
         $mime[] = sprintf("Content-Transfer-Encoding: %s\r\n\r\n", 
$this->Encoding);

         $mime[] = sprintf("--Boundary-=%s\r\n", $this->subboundary);
         $mime[] = sprintf("Content-Type: text/html; charset = \"%s\";\r\n", 
$this->CharSet);
         $mime[] = sprintf("Content-Transfer-Encoding: %s\r\n\r\n", 
$this->Encoding);
         $mime[] = sprintf("%s\r\n\r\n", $this->Body);

         $mime[] = sprintf("--Boundary-=%s\r\n", $this->subboundary);
         $mime[] = sprintf("Content-Type: text/plain; charset = \"%s\";\r\n", 
$this->CharSet);
         $mime[] = sprintf("Content-Transfer-Encoding: %s\r\n\r\n", 
$this->Encoding);
         $mime[] = sprintf("%s\r\n\r\n", $this->AltBody);

         $mime[] = sprintf("\r\n--Boundary-=%s--\r\n\r\n", $this->subboundary);

         $mime[] = sprintf("\r\n--Boundary-=%s--\r\n", $this->boundary);

         $this->Body = $this->encode_string(join("", $mime), $this->Encoding);
      }
      else
      {
         $this->Body = $this->encode_string($this->Body, $this->Encoding);
      }


      if(count($this->attachment) > 0)
      {
         if(!$body = $this->attach_all())
            return false;
      }
      else
         $body = $this->Body;

      return($body);
   }


   /////////////////////////////////////////////////
   // ATTACHMENT METHODS
   /////////////////////////////////////////////////

   /**
    * Adds an attachment from the OS filesystem.
    * Checks if attachment is valid and then adds
    * the attachment to the list.
    * Returns false if the file was not found.
    * @public
    * @returns bool
    */
   function AddAttachment($path, $name = "", $encoding = "base64", $type = 
"application/octet-stream") {
      if(address@hidden($path))
      {
         $this->error_handler(sprintf("Could not find %s file on filesystem", 
$path));
         return false;
      }

      $filename = basename($path);
      if($name == "")
         $name = $filename;

      // Append to $attachment array
      $cur = count($this->attachment);
      $this->attachment[$cur][0] = $path;
      $this->attachment[$cur][1] = $filename;
      $this->attachment[$cur][2] = $name;
      $this->attachment[$cur][3] = $encoding;
      $this->attachment[$cur][4] = $type;
      $this->attachment[$cur][5] = false; // isStringAttachment

      return true;
   }

   /**
    * Attaches all fs, string, and binary attachments to the message.
    * Returns a string if successful or false if unsuccessful.
    * @private
    * @returns string
    */
   function attach_all() {
      // Return text of body
      $mime = array();
      $mime[] = "This is a MIME message. If you are reading this text, you\r\n";
      $mime[] = "might want to consider changing to a mail reader that\r\n";
      $mime[] = "understands how to properly display MIME multipart 
messages.\r\n\r\n";
      $mime[] = sprintf("--Boundary-=%s\r\n", $this->boundary);

      // Insert body. If multipart/alternative, insert both html and plain.
      if (!empty($this->AltBody))
      {
          $mime[] = sprintf("Content-Type: %s; charset = \"%s\"; boundary = 
\"Boundary-=%s\";\r\n",
                            $this->ContentType, $this->CharSet, 
$this->subboundary);
          $mime[] = sprintf("Content-Transfer-Encoding: %s\r\n\r\n", 
$this->Encoding);

          $mime[] = sprintf("--Boundary-=%s\r\n", $this->subboundary);
          $mime[] = sprintf("Content-Type: text/html; charset = \"%s\";\r\n", 
$this->CharSet);
          $mime[] = sprintf("Content-Transfer-Encoding: %s\r\n\r\n", 
$this->Encoding);
          $mime[] = sprintf("%s\r\n\r\n", $this->Body);

          $mime[] = sprintf("--Boundary-=%s\r\n", $this->subboundary);
          $mime[] = sprintf("Content-Type: text/plain; charset = \"%s\";\r\n", 
$this->CharSet);
          $mime[] = sprintf("Content-Transfer-Encoding: %s\r\n\r\n", 
$this->Encoding);
          $mime[] = sprintf("%s\r\n\r\n", $this->AltBody);

          $mime[] = sprintf("\r\n--Boundary-=%s--\r\n\r\n", $this->subboundary);
      }
      else
      {
          $mime[] = sprintf("Content-Type: %s; charset = \"%s\";\r\n", 
$this->ContentType, $this->CharSet);
          $mime[] = sprintf("Content-Transfer-Encoding: %s\r\n\r\n", 
$this->Encoding);
          $mime[] = sprintf("%s\r\n", $this->Body);
      }

      // Add all attachments
      for($i = 0; $i < count($this->attachment); $i++)
      {
         // Check for string attachment
         $isString = $this->attachment[$i][5];
         if ($isString)
         {
            $string = $this->attachment[$i][0];
         }
         else
         {
            $path = $this->attachment[$i][0];
         }
         $filename = $this->attachment[$i][1];
         $name = $this->attachment[$i][2];
         $encoding = $this->attachment[$i][3];
         $type = $this->attachment[$i][4];
         $mime[] = sprintf("--Boundary-=%s\r\n", $this->boundary);
         $mime[] = sprintf("Content-Type: %s; ", $type);
         $mime[] = sprintf("name=\"%s\"\r\n", $name);
         $mime[] = sprintf("Content-Transfer-Encoding: %s\r\n", $encoding);
         $mime[] = sprintf("Content-Disposition: attachment; 
filename=\"%s\"\r\n\r\n", $name);

         // Encode as string attachment
         if($isString)
         {
            if(!$mime[] = sprintf("%s\r\n\r\n", $this->encode_string($string, 
$encoding)))
               return false;
         }
         else
         {
            if(!$mime[] = sprintf("%s\r\n\r\n", $this->encode_file($path, 
$encoding)))
               return false;
         }
      }
      $mime[] = sprintf("\r\n--Boundary-=%s--\r\n", $this->boundary);

      return(join("", $mime));
   }

   /**
    * Encodes attachment in requested format.  Returns a
    * string if successful or false if unsuccessful.
    * @private
    * @returns string
    */
   function encode_file ($path, $encoding = "base64") {
      if(address@hidden = fopen($path, "rb"))
      {
         $this->error_handler(sprintf("File Error: Could not open file %s", 
$path));
         return false;
      }
      $file = fread($fd, filesize($path));
      $encoded = $this->encode_string($file, $encoding);
      fclose($fd);

      return($encoded);
   }

   /**
    * Encodes string to requested format. Returns a
    * string if successful or false if unsuccessful.
    * @private
    * @returns string
    */
   function encode_string ($str, $encoding = "base64") {
      switch(strtolower($encoding)) {
         case "base64":
            // chunk_split is found in PHP >= 3.0.6
            $encoded = chunk_split(base64_encode($str));
            break;

         case "7bit":
         case "8bit":
            $encoded = $this->fix_eol($str);
            if (substr($encoded, -2) != "\r\n")
               $encoded .= "\r\n";
            break;

         case "binary":
            $encoded = $str;
            break;

         case "quoted-printable":
            $encoded = $this->encode_qp($str);
            break;

         default:
            $this->error_handler(sprintf("Unknown encoding: %s", $encoding));
            return false;
      }
      return($encoded);
   }

   /**
    * Encode string to quoted-printable.  Returns a string.
    * @private
    * @returns string
    */
   function encode_qp ($str) {
      $encoded = $this->fix_eol($str);
      if (substr($encoded, -2) != "\r\n")
         $encoded .= "\r\n";

      // Replace every high ascii, control and = characters
      $encoded = preg_replace("/([\001-\010\013\014\016-\037\075\177-\377])/e",
                 "'='.sprintf('%02X', ord('\\1'))", $encoded);
      // Replace every spaces and tabs when it's the last character on a line
      $encoded = preg_replace("/([\011\040])\r\n/e",
                 "'='.sprintf('%02X', ord('\\1')).'\r\n'", $encoded);

      // Maximum line length of 76 characters before CRLF (74 + space + '=')
      $encoded = $this->WordWrap($encoded, 74, true);

      return $encoded;
   }

   /**
   * Adds a string or binary attachment (non-filesystem) to the list.
   * This method can be used to attach ascii or binary data,
   * such as a BLOB record from a database.
   * @public
   * @returns void
   */
   function AddStringAttachment($string, $filename, $encoding = "binary", $type 
= "application/octet-stream") {
      // Append to $attachment array
      $cur = count($this->attachment);
      $this->attachment[$cur][0] = $string;
      $this->attachment[$cur][1] = $filename;
      $this->attachment[$cur][2] = $filename;
      $this->attachment[$cur][3] = $encoding;
      $this->attachment[$cur][4] = $type;
      $this->attachment[$cur][5] = true; // isString
   }

   /////////////////////////////////////////////////
   // MESSAGE RESET METHODS
   /////////////////////////////////////////////////

   /**
    * Clears all recipients assigned in the TO array.  Returns void.
    * @public
    * @returns void
    */
   function ClearAddresses() {
      $this->to = array();
   }

   /**
    * Clears all recipients assigned in the CC array.  Returns void.
    * @public
    * @returns void
    */
   function ClearCCs() {
      $this->cc = array();
   }

   /**
    * Clears all recipients assigned in the BCC array.  Returns void.
    * @public
    * @returns void
    */
   function ClearBCCs() {
      $this->bcc = array();
   }

   /**
    * Clears all recipients assigned in the ReplyTo array.  Returns void.
    * @public
    * @returns void
    */
   function ClearReplyTos() {
      $this->ReplyTo = array();
   }

   /**
    * Clears all recipients assigned in the TO, CC and BCC
    * array.  Returns void.
    * @public
    * @returns void
    */
   function ClearAllRecipients() {
      $this->to = array();
      $this->cc = array();
      $this->bcc = array();
   }

   /**
    * Clears all previously set filesystem, string, and binary
    * attachments.  Returns void.
    * @public
    * @returns void
    */
   function ClearAttachments() {
      $this->attachment = array();
   }

   /**
    * Clears all custom headers.  Returns void.
    * @public
    * @returns void
    */
   function ClearCustomHeaders() {
      $this->CustomHeader = array();
   }


   /////////////////////////////////////////////////
   // MISCELLANEOUS METHODS
   /////////////////////////////////////////////////

   /**
    * Adds the error message to the error container.
    * Returns void.
    * @private
    * @returns void
    */
   function error_handler($msg) {
        $this->ErrorInfo = $msg;
   }

   /**
    * Returns the proper RFC 822 formatted date. Returns string.
    * @private
    * @returns string
    */
   function rfc_date() {
        $tz = date("Z");
        $tzs = ($tz < 0) ? "-" : "+";
        $tz = abs($tz);
        $tz = ($tz/3600)*100 + ($tz%3600)/60;
        $date = sprintf("%s %s%04d", date("D, j M Y H:i:s"), $tzs, $tz);
        return $date;
   }

   /**
    * Changes every end of line from CR or LF to CRLF.  Returns string.
    * @private
    * @returns string
    */
   function fix_eol($str) {
      $str = str_replace("\r\n", "\n", $str);
      $str = str_replace("\r", "\n", $str);
      $str = str_replace("\n", "\r\n", $str);
      return $str;
   }

   /**
    * Adds a custom header.  Returns void.
    * @public
    * @returns void
    */
   function AddCustomHeader($custom_header) {
      $this->CustomHeader[] = $custom_header;
   }

   /**
    * Adds all the Microsoft message headers.  Returns string.
    * @private
    * @returns string
    */
   function AddMSMailHeaders() {
      $MSHeader = "";
      if($this->Priority == 1)
         $MSPriority = "High";
      elseif($this->Priority == 5)
         $MSPriority = "Low";
      else
         $MSPriority = "Medium";

      $MSHeader .= sprintf("X-MSMail-Priority: %s\r\n", $MSPriority);
      $MSHeader .= sprintf("Importance: %s\r\n", $MSPriority);

      return($MSHeader);
   }

}
// End of class
?>

====================================================
Index: class.smtp.php
<?php
    /*
     * File: smtp.php
     *
     * Description: Define an SMTP class that can be used to connect
     *              and communicate with any SMTP server. It implements
     *              all the SMTP functions defined in RFC821 except TURN.
     *
     * Creator: Chris Ryan <address@hidden>
     * Created: 03/26/2001
     *
     * TODO:
     *     - Move all the duplicate code to a utility function
     *           Most of the functions have the first lines of
     *           code do the same processing. If this can be moved
     *           into a utility function then it would reduce the
     *           overall size of the code significantly.
     */

    /*
     * STMP is rfc 821 compliant and implements all the rfc 821 SMTP
     * commands except TURN which will always return a not implemented
     * error. SMTP also provides some utility methods for sending mail
     * to an SMTP server.
     */
    class SMTP {
        var $SMTP_PORT = 25; # the default SMTP PORT
        var $CRLF = "\r\n";  # CRLF pair

        var $smtp_conn;      # the socket to the server
        var $error;          # error if any on the last call
        var $helo_rply;      # the reply the server sent to us for HELO

        var $do_debug;       # the level of debug to perform

        /*
         * SMTP()
         *
         * Initialize the class so that the data is in a known state.
         */
        function SMTP() {
            $this->smtp_conn = 0;
            $this->error = null;
            $this->helo_rply = null;

            $this->do_debug = 0;
        }

        /************************************************************
         *                    CONNECTION FUNCTIONS                  *
         ***********************************************************/

        /*
         * Connect($host, $port=0, $tval=30)
         *
         * Connect to the server specified on the port specified.
         * If the port is not specified use the default SMTP_PORT.
         * If tval is specified then a connection will try and be
         * established with the server for that number of seconds.
         * If tval is not specified the default is 30 seconds to
         * try on the connection.
         *
         * SMTP CODE SUCCESS: 220
         * SMTP CODE FAILURE: 421
         */
        function Connect($host,$port=0,$tval=30) {
            # set the error val to null so there is no confusion
            $this->error = null;

            # make sure we are __not__ connected
            if($this->connected()) {
                # ok we are connected! what should we do?
                # for now we will just give an error saying we
                # are already connected
                $this->error =
                    array("error" => "Already connected to a server");
                return false;
            }

            if(empty($port)) {
                $port = $this->SMTP_PORT;
            }

            #connect to the smtp server
            $this->smtp_conn = fsockopen($host,    # the host of the server
                                         $port,    # the port to use
                                         $errno,   # error number if any
                                         $errstr,  # error message if any
                                         $tval);   # give up after ? secs
            # verify we connected properly
            if(empty($this->smtp_conn)) {
                $this->error = array("error" => "Failed to connect to server",
                                     "errno" => $errno,
                                     "errstr" => $errstr);
                if($this->do_debug >= 1) {
                    echo "SMTP -> ERROR: " . $this->error["error"] .
                             ": $errstr ($errno)" . $this->CRLF;
                }
                return false;
            }

            # sometimes the SMTP server takes a little longer to respond
            # so we will give it a longer timeout for the first read
            // Commented b/c of win32 warning messages
            //if(function_exists("socket_set_timeout"))
            //   socket_set_timeout($this->smtp_conn, 1, 0);

            # get any announcement stuff
            $announce = $this->get_lines();

            # set the timeout  of any socket functions at 1/10 of a second
            //if(function_exists("socket_set_timeout"))
            //   socket_set_timeout($this->smtp_conn, 0, 100000);

            if($this->do_debug >= 2) {
                echo "SMTP -> FROM SERVER:" . $this->CRLF . $announce;
            }

            return true;
        }

        /*
         * Authenticate()
         *
         * Performs SMTP authentication.  Must be run after running the
         * Hello() method.  Returns true if successfully authenticated.
         */
        function Authenticate($username, $password) {
            // Start authentication
            fputs($this->smtp_conn,"AUTH LOGIN" . $this->CRLF);

            $rply = $this->get_lines();
            $code = substr($rply,0,3);

            if($code != 334) {
                $this->error =
                    array("error" => "AUTH not accepted from server",
                          "smtp_code" => $code,
                          "smtp_msg" => substr($rply,4));
                if($this->do_debug >= 1) {
                    echo "SMTP -> ERROR: " . $this->error["error"] .
                             ": " . $rply . $this->CRLF;
                }
                return false;
            }

            // Send encoded username
            fputs($this->smtp_conn, base64_encode($username) . $this->CRLF);

            $rply = $this->get_lines();
            $code = substr($rply,0,3);

            if($code != 334) {
                $this->error =
                    array("error" => "Username not accepted from server",
                          "smtp_code" => $code,
                          "smtp_msg" => substr($rply,4));
                if($this->do_debug >= 1) {
                    echo "SMTP -> ERROR: " . $this->error["error"] .
                             ": " . $rply . $this->CRLF;
                }
                return false;
            }

            // Send encoded password
            fputs($this->smtp_conn, base64_encode($password) . $this->CRLF);

            $rply = $this->get_lines();
            $code = substr($rply,0,3);

            if($code != 235) {
                $this->error =
                    array("error" => "Password not accepted from server",
                          "smtp_code" => $code,
                          "smtp_msg" => substr($rply,4));
                if($this->do_debug >= 1) {
                    echo "SMTP -> ERROR: " . $this->error["error"] .
                             ": " . $rply . $this->CRLF;
                }
                return false;
            }

            return true;
        }

        /*
         * Connected()
         *
         * Returns true if connected to a server otherwise false
         */
        function Connected() {
            if(!empty($this->smtp_conn)) {
                $sock_status = socket_get_status($this->smtp_conn);
                if($sock_status["eof"]) {
                    # hmm this is an odd situation... the socket is
                    # valid but we aren't connected anymore
                    if($this->do_debug >= 1) {
                        echo "SMTP -> NOTICE:" . $this->CRLF .
                             "EOF caught while checking if connected";
                    }
                    $this->Close();
                    return false;
                }
                return true; # everything looks good
            }
            return false;
        }

        /*
         * Close()
         *
         * Closes the socket and cleans up the state of the class.
         * It is not considered good to use this function without
         * first trying to use QUIT.
         */
        function Close() {
            $this->error = null; # so there is no confusion
            $this->helo_rply = null;
            if(!empty($this->smtp_conn)) {
                # close the connection and cleanup
                fclose($this->smtp_conn);
                $this->smtp_conn = 0;
            }
        }


        /**************************************************************
         *                        SMTP COMMANDS                       *
         *************************************************************/

        /*
         * Data($msg_data)
         *
         * Issues a data command and sends the msg_data to the server
         * finializing the mail transaction. $msg_data is the message
         * that is to be send with the headers. Each header needs to be
         * on a single line followed by a <CRLF> with the message headers
         * and the message body being seperated by and additional <CRLF>.
         *
         * Implements rfc 821: DATA <CRLF>
         *
         * SMTP CODE INTERMEDIATE: 354
         *     [data]
         *     <CRLF>.<CRLF>
         *     SMTP CODE SUCCESS: 250
         *     SMTP CODE FAILURE: 552,554,451,452
         * SMTP CODE FAILURE: 451,554
         * SMTP CODE ERROR  : 500,501,503,421
         */
        function Data($msg_data) {
            $this->error = null; # so no confusion is caused

            if(!$this->connected()) {
                $this->error = array(
                        "error" => "Called Data() without being connected");
                return false;
            }

            fputs($this->smtp_conn,"DATA" . $this->CRLF);

            $rply = $this->get_lines();
            $code = substr($rply,0,3);

            if($this->do_debug >= 2) {
                echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
            }

            if($code != 354) {
                $this->error =
                    array("error" => "DATA command not accepted from server",
                          "smtp_code" => $code,
                          "smtp_msg" => substr($rply,4));
                if($this->do_debug >= 1) {
                    echo "SMTP -> ERROR: " . $this->error["error"] .
                             ": " . $rply . $this->CRLF;
                }
                return false;
            }

            # the server is ready to accept data!
            # according to rfc 821 we should not send more than 1000
            # including the CRLF
            # characters on a single line so we will break the data up
            # into lines by \r and/or \n then if needed we will break
            # each of those into smaller lines to fit within the limit.
            # in addition we will be looking for lines that start with
            # a period '.' and append and additional period '.' to that
            # line. NOTE: this does not count towards are limit.

            # normalize the line breaks so we know the explode works
            $msg_data = str_replace("\r\n","\n",$msg_data);
            $msg_data = str_replace("\r","\n",$msg_data);
            $lines = explode("\n",$msg_data);

            # we need to find a good way to determine is headers are
            # in the msg_data or if it is a straight msg body
            # currently I'm assuming rfc 822 definitions of msg headers
            # and if the first field of the first line (':' sperated)
            # does not contain a space then it _should_ be a header
            # and we can process all lines before a blank "" line as
            # headers.
            $field = substr($lines[0],0,strpos($lines[0],":"));
            $in_headers = false;
            if(!empty($field) && !strstr($field," ")) {
                $in_headers = true;
            }

            $max_line_length = 998; # used below; set here for ease in change

            while(list(,$line) = @each($lines)) {
                $lines_out = null;
                if($line == "" && $in_headers) {
                    $in_headers = false;
                }
                # ok we need to break this line up into several
                # smaller lines
                while(strlen($line) > $max_line_length) {
                    $pos = strrpos(substr($line,0,$max_line_length)," ");
                    $lines_out[] = substr($line,0,$pos);
                    $line = substr($line,$pos + 1);
                    # if we are processing headers we need to
                    # add a LWSP-char to the front of the new line
                    # rfc 822 on long msg headers
                    if($in_headers) {
                        $line = "\t" . $line;
                    }
                }
                $lines_out[] = $line;

                # now send the lines to the server
                while(list(,$line_out) = @each($lines_out)) {
                    if($line_out[0] == ".") {
                        $line_out = "." . $line_out;
                    }
                    fputs($this->smtp_conn,$line_out . $this->CRLF);
                }
            }

            # ok all the message data has been sent so lets get this
            # over with aleady
            fputs($this->smtp_conn, $this->CRLF . "." . $this->CRLF);

            $rply = $this->get_lines();
            $code = substr($rply,0,3);

            if($this->do_debug >= 2) {
                echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
            }

            if($code != 250) {
                $this->error =
                    array("error" => "DATA not accepted from server",
                          "smtp_code" => $code,
                          "smtp_msg" => substr($rply,4));
                if($this->do_debug >= 1) {
                    echo "SMTP -> ERROR: " . $this->error["error"] .
                             ": " . $rply . $this->CRLF;
                }
                return false;
            }
            return true;
        }

        /*
         * Expand($name)
         *
         * Expand takes the name and asks the server to list all the
         * people who are members of the _list_. Expand will return
         * back and array of the result or false if an error occurs.
         * Each value in the array returned has the format of:
         *     [ <full-name> <sp> ] <path>
         * The definition of <path> is defined in rfc 821
         *
         * Implements rfc 821: EXPN <SP> <string> <CRLF>
         *
         * SMTP CODE SUCCESS: 250
         * SMTP CODE FAILURE: 550
         * SMTP CODE ERROR  : 500,501,502,504,421
         */
        function Expand($name) {
            $this->error = null; # so no confusion is caused

            if(!$this->connected()) {
                $this->error = array(
                        "error" => "Called Expand() without being connected");
                return false;
            }

            fputs($this->smtp_conn,"EXPN " . $name . $this->CRLF);

            $rply = $this->get_lines();
            $code = substr($rply,0,3);

            if($this->do_debug >= 2) {
                echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
            }

            if($code != 250) {
                $this->error =
                    array("error" => "EXPN not accepted from server",
                          "smtp_code" => $code,
                          "smtp_msg" => substr($rply,4));
                if($this->do_debug >= 1) {
                    echo "SMTP -> ERROR: " . $this->error["error"] .
                             ": " . $rply . $this->CRLF;
                }
                return false;
            }

            # parse the reply and place in our array to return to user
            $entries = explode($this->CRLF,$rply);
            while(list(,$l) = @each($entries)) {
                $list[] = substr($l,4);
            }

            return $rval;
        }

        /*
         * Hello($host="")
         *
         * Sends the HELO command to the smtp server.
         * This makes sure that we and the server are in
         * the same known state.
         *
         * Implements from rfc 821: HELO <SP> <domain> <CRLF>
         *
         * SMTP CODE SUCCESS: 250
         * SMTP CODE ERROR  : 500, 501, 504, 421
         */
        function Hello($host="") {
            $this->error = null; # so no confusion is caused

            if(!$this->connected()) {
                $this->error = array(
                        "error" => "Called Hello() without being connected");
                return false;
            }

            # if a hostname for the HELO wasn't specified determine
            # a suitable one to send
            if(empty($host)) {
                # we need to determine some sort of appopiate default
                # to send to the server
                $host = "localhost";
            }

            fputs($this->smtp_conn,"HELO " . $host . $this->CRLF);

            $rply = $this->get_lines();
            $code = substr($rply,0,3);

            if($this->do_debug >= 2) {
                echo "SMTP -> FROM SERVER: " . $this->CRLF . $rply;
            }

            if($code != 250) {
                $this->error =
                    array("error" => "HELO not accepted from server",
                          "smtp_code" => $code,
                          "smtp_msg" => substr($rply,4));
                if($this->do_debug >= 1) {
                    echo "SMTP -> ERROR: " . $this->error["error"] .
                             ": " . $rply . $this->CRLF;
                }
                return false;
            }

            $this->helo_rply = $rply;

            return true;
        }

        /*
         * Help($keyword="")
         *
         * Gets help information on the keyword specified. If the keyword
         * is not specified then returns generic help, ussually contianing
         * A list of keywords that help is available on. This function
         * returns the results back to the user. It is up to the user to
         * handle the returned data. If an error occurs then false is
         * returned with $this->error set appropiately.
         *
         * Implements rfc 821: HELP [ <SP> <string> ] <CRLF>
         *
         * SMTP CODE SUCCESS: 211,214
         * SMTP CODE ERROR  : 500,501,502,504,421
         *
         */
        function Help($keyword="") {
            $this->error = null; # to avoid confusion

            if(!$this->connected()) {
                $this->error = array(
                        "error" => "Called Help() without being connected");
                return false;
            }

            $extra = "";
            if(!empty($keyword)) {
                $extra = " " . $keyword;
            }

            fputs($this->smtp_conn,"HELP" . $extra . $this->CRLF);

            $rply = $this->get_lines();
            $code = substr($rply,0,3);

            if($this->do_debug >= 2) {
                echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
            }

            if($code != 211 && $code != 214) {
                $this->error =
                    array("error" => "HELP not accepted from server",
                          "smtp_code" => $code,
                          "smtp_msg" => substr($rply,4));
                if($this->do_debug >= 1) {
                    echo "SMTP -> ERROR: " . $this->error["error"] .
                             ": " . $rply . $this->CRLF;
                }
                return false;
            }

            return $rply;
        }

        /*
         * Mail($from)
         *
         * Starts a mail transaction from the email address specified in
         * $from. Returns true if successful or false otherwise. If True
         * the mail transaction is started and then one or more Recipient
         * commands may be called followed by a Data command.
         *
         * Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
         *
         * SMTP CODE SUCCESS: 250
         * SMTP CODE SUCCESS: 552,451,452
         * SMTP CODE SUCCESS: 500,501,421
         */
        function Mail($from) {
            $this->error = null; # so no confusion is caused

            if(!$this->connected()) {
                $this->error = array(
                        "error" => "Called Mail() without being connected");
                return false;
            }

            fputs($this->smtp_conn,"MAIL FROM:" . $from . $this->CRLF);

            $rply = $this->get_lines();
            $code = substr($rply,0,3);

            if($this->do_debug >= 2) {
                echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
            }

            if($code != 250) {
                $this->error =
                    array("error" => "MAIL not accepted from server",
                          "smtp_code" => $code,
                          "smtp_msg" => substr($rply,4));
                if($this->do_debug >= 1) {
                    echo "SMTP -> ERROR: " . $this->error["error"] .
                             ": " . $rply . $this->CRLF;
                }
                return false;
            }
            return true;
        }

        /*
         * Noop()
         *
         * Sends the command NOOP to the SMTP server.
         *
         * Implements from rfc 821: NOOP <CRLF>
         *
         * SMTP CODE SUCCESS: 250
         * SMTP CODE ERROR  : 500, 421
         */
        function Noop() {
            $this->error = null; # so no confusion is caused

            if(!$this->connected()) {
                $this->error = array(
                        "error" => "Called Noop() without being connected");
                return false;
            }

            fputs($this->smtp_conn,"NOOP" . $this->CRLF);

            $rply = $this->get_lines();
            $code = substr($rply,0,3);

            if($this->do_debug >= 2) {
                echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
            }

            if($code != 250) {
                $this->error =
                    array("error" => "NOOP not accepted from server",
                          "smtp_code" => $code,
                          "smtp_msg" => substr($rply,4));
                if($this->do_debug >= 1) {
                    echo "SMTP -> ERROR: " . $this->error["error"] .
                             ": " . $rply . $this->CRLF;
                }
                return false;
            }
            return true;
        }

        /*
         * Quit($close_on_error=true)
         *
         * Sends the quit command to the server and then closes the socket
         * if there is no error or the $close_on_error argument is true.
         *
         * Implements from rfc 821: QUIT <CRLF>
         *
         * SMTP CODE SUCCESS: 221
         * SMTP CODE ERROR  : 500
         */
        function Quit($close_on_error=true) {
            $this->error = null; # so there is no confusion

            if(!$this->connected()) {
                $this->error = array(
                        "error" => "Called Quit() without being connected");
                return false;
            }

            # send the quit command to the server
            fputs($this->smtp_conn,"quit" . $this->CRLF);

            # get any good-bye messages
            $byemsg = $this->get_lines();

            if($this->do_debug >= 2) {
                echo "SMTP -> FROM SERVER:" . $this->CRLF . $byemsg;
            }

            $rval = true;
            $e = null;

            $code = substr($byemsg,0,3);
            if($code != 221) {
                # use e as a tmp var cause Close will overwrite $this->error
                $e = array("error" => "SMTP server rejected quit command",
                           "smtp_code" => $code,
                           "smtp_rply" => substr($byemsg,4));
                $rval = false;
                if($this->do_debug >= 1) {
                    echo "SMTP -> ERROR: " . $e["error"] . ": " .
                             $byemsg . $this->CRLF;
                }
            }

            if(empty($e) || $close_on_error) {
                $this->Close();
            }

            return $rval;
        }

        /*
         * Recipient($to)
         *
         * Sends the command RCPT to the SMTP server with the TO: argument of 
$to.
         * Returns true if the recipient was accepted false if it was rejected.
         *
         * Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
         *
         * SMTP CODE SUCCESS: 250,251
         * SMTP CODE FAILURE: 550,551,552,553,450,451,452
         * SMTP CODE ERROR  : 500,501,503,421
         */
        function Recipient($to) {
            $this->error = null; # so no confusion is caused

            if(!$this->connected()) {
                $this->error = array(
                        "error" => "Called Recipient() without being 
connected");
                return false;
            }

            fputs($this->smtp_conn,"RCPT TO:" . $to . $this->CRLF);

            $rply = $this->get_lines();
            $code = substr($rply,0,3);

            if($this->do_debug >= 2) {
                echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
            }

            if($code != 250 && $code != 251) {
                $this->error =
                    array("error" => "RCPT not accepted from server",
                          "smtp_code" => $code,
                          "smtp_msg" => substr($rply,4));
                if($this->do_debug >= 1) {
                    echo "SMTP -> ERROR: " . $this->error["error"] .
                             ": " . $rply . $this->CRLF;
                }
                return false;
            }
            return true;
        }

        /*
         * Reset()
         *
         * Sends the RSET command to abort and transaction that is
         * currently in progress. Returns true if successful false
         * otherwise.
         *
         * Implements rfc 821: RSET <CRLF>
         *
         * SMTP CODE SUCCESS: 250
         * SMTP CODE ERROR  : 500,501,504,421
         */
        function Reset() {
            $this->error = null; # so no confusion is caused

            if(!$this->connected()) {
                $this->error = array(
                        "error" => "Called Reset() without being connected");
                return false;
            }

            fputs($this->smtp_conn,"RSET" . $this->CRLF);

            $rply = $this->get_lines();
            $code = substr($rply,0,3);

            if($this->do_debug >= 2) {
                echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
            }

            if($code != 250) {
                $this->error =
                    array("error" => "RSET failed",
                          "smtp_code" => $code,
                          "smtp_msg" => substr($rply,4));
                if($this->do_debug >= 1) {
                    echo "SMTP -> ERROR: " . $this->error["error"] .
                             ": " . $rply . $this->CRLF;
                }
                return false;
            }

            return true;
        }

        /*
         * Send($from)
         *
         * Starts a mail transaction from the email address specified in
         * $from. Returns true if successful or false otherwise. If True
         * the mail transaction is started and then one or more Recipient
         * commands may be called followed by a Data command. This command
         * will send the message to the users terminal if they are logged
         * in.
         *
         * Implements rfc 821: SEND <SP> FROM:<reverse-path> <CRLF>
         *
         * SMTP CODE SUCCESS: 250
         * SMTP CODE SUCCESS: 552,451,452
         * SMTP CODE SUCCESS: 500,501,502,421
         */
        function Send($from) {
            $this->error = null; # so no confusion is caused

            if(!$this->connected()) {
                $this->error = array(
                        "error" => "Called Send() without being connected");
                return false;
            }

            fputs($this->smtp_conn,"SEND FROM:" . $from . $this->CRLF);

            $rply = $this->get_lines();
            $code = substr($rply,0,3);

            if($this->do_debug >= 2) {
                echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
            }

            if($code != 250) {
                $this->error =
                    array("error" => "SEND not accepted from server",
                          "smtp_code" => $code,
                          "smtp_msg" => substr($rply,4));
                if($this->do_debug >= 1) {
                    echo "SMTP -> ERROR: " . $this->error["error"] .
                             ": " . $rply . $this->CRLF;
                }
                return false;
            }
            return true;
        }

        /*
         * SendAndMail($from)
         *
         * Starts a mail transaction from the email address specified in
         * $from. Returns true if successful or false otherwise. If True
         * the mail transaction is started and then one or more Recipient
         * commands may be called followed by a Data command. This command
         * will send the message to the users terminal if they are logged
         * in and send them an email.
         *
         * Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
         *
         * SMTP CODE SUCCESS: 250
         * SMTP CODE SUCCESS: 552,451,452
         * SMTP CODE SUCCESS: 500,501,502,421
         */
        function SendAndMail($from) {
            $this->error = null; # so no confusion is caused

            if(!$this->connected()) {
                $this->error = array(
                    "error" => "Called SendAndMail() without being connected");
                return false;
            }

            fputs($this->smtp_conn,"SAML FROM:" . $from . $this->CRLF);

            $rply = $this->get_lines();
            $code = substr($rply,0,3);

            if($this->do_debug >= 2) {
                echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
            }

            if($code != 250) {
                $this->error =
                    array("error" => "SAML not accepted from server",
                          "smtp_code" => $code,
                          "smtp_msg" => substr($rply,4));
                if($this->do_debug >= 1) {
                    echo "SMTP -> ERROR: " . $this->error["error"] .
                             ": " . $rply . $this->CRLF;
                }
                return false;
            }
            return true;
        }

        /*
         * SendOrMail($from)
         *
         * Starts a mail transaction from the email address specified in
         * $from. Returns true if successful or false otherwise. If True
         * the mail transaction is started and then one or more Recipient
         * commands may be called followed by a Data command. This command
         * will send the message to the users terminal if they are logged
         * in or mail it to them if they are not.
         *
         * Implements rfc 821: SOML <SP> FROM:<reverse-path> <CRLF>
         *
         * SMTP CODE SUCCESS: 250
         * SMTP CODE SUCCESS: 552,451,452
         * SMTP CODE SUCCESS: 500,501,502,421
         */
        function SendOrMail($from) {
            $this->error = null; # so no confusion is caused

            if(!$this->connected()) {
                $this->error = array(
                    "error" => "Called SendOrMail() without being connected");
                return false;
            }

            fputs($this->smtp_conn,"SOML FROM:" . $from . $this->CRLF);

            $rply = $this->get_lines();
            $code = substr($rply,0,3);

            if($this->do_debug >= 2) {
                echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
            }

            if($code != 250) {
                $this->error =
                    array("error" => "SOML not accepted from server",
                          "smtp_code" => $code,
                          "smtp_msg" => substr($rply,4));
                if($this->do_debug >= 1) {
                    echo "SMTP -> ERROR: " . $this->error["error"] .
                             ": " . $rply . $this->CRLF;
                }
                return false;
            }
            return true;
        }

        /*
         * Turn()
         *
         * This is an optional command for SMTP that this class does not
         * support. This method is here to make the RFC821 Definition
         * complete for this class and __may__ be implimented in the future
         *
         * Implements from rfc 821: TURN <CRLF>
         *
         * SMTP CODE SUCCESS: 250
         * SMTP CODE FAILURE: 502
         * SMTP CODE ERROR  : 500, 503
         */
        function Turn() {
            $this->error = array("error" => "This method, TURN, of the SMTP ".
                                            "is not implemented");
            if($this->do_debug >= 1) {
                echo "SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF;
            }
            return false;
        }

        /*
         * Verify($name)
         *
         * Verifies that the name is recognized by the server.
         * Returns false if the name could not be verified otherwise
         * the response from the server is returned.
         *
         * Implements rfc 821: VRFY <SP> <string> <CRLF>
         *
         * SMTP CODE SUCCESS: 250,251
         * SMTP CODE FAILURE: 550,551,553
         * SMTP CODE ERROR  : 500,501,502,421
         */
        function Verify($name) {
            $this->error = null; # so no confusion is caused

            if(!$this->connected()) {
                $this->error = array(
                        "error" => "Called Verify() without being connected");
                return false;
            }

            fputs($this->smtp_conn,"VRFY " . $name . $this->CRLF);

            $rply = $this->get_lines();
            $code = substr($rply,0,3);

            if($this->do_debug >= 2) {
                echo "SMTP -> FROM SERVER:" . $this->CRLF . $rply;
            }

            if($code != 250 && $code != 251) {
                $this->error =
                    array("error" => "VRFY failed on name '$name'",
                          "smtp_code" => $code,
                          "smtp_msg" => substr($rply,4));
                if($this->do_debug >= 1) {
                    echo "SMTP -> ERROR: " . $this->error["error"] .
                             ": " . $rply . $this->CRLF;
                }
                return false;
            }
            return $rply;
        }

        /******************************************************************
         *                       INTERNAL FUNCTIONS                       *
         ******************************************************************/

        /*
         * get_lines()
         *
         * __internal_use_only__: read in as many lines as possible
         * either before eof or socket timeout occurs on the operation.
         * With SMTP we can tell if we have more lines to read if the
         * 4th character is '-' symbol. If it is a space then we don't
         * need to read anything else.
         */
        function get_lines() {
            $data = "";
            while($str = fgets($this->smtp_conn,515)) {
                if($this->do_debug >= 4) {
                    echo "SMTP -> get_lines(): \$data was \"$data\"" .
                             $this->CRLF;
                    echo "SMTP -> get_lines(): \$str is \"$str\"" .
                             $this->CRLF;
                }
                $data .= $str;
                if($this->do_debug >= 4) {
                    echo "SMTP -> get_lines(): \$data is \"$data\"" . 
$this->CRLF;
                }
                # if the 4th character is a space then we are done reading
                # so just break the loop
                if(substr($str,3,1) == " ") { break; }
            }
            return $data;
        }

    }


 ?>

====================================================
Index: display_messages.php
<?php
   /**
    **  display_messages.php
    **
    **  This contains all messages, including information, error, and just
    **  about any other message you can think of.
    **
    ** $Id: display_messages.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $
    **/

    $display_messages_php = true;

    function error_username_password_incorrect($color) {
      echo '<BR>';
      echo " <TABLE COLS=1 WIDTH=75% NOBORDER BGCOLOR=\"$color[4]\" 
ALIGN=CENTER>";
      echo '   <TR>';
      echo "      <TD BGCOLOR=\"$color[0]\">";
      echo '         <B><CENTER>ERROR</CENTER></B>';
      echo '   </TD></TR><TR><TD>';
      echo '      <CENTER><BR>' . lang("Unknown user or password incorrect.") . 
'<BR><A HREF="login.php" TARGET=_top>' . lang("Click here to try again") . 
'</A>.</CENTER>';
      echo '   </TD></TR>';
      echo '</TABLE>';
      echo '</BODY></HTML>';
    }

    function general_info($motd, $org_logo, $version, $org_name, $color) {
      echo '<BR>';
      echo "<TABLE COLS=1 WIDTH=80% CELLSPACING=0 CELLPADDING=2 NOBORDER 
ALIGN=CENTER><TR><TD BGCOLOR=\"$color[9]\">";
      echo '<TABLE COLS=1 WIDTH=100% CELLSPACING=0 CELLPADDING=3 NOBORDER 
BGCOLOR="#FFFFFF" ALIGN=CENTER>';
      echo '   <TR>';
      echo "      <TD BGCOLOR=\"$color[0]\">";
      echo '         <B><CENTER>';
      printf (lang("Welcome to %1's WebMail system"), $org_name);
      echo '         </CENTER></B>';
      echo '   <TR><TD BGCOLOR="#FFFFFF">';
      echo '      <TABLE COLS=2 WIDTH=90% CELLSPACING=0 CELLPADDING=3 NOBORDER 
align="center">';
      echo '         <TR>';
      echo '            <TD BGCOLOR="#FFFFFF"><CENTER>';
      if (strlen($org_logo) > 3)
         echo "               <IMG SRC=\"$org_logo\">";
      else
         echo "               <B>$org_name</B>";
      echo '         <BR><CENTER>';
      printf (lang("Running SquirrelMail version %1 (c) 1999-2000."), $version);
      echo '            </CENTER><BR>';
      echo '            </CENTER></TD></TR><TR>';
      echo '            <TD BGCOLOR="#FFFFFF">';
      echo "               $motd";
      echo '            </TD>';
      echo '         </TR>';
      echo '      </TABLE>';
      echo '   </TD></TR>';
      echo '</TABLE>';
      echo '</TD></TR></TABLE>';
   }

    function error_message($message, $mailbox, $sort, $startMessage, $color) {
          global $phpgw;
      $urlMailbox = urlencode($mailbox);

      echo '<BR>';
      echo "<TABLE COLS=1 WIDTH=70% NOBORDER BGCOLOR=\"$color[4]\" 
ALIGN=CENTER>";
      echo '   <TR>';
      echo "      <TD BGCOLOR=\"$color[0]\">";
      echo "         <FONT COLOR=\"$color[2]\"><B><CENTER>" . lang("ERROR") . 
'</CENTER></B></FONT>';
      echo '   </TD></TR><TR><TD>';
      echo "      <CENTER><BR>$message<BR>\n";
      echo '      <BR>';
      echo "         <A HREF=\"". 
$phpgw->link("/squirrelmail/index.php","sort=$sort&startMessage=$startMessage&mailbox=$urlMailbox")."\">";
      printf (lang("Click here to return to %1"), $mailbox);
      echo '</A>.';
      echo '   </TD></TR>';
      echo '</TABLE>';
    }

    function plain_error_message($message, $color) {
      echo '<BR>';
      echo "<TABLE COLS=1 WIDTH=70% NOBORDER BGCOLOR=\"$color[4]\" 
ALIGN=CENTER>";
      echo '   <TR>';
      echo "      <TD BGCOLOR=\"$color[0]\">";
      echo "         <FONT COLOR=\"$color[2]\"><B><CENTER>" . lang("ERROR") . 
'</CENTER></B></FONT>';
      echo '   </TD></TR><TR><TD>';
      echo "      <CENTER><BR>$message";
      echo '      </CENTER>';
      echo '   </TD></TR>';
      echo '</TABLE>';
    }
?>

====================================================
Index: date.php
<?php
   /**
    **  date.php
    **
    **  Takes a date and parses it into a usable format.  The form that a
    **  date SHOULD arrive in is:
    **        <Tue,> 29 Jun 1999 09:52:11 -0500 (EDT)
    **  (as specified in RFC 822) -- 'Tue' is optional
    **
    **  $Id: date.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $
    **/

   $date_php = true;

   // corrects a time stamp to be the local time
   function getGMTSeconds($stamp, $gmt) {
      global $invert_time;
      if (($gmt == 'Pacific') || ($gmt == 'PST'))
         $gmt = '-0800';
      else if (($gmt == 'EDT'))
         $gmt = '-0400';
      else if (($gmt == 'Eastern') || ($gmt == 'EST') || ($gmt == 'CDT'))
         $gmt = '-0500';
      else if (($gmt == 'Central') || ($gmt == 'CST') || ($gmt == 'MDT'))
         $gmt = '-0600';
      else if (($gmt == 'Mountain') || ($gmt == 'MST') || ($gmt == 'PDT'))
         $gmt = '-0700';
      else if ($gmt == 'BST')
         $gmt = '+0100';
      else if ($gmt == 'EET')
         $gmt = '+0200';
      else if ($gmt == 'GMT')
         $gmt = '+0000';
      else if ($gmt == 'HKT')
         $gmt = '+0800';
      else if ($gmt == 'IST')
         $gmt = '+0200';
      else if ($gmt == 'JST')
         $gmt = '+0900';
      else if ($gmt == 'MET')
         $gmt = '+0100';
      else if ($gmt == 'MET DST' || $gmt == 'METDST')
         $gmt = '+0200';

      if (substr($gmt, 0, 1) == '-') {
         $neg = true;
         $gmt = substr($gmt, 1, strlen($gmt));
      } else if (substr($gmt, 0, 1) == '+') {
         $neg = false;
         $gmt = substr($gmt, 1, strlen($gmt));
      } else
         $neg = false;

      $gmt = substr($gmt, 0, 2);
      $gmt = $gmt * 3600;
      if ($neg == true)
         $gmt = "-$gmt";
      else
         $gmt = "+$gmt";

      /** now find what the server is at **/
      $current = date('Z', time());
      if ($invert_time)
          $current = - $current;
      $stamp = (int)$stamp - (int)$gmt + (int)$current;

      return $stamp;
   }

   function getLongDateString($stamp) {
      return date('D, F j, Y g:i a', $stamp);
   }

   function getDateString($stamp) {
      global $invert_time;
      $now = time();
      $dateZ = date('Z', $now);
      if ($invert_time)
          $dateZ = - $dateZ;
      $midnight = $now - ($now % 86400) - $dateZ;

      if ($midnight < $stamp) {
         // Today
         return date('g:i a', $stamp);
      } else if ($midnight - (60 * 60 * 24 * 6) < $stamp) {
         // This week
         return date('D, g:i a', $stamp);
      } else {
         // before this week
         return date('M j, Y', $stamp);
      }
   }

   function getTimeStamp($dateParts) {
      /** $dateParts[0] == <day of week>   Mon, Tue, Wed
       ** $dateParts[1] == <day of month>  23
       ** $dateParts[2] == <month>         Jan, Feb, Mar
       ** $dateParts[3] == <year>          1999
       ** $dateParts[4] == <time>          18:54:23 (HH:MM:SS)
       ** $dateParts[5] == <from GMT>      +0100
       ** $dateParts[6] == <zone>          (EDT)
       **
       ** NOTE:  In RFC 822, it states that <day of week> is optional.
       **        In that case, dateParts[0] would be the <day of month>
       **        and everything would be bumped up one.
       **/

      // Simply check to see if the first element in the dateParts
      // array is an integer or not.
      //    Since the day of week is optional, this check is needed.
      //
      //    The old code used eregi('mon|tue|wed|thu|fri|sat|sun',
      //    $dateParts[0], $tmp) to find if the first element was the
      //    day of week or day of month. This is an expensive call
      //    (processing time) to have inside a loop. Doing it this way
      //    saves quite a bit of time for large mailboxes.
      //
      //    It is also quicker to call explode only once rather than
      //    the 3 times it was getting called by calling the functions
      //    getHour, getMinute, and getSecond.
      //
      if (intval(trim($dateParts[0])) > 0) {
         $string = $dateParts[0] . ' ' . $dateParts[1] . ' ' .
                   $dateParts[2] . ' ' . $dateParts[3];
         return getGMTSeconds(strtotime($string), $dateParts[4]);
      }
      $string = $dateParts[0] . ' ' . $dateParts[1] . ' ' .
                $dateParts[2] . ' ' . $dateParts[3] . ' ' . $dateParts[4];
          if (isset($dateParts[5]))
        return getGMTSeconds(strtotime($string), $dateParts[5]);
          else
                return getGMTSeconds(strtotime($string), '');
   }

   // I use this function for profiling. Should never be called in
   // actual versions of squirrelmail released to public.
   function getmicrotime() {
      $mtime = microtime();
      $mtime = explode(' ',$mtime);
      $mtime = $mtime[1] + $mtime[0];
      return ($mtime);
   }
?>

====================================================
Index: class.uicompose.inc.php
<?php
        
/***************************************************************************\
        * phpGroupWare - Squirrelmail                                           
    *
        * http://www.phpgroupware.org                                           
    *
        * http://www.linux-at-work.de                                           
    *
        * Written by : Lars Kneschke address@hidden                   *
        * -------------------------------------------------                     
    *
        * This program is free software; you can redistribute it and/or modify 
it   *
        * under the terms of the GNU General Public License as published by the 
    *
        * Free Software Foundation; either version 2 of the License, or (at 
your    *
        * option) any later version.                                            
    *
        
\***************************************************************************/
        /* $Id: class.uicompose.inc.php,v 1.1 2005/05/05 00:56:40 skwashd Exp $ 
*/

        class uicompose
        {

                var $public_functions = array
                (
                        'compose'       => True,
                        'action'        => True
                );

                function uicompose()
                {
                        if (!isset($GLOBALS['HTTP_POST_VARS']['composeid']) && 
!isset($GLOBALS['HTTP_GET_VARS']['composeid']))
                        {
                                // create new compose session
                                $this->bocompose   = 
CreateObject('squirrelmail.bocompose');
                                $this->composeID = 
$this->bocompose->getComposeID();
                        }
                        else
                        {
                                // reuse existing compose session
                                if 
(isset($GLOBALS['HTTP_POST_VARS']['composeid']))
                                        $this->composeID = 
$GLOBALS['HTTP_POST_VARS']['composeid'];
                                else
                                        $this->composeID = 
$GLOBALS['HTTP_GET_VARS']['composeid'];
                                $this->bocompose   = 
CreateObject('squirrelmail.bocompose',$this->composeID);
                        }

                        $this->t = 
CreateObject('phpgwapi.Template',PHPGW_APP_TPL);

                        $this->t->set_unknowns('remove');

                        $this->rowColor[0] = 
$GLOBALS['phpgw_info']["theme"]["bg01"];
                        $this->rowColor[1] = 
$GLOBALS['phpgw_info']["theme"]["bg02"];


                }

                function action()
                {
                        $formData['to']         = 
$this->bocompose->stripSlashes($GLOBALS['HTTP_POST_VARS']['to']);
                        $formData['cc']         = 
$this->bocompose->stripSlashes($GLOBALS['HTTP_POST_VARS']['cc']);
                        $formData['bcc']        = 
$this->bocompose->stripSlashes($GLOBALS['HTTP_POST_VARS']['bcc']);
                        $formData['reply_to']   = 
$this->bocompose->stripSlashes($GLOBALS['HTTP_POST_VARS']['reply_to']);
                        $formData['subject']    = 
$this->bocompose->stripSlashes($GLOBALS['HTTP_POST_VARS']['subject']);
                        $formData['body']       = 
$this->bocompose->stripSlashes($GLOBALS['HTTP_POST_VARS']['body']);
                        $formData['priority']   = 
$this->bocompose->stripSlashes($GLOBALS['HTTP_POST_VARS']['priority']);
                        $formData['signature']  = 
$this->bocompose->stripSlashes($GLOBALS['HTTP_POST_VARS']['signature']);

                        if (isset($GLOBALS['HTTP_POST_VARS']['send']))
                        {
                                $action="send";
                        }
                        elseif (isset($GLOBALS['HTTP_POST_VARS']['addfile']))
                        {
                                $action="addfile";
                        }
                        elseif (isset($GLOBALS['HTTP_POST_VARS']['removefile']))
                        {
                                $action="removefile";
                        }

                        switch ($action)
                        {
                                case "addfile":
                                        $formData['name']       = 
$GLOBALS['HTTP_POST_FILES']['attachfile']['name'];
                                        $formData['type']       = 
$GLOBALS['HTTP_POST_FILES']['attachfile']['type'];
                                        $formData['file']       = 
$GLOBALS['HTTP_POST_FILES']['attachfile']['tmp_name'];
                                        $formData['size']       = 
$GLOBALS['HTTP_POST_FILES']['attachfile']['size'];
                                        
$this->bocompose->addAttachment($formData);
                                        $this->compose();
                                        break;

                                case "removefile":
                                        $formData['removeAttachments']  = 
$GLOBALS['HTTP_POST_VARS']['attachment'];
                                        
$this->bocompose->removeAttachment($formData);
                                        $this->compose();
                                        break;

                                case "send":
                                        $this->bocompose->send($formData);
                                        $linkData = array
                                        (
                                                'mailbox'       => 
$GLOBALS['HTTP_GET_VARS']['mailbox'],
                                                'startMessage'  => '1'
                                        );
                                        $link = 
$GLOBALS['phpgw']->link('/squirrelmail/index.php',$linkData);
                                        $GLOBALS['phpgw']->redirect($link);
                                        $GLOBALS['phpgw']->common->phpgw_exit();
                                        break;
                        }
                }

                function compose()
                {
                        // read the data from session
                        // all values are empty for a new compose window
                        $sessionData = $this->bocompose->getSessionData();

                        // is the to address set already?
                        if (!empty($GLOBALS['HTTP_GET_VARS']['send_to']))
                        {
                                $sessionData['to'] = 
urldecode($GLOBALS['HTTP_GET_VARS']['send_to']);
                        }

                        $this->display_app_header();

                        $this->t->set_file(array("composeForm" => 
"composeForm.tpl"));
                        $this->t->set_block('composeForm','header','header');
                        $this->t->set_block('composeForm','body_input');
                        
$this->t->set_block('composeForm','attachment','attachment');
                        
$this->t->set_block('composeForm','attachment_row','attachment_row');
                        
$this->t->set_block('composeForm','attachment_row_bold');

                        $this->translate();

                        $linkData = array
                        (
                                'mailbox'       => 
$GLOBALS['HTTP_GET_VARS']['mailbox'],
                                'startMessage'  => '1'
                        );
                        
$this->t->set_var("link_message_list",$GLOBALS['phpgw']->link('/squirrelmail/index.php',$linkData));

                        $linkData = array
                        (
                                'menuaction'    => 
'squirrelmail.uicompose.action',
                                'composeid'     => $this->composeID,
                                'mailbox'       => 
$GLOBALS['HTTP_GET_VARS']['mailbox'],
                                'startMessage'  => '1'
                        );
                        
$this->t->set_var("link_action",$GLOBALS['phpgw']->link('/index.php',$linkData));
                        
$this->t->set_var('folder_name',$GLOBALS['HTTP_GET_VARS']['mailbox']);

                        // header
                        $this->t->set_var("to",$sessionData['to']);
                        $this->t->set_var("cc",$sessionData['cc']);
                        $this->t->set_var("bcc",$sessionData['bcc']);
                        $this->t->set_var("reply_to",$sessionData['reply_to']);
                        $this->t->set_var("subject",$sessionData['subject']);
                        $this->t->pparse("out","header");

                        // body
                        $this->t->set_var("body",$sessionData['body']);
                        
$this->t->set_var("signature",$sessionData['signature']);
                        $this->t->pparse("out","body_input");

                        // attachments
                        if (is_array($sessionData['attachments']) && 
count($sessionData['attachments']) > 0)
                        {
                                
$this->t->set_var('row_color',$this->rowColor[0]);
                                $this->t->set_var('name',lang('name'));
                                $this->t->set_var('type',lang('type'));
                                $this->t->set_var('size',lang('size'));
                                
$this->t->parse('attachment_rows','attachment_row_bold',True);
                                while (list($key,$value) = 
each($sessionData['attachments']))
                                {
                                        #print "$key : $value<br>";
                                        
$this->t->set_var('row_color',$this->rowColor[($key+1)%2]);
                                        
$this->t->set_var('name',$value['name']);
                                        
$this->t->set_var('type',$value['type']);
                                        
$this->t->set_var('size',$value['size']);
                                        
$this->t->set_var('attachment_number',$key);
                                        
$this->t->parse('attachment_rows','attachment_row',True);
                                }
                        }
                        else
                        {
                                $this->t->set_var('attachment_rows','');
                        }

                        $this->t->pparse("out","attachment");
                }

                function display_app_header()
                {
                        $GLOBALS['phpgw']->common->phpgw_header();
                        echo parse_navbar();
                }

                function reply()
                {
                        // is the to address set already?
                        if (!empty($GLOBALS['HTTP_GET_VARS']['reply_id']))
                        {
                                $formData['to']         = 
urldecode($GLOBALS['HTTP_GET_VARS']['send_to']);
                                $formData['subject']    = 
urldecode($GLOBALS['HTTP_GET_VARS']['reply_subj']);
                        }

                        $this->compose();
                }

                function translate()
                {
                        $this->t->set_var("lang_message_list",lang('Message 
List'));
                        $this->t->set_var("lang_to",lang('to'));
                        $this->t->set_var("lang_cc",lang('cc'));
                        $this->t->set_var("lang_bcc",lang('bcc'));
                        $this->t->set_var("lang_reply_to",lang('reply to'));
                        $this->t->set_var("lang_subject",lang('subject'));
                        
$this->t->set_var("lang_addressbook",lang('addressbook'));
                        $this->t->set_var("lang_send",lang('send'));
                        $this->t->set_var("lang_back_to_folder",lang('back to 
folder'));
                        
$this->t->set_var("lang_attachments",lang('attachments'));
                        $this->t->set_var("lang_add",lang('add'));
                        $this->t->set_var("lang_remove",lang('remove'));
                        $this->t->set_var("lang_priority",lang('priority'));
                        $this->t->set_var("lang_normal",lang('normal'));
                        $this->t->set_var("lang_high",lang('high'));
                        $this->t->set_var("lang_low",lang('low'));
                        $this->t->set_var("lang_signature",lang('signature'));

                        
$this->t->set_var("th_bg",$GLOBALS['phpgw_info']["theme"]["th_bg"]);
                        
$this->t->set_var("bg01",$GLOBALS['phpgw_info']["theme"]["bg01"]);
                        
$this->t->set_var("bg02",$GLOBALS['phpgw_info']["theme"]["bg02"]);
                        
$this->t->set_var("bg03",$GLOBALS['phpgw_info']["theme"]["bg03"]);
                }
}






reply via email to

[Prev in Thread] Current Thread [Next in Thread]