From f7652eeb07a1c1f6a9616e2af1577bda47359a8e Mon Sep 17 00:00:00 2001 From: Klaus Leithoff Date: Tue, 7 Sep 2010 09:14:14 +0000 Subject: [PATCH] rework of bofelamimail::_strtotime, to make propper use of egw_time; performance issue: limit the number of links and email to be parsed (and adapted) to 100 each, as it should be sufficient for most standard emails; try to further improve the display of textmails; backport of bofelamimails version of wordwrap from trunk (allow to skip lines that start with ) --- felamimail/inc/class.bocompose.inc.php | 1146 ++++++++++++++ felamimail/inc/class.bofelamimail.inc.php | 32 +- felamimail/inc/class.uidisplay.inc.php | 1649 +++++++++++++++++++++ felamimail/inc/class.uiwidgets.inc.php | 1019 +++++++++++++ 4 files changed, 3836 insertions(+), 10 deletions(-) create mode 100644 felamimail/inc/class.bocompose.inc.php create mode 100644 felamimail/inc/class.uidisplay.inc.php create mode 100644 felamimail/inc/class.uiwidgets.inc.php diff --git a/felamimail/inc/class.bocompose.inc.php b/felamimail/inc/class.bocompose.inc.php new file mode 100644 index 0000000000..45125abf4d --- /dev/null +++ b/felamimail/inc/class.bocompose.inc.php @@ -0,0 +1,1146 @@ + True, + 'action' => True + ); + + var $attachments; // Array of attachments + var $preferences; // the prefenrences(emailserver, username, ...) + var $preferencesArray; + var $bofelamimail; + var $bopreferences; + var $bosignatures; + var $displayCharset; + + function bocompose($_composeID = '', $_charSet = 'iso-8859-1') + { + $this->displayCharset = strtolower($_charSet); + $this->bosignatures = CreateObject('felamimail.felamimail_bosignatures'); + $this->bofelamimail = CreateObject('felamimail.bofelamimail',$this->displayCharset); + $this->bopreferences =& $this->bofelamimail->bopreferences; + $this->preferences = $this->bopreferences->getPreferences(); + $this->preferencesArray =& $GLOBALS['egw_info']['user']['preferences']['felamimail']; + //force the default for the forwarding -> asmail + if (is_array($this->preferencesArray)) { + if (!array_key_exists('message_forwarding',$this->preferencesArray) + || !isset($this->preferencesArray['message_forwarding']) + || empty($this->preferencesArray['message_forwarding'])) $this->preferencesArray['message_forwarding'] = 'asmail'; + } else { + $this->preferencesArray['message_forwarding'] = 'asmail'; + } + // check if there is a composeid set, and restore the session, if so + if (!empty($_composeID)) + { + $this->composeID = $_composeID; + $this->restoreSessionData(); + } + else // new email + { + $this->setDefaults(); + } + } + + /** + * adds uploaded files or files in eGW's temp directory as attachments + * + * It also stores the given data in the session + * + * @param array $_formData fields of the compose form (to,cc,bcc,reply_to,subject,body,priority,signature), plus data of the file (name,file,size,type) + */ + function addAttachment($_formData) + { +#echo "addattachment
"; +#_debug_array($_formData); + // to gard against exploits the file must be either uploaded or be in the temp_dir + if ($_formData['size'] != 0 && (is_uploaded_file($_formData['file']) || + realpath(dirname($_formData['file'])) == realpath($GLOBALS['egw_info']['server']['temp_dir'])) || + parse_url($_formData['file'],PHP_URL_SCHEME) == 'vfs') + { + // ensure existance of eGW 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['egw_info']['server']['temp_dir'])) + { + @mkdir($GLOBALS['egw_info']['server']['temp_dir'],0700); + } + + // if we were NOT able to create this temp directory, then make an ERROR report + if (!file_exists($GLOBALS['egw_info']['server']['temp_dir'])) + { + $alert_msg .= 'Error:'.'
' + .'Server is unable to access phpgw tmp directory'.'
' + .$GLOBALS['egw_info']['server']['temp_dir'].'
' + .'Please check your configuration'.'
' + .'
'; + } + + // 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['egw_info']['server']['temp_dir']. + SEP. + md5(time().$GLOBALS['egw_info']['user']['account_id'].$this->composeID.basename($_formData['file'])); + + if (parse_url($_formData['file'],PHP_URL_SCHEME) == 'vfs') + { + $tmpFileName = $_formData['file']; // no need to store it somewhere + } + elseif (is_uploaded_file($_formData['file'])) + { + //error_log(__METHOD__." Uploaded File:".$_formData['file']." with filesize:".filesize($_formData['file'])); + move_uploaded_file($_formData['file'],$tmpFileName); // requirement for safe_mode! + //error_log(__METHOD__." copy to :".$tmpFileName." with filesize:".filesize($tmpFileName)); + } + else + { + rename($_formData['file'],$tmpFileName); + } + //$attachmentID = $this->getRandomString(); + //error_log(__METHOD__." add Attachment with ID (random String):".$attachmentID); + $buffer = array( + 'name' => $_formData['name'], + 'type' => $_formData['type'], + 'file' => $tmpFileName, + 'size' => $_formData['size'] + ); + // trying diiferent ID-ing Method, as getRandomString seems to produce non Random String on certain systems. + $attachmentID = md5(time().serialize($buffer)); + //error_log(__METHOD__." add Attachment with ID:".$attachmentID." (md5 of serialized array)"); + $this->sessionData['attachments'][$attachmentID] = $buffer; + unset($buffer); + } + + $this->saveSessionData(); + #print"
";
+			#error_log(print_r($this->sessionData,true));
+			#print"
";exit; + } + + function addMessageAttachment($_uid, $_partID, $_folder, $_name, $_type, $_size) + { + $this->sessionData['attachments'][]=array ( + 'uid' => $_uid, + 'partID' => $_partID, + 'name' => $_name, + 'type' => $_type, + 'size' => $_size, + 'folder' => $_folder + ); + $this->saveSessionData(); + } + + /** + * replace emailaddresses eclosed in <> (eg.: ) with the emailaddress only (e.g: me@you.de) + * always returns 1 + */ + static function replaceEmailAdresses(&$text) + { + // replace emailaddresses eclosed in <> (eg.: ) with the emailaddress only (e.g: me@you.de) + bofelamimail::replaceEmailAdresses($text); + return 1; + } + + function convertHTMLToText(&$_html,$sourceishtml = true) + { + $stripalltags = true; + // third param is stripalltags, we may not need that, if the source is already in ascii + if (!$sourceishtml) $stripalltags=false; + return bofelamimail::convertHTMLToText($_html,false,$stripalltags); + } + + function convertHTMLToTextTiny($_html) + { + print "
"; print htmlspecialchars($_html); print "
"; + // remove these tags and any spaces behind the tags + $search = array('/ */', '/<.?strong>/', '/<.?em>/', '/<.?u>/', '/<.?ul> */', '/<.?ol> */', '/<.?font.*?> */', '/<.?blockquote> */'); + $replace = ''; + $text = preg_replace($search, $replace, $_html); + + // convert these tags and any spaces behind the tags to line breaks + $search = array('/<\/li> */', '/
*/'); + $replace = "\r\n"; + $text = preg_replace($search, $replace, $text); + + // convert these tags and any spaces behind the tags to double line breaks + $search = array('/ <\/p> */', '/<\/p> */'); + $replace = "\r\n\r\n"; + $text = preg_replace($search, $replace, $text); + + // special replacements + $search = array('/
  • /'); + $replace = array(' * '); + + $text = preg_replace($search, $replace, $text); + + $text = html_entity_decode($text, ENT_COMPAT, $this->displayCharset); + + print "
    "; print htmlspecialchars($text); print "
    "; exit; + + return $text; + } + + function generateRFC822Address($_addressObject) + { + if(!empty($_addressObject->personal) && !empty($_addressObject->mailbox) && !empty($_addressObject->host)) { + return sprintf('"%s" <%s@%s>', $this->bofelamimail->decode_header($_addressObject->personal), $_addressObject->mailbox, $_addressObject->host); + } elseif(!empty($_addressObject->mailbox) && !empty($_addressObject->host)) { + return sprintf("%s@%s", $_addressObject->mailbox, $_addressObject->host); + } else { + return $_addressObject->mailbox; + } + } + + // create a hopefully unique id, to keep track of different compose windows + // if you do this, you are creating a new email + function getComposeID() + { + $this->composeID = $this->getRandomString(); + + $this->setDefaults(); + + return $this->composeID; + } + + // $_mode can be: + // single: for a reply to one address + // all: for a reply to all + function getDraftData($_icServer, $_folder, $_uid, $_partID=NULL) + { + $this->sessionData['to'] = array(); + + $bofelamimail =& $this->bofelamimail; //CreateObject('felamimail.bofelamimail',$this->displayCharset); + $bofelamimail->openConnection(); + $bofelamimail->reopen($_folder); + + $userEMailAddresses = $this->preferences->getUserEMailAddresses(); + + // get message headers for specified message + #$headers = $bofelamimail->getMessageHeader($_folder, $_uid); + $headers = $bofelamimail->getMessageEnvelope($_uid, $_partID); + $addHeadInfo = $bofelamimail->getMessageHeader($_uid, $_partID); + if (!empty($addHeadInfo['X-MAILFOLDER'])) { + foreach ( explode('|',$addHeadInfo['X-MAILFOLDER']) as $val ) { + $this->sessionData['folder'][] = $val; + } + } + if (!empty($addHeadInfo['X-SIGNATURE'])) { + $this->sessionData['signatureID'] = $addHeadInfo['X-SIGNATURE']; + } + if (!empty($addHeadInfo['X-STATIONERY'])) { + $this->sessionData['stationeryID'] = $addHeadInfo['X-STATIONERY']; + } + if (!empty($addHeadInfo['X-IDENTITY'])) { + $this->sessionData['identity'] = $addHeadInfo['X-IDENTITY']; + } + $this->sessionData['uid'] = $_uid; + $this->sessionData['messageFolder'] = $_folder; + $this->sessionData['isDraft'] = true; + foreach((array)$headers['CC'] as $val) { + if($val['MAILBOX_NAME'] == 'undisclosed-recipients' || (empty($val['MAILBOX_NAME']) && empty($val['HOST_NAME'])) ) { + continue; + } + + if($userEMailAddresses[$val['EMAIL']]) { + continue; + } + + if(!$foundAddresses[$val['EMAIL']]) { + $address = $val['PERSONAL_NAME'] != 'NIL' ? $val['RFC822_EMAIL'] : $val['EMAIL']; + $address = $this->bofelamimail->decode_header($address); + $this->sessionData['cc'][] = $address; + $foundAddresses[$val['EMAIL']] = true; + } + } + + foreach((array)$headers['TO'] as $val) { + if($val['MAILBOX_NAME'] == 'undisclosed-recipients' || (empty($val['MAILBOX_NAME']) && empty($val['HOST_NAME'])) ) { + continue; + } + + if($userEMailAddresses[$val['EMAIL']]) { + continue; + } + + if(!$foundAddresses[$val['EMAIL']]) { + $address = $val['PERSONAL_NAME'] != 'NIL' ? $val['RFC822_EMAIL'] : $val['EMAIL']; + $address = $this->bofelamimail->decode_header($address); + $this->sessionData['to'][] = $address; + $foundAddresses[$val['EMAIL']] = true; + } + } + + foreach((array)$headers['REPLY_TO'] as $val) { + if($val['MAILBOX_NAME'] == 'undisclosed-recipients' || (empty($val['MAILBOX_NAME']) && empty($val['HOST_NAME'])) ) { + continue; + } + + if($userEMailAddresses[$val['EMAIL']]) { + continue; + } + + if(!$foundAddresses[$val['EMAIL']]) { + $address = $val['PERSONAL_NAME'] != 'NIL' ? $val['RFC822_EMAIL'] : $val['EMAIL']; + $address = $this->bofelamimail->decode_header($address); + $this->sessionData['replyto'][] = $address; + $foundAddresses[$val['EMAIL']] = true; + } + } + + foreach((array)$headers['BCC'] as $val) { + if($val['MAILBOX_NAME'] == 'undisclosed-recipients' || (empty($val['MAILBOX_NAME']) && empty($val['HOST_NAME'])) ) { + continue; + } + + if($userEMailAddresses[$val['EMAIL']]) { + continue; + } + + if(!$foundAddresses[$val['EMAIL']]) { + $address = $val['PERSONAL_NAME'] != 'NIL' ? $val['RFC822_EMAIL'] : $val['EMAIL']; + $address = $this->bofelamimail->decode_header($address); + $this->sessionData['bcc'][] = $address; + $foundAddresses[$val['EMAIL']] = true; + } + } + + $this->sessionData['subject'] = $bofelamimail->decode_header($headers['SUBJECT']); + // remove a printview tag if composing + $searchfor = '/^\['.lang('printview').':\]/'; + $this->sessionData['subject'] = preg_replace($searchfor,'',$this->sessionData['subject']); + $bodyParts = $bofelamimail->getMessageBody($_uid, $this->preferencesArray['always_display'], $_partID); + #_debug_array($bodyParts); + + #$fromAddress = ($headers['FROM'][0]['PERSONAL_NAME'] != 'NIL') ? $headers['FROM'][0]['RFC822_EMAIL'] : $headers['FROM'][0]['EMAIL']; + if($bodyParts['0']['mimeType'] == 'text/html') { + $this->sessionData['mimeType'] = 'html'; + + for($i=0; $i0) { + $this->sessionData['body'] .= '
    '; + } + if($bodyParts[$i]['mimeType'] == 'text/plain') { + #$bodyParts[$i]['body'] = nl2br($bodyParts[$i]['body']); + $bodyParts[$i]['body'] = "
    ".$bodyParts[$i]['body']."
    "; + } + $bodyParts[$i]['body'] = $GLOBALS['egw']->translation->convert($bodyParts[$i]['body'], $bodyParts[$i]['charSet']); + #error_log( "GetDraftData (HTML) CharSet:".mb_detect_encoding($bodyParts[$i]['body'] . 'a' , strtoupper($bodyParts[$i]['charSet']).','.strtoupper($this->displayCharset).',UTF-8, ISO-8859-1')); + $this->sessionData['body'] .= "
    ". $bodyParts[$i]['body'] ; + } + + } else { + $this->sessionData['mimeType'] = 'plain'; + + for($i=0; $i0) { + $this->sessionData['body'] .= "
    "; + } + $bodyParts[$i]['body'] = $GLOBALS['egw']->translation->convert($bodyParts[$i]['body'], $bodyParts[$i]['charSet']); + #error_log( "GetDraftData (Plain) CharSet".mb_detect_encoding($bodyParts[$i]['body'] . 'a' , strtoupper($bodyParts[$i]['charSet']).','.strtoupper($this->displayCharset).',UTF-8, ISO-8859-1')); + $this->sessionData['body'] .= "\r\n". $bodyParts[$i]['body'] ; + } + } + + if($attachments = $bofelamimail->getMessageAttachments($_uid,$_partID)) { + foreach($attachments as $attachment) { + $this->addMessageAttachment($_uid, $attachment['partID'], + $_folder, + $attachment['name'], + $attachment['mimeType'], + $attachment['size']); + } + } + $bofelamimail->closeConnection(); + + $this->saveSessionData(); + } + + function getErrorInfo() + { + if(isset($this->errorInfo)) { + $errorInfo = $this->errorInfo; + unset($this->errorInfo); + return $errorInfo; + } + return false; + } + + function getForwardData($_icServer, $_folder, $_uid, $_partID) + { + if ($this->preferencesArray['message_forwarding'] == 'inline') { + $this->getReplyData('forward', $_icServer, $_folder, $_uid, $_partID); + } + $bofelamimail =& $this->bofelamimail; //CreateObject('felamimail.bofelamimail',$this->displayCharset); + $bofelamimail->openConnection(); + $bofelamimail->reopen($_folder); + + // get message headers for specified message + $headers = $bofelamimail->getMessageEnvelope($_uid, $_partID); + + #_debug_array($headers); exit; + // check for Re: in subject header + $this->sessionData['subject'] = "[FWD] " . $bofelamimail->decode_header($headers['SUBJECT']); + $this->sessionData['sourceFolder']=$_folder; + $this->sessionData['forwardFlag']='forwarded'; + $this->sessionData['forwardedUID']=$_uid; + if ($this->preferencesArray['message_forwarding'] == 'asmail') { + $this->sessionData['mimeType'] = $this->preferencesArray['composeOptions']; + if($headers['SIZE']) + $size = $headers['SIZE']; + else + $size = lang('unknown'); + + $this->addMessageAttachment($_uid, $_partID, $_folder, + $bofelamimail->decode_header($headers['SUBJECT']), + 'MESSAGE/RFC822', $size); + } + else + { + unset($this->sessionData['in-reply-to']); + unset($this->sessionData['to']); + unset($this->sessionData['cc']); + if($attachments = $bofelamimail->getMessageAttachments($_uid,$_partID)) { + foreach($attachments as $attachment) { + $this->addMessageAttachment($_uid, $attachment['partID'], + $_folder, + $attachment['name'], + $attachment['mimeType'], + $attachment['size']); + } + } + } + $bofelamimail->closeConnection(); + + $this->saveSessionData(); + } + + function getRandomString() { + mt_srand((float) microtime() * 1000000); + return md5(mt_rand (100000, 999999)); + } + + // $_mode can be: + // single: for a reply to one address + // all: for a reply to all + // forward: inlineforwarding of a message with its attachments + function getReplyData($_mode, $_icServer, $_folder, $_uid, $_partID) + { + $foundAddresses = array(); + + $bofelamimail =& $this->bofelamimail; //CreateObject('felamimail.bofelamimail',$this->displayCharset); + $bofelamimail->openConnection(); + $bofelamimail->reopen($_folder); + + $userEMailAddresses = $this->preferences->getUserEMailAddresses(); + + // get message headers for specified message + #print "AAAA: $_folder, $_uid, $_partID
    "; + $headers = $bofelamimail->getMessageEnvelope($_uid, $_partID); + #$headers = $bofelamimail->getMessageHeader($_uid, $_partID); + $this->sessionData['uid'] = $_uid; + $this->sessionData['messageFolder'] = $_folder; + $this->sessionData['in-reply-to'] = $headers['MESSAGE_ID']; + + // check for Reply-To: header and use if available + if(!empty($headers['REPLY_TO']) && ($headers['REPLY_TO'] != $headers['FROM'])) { + foreach($headers['REPLY_TO'] as $val) { + if($val['EMAIL'] == 'NIL') { + continue; + } + + if(!$foundAddresses[$val['EMAIL']]) { + $address = $val['PERSONAL_NAME'] != 'NIL' ? $val['RFC822_EMAIL'] : $val['EMAIL']; + $address = $this->bofelamimail->decode_header($address); + $oldTo[] = $address; + $foundAddresses[$val['EMAIL']] = true; + } + } + $oldToAddress = $headers['REPLY_TO'][0]['EMAIL']; + } else { + foreach($headers['FROM'] as $val) { + if($val['EMAIL'] == 'NIL') { + continue; + } + if(!$foundAddresses[$val['EMAIL']]) { + $address = $val['PERSONAL_NAME'] != 'NIL' ? $val['RFC822_EMAIL'] : $val['EMAIL']; + $address = $this->bofelamimail->decode_header($address); + $oldTo[] = $address; + $foundAddresses[$val['EMAIL']] = true; + } + } + $oldToAddress = $headers['REPLY_TO'][0]['EMAIL']; + } + + if($_mode != 'all' || ($_mode == 'all' && !$userEMailAddresses[$oldToAddress]) ) { + $this->sessionData['to'] = $oldTo; + } + + if($_mode == 'all') { + // reply to any address which is cc, but not to my self + #if($headers->cc) { + foreach($headers['CC'] as $val) { + if($val['MAILBOX_NAME'] == 'undisclosed-recipients' || (empty($val['MAILBOX_NAME']) && empty($val['HOST_NAME'])) ) { + continue; + } + + if($userEMailAddresses[$val['EMAIL']]) { + continue; + } + + if(!$foundAddresses[$val['EMAIL']]) { + $address = $val['PERSONAL_NAME'] != 'NIL' ? $val['RFC822_EMAIL'] : $val['EMAIL']; + $address = $this->bofelamimail->decode_header($address); + $this->sessionData['cc'][] = $address; + $foundAddresses[$val['EMAIL']] = true; + } + } + #} + + // reply to any address which is to, but not to my self + #if($headers->to) { + foreach($headers['TO'] as $val) { + if($val['MAILBOX_NAME'] == 'undisclosed-recipients' || (empty($val['MAILBOX_NAME']) && empty($val['HOST_NAME'])) ) { + continue; + } + + if($userEMailAddresses[$val['EMAIL']]) { + continue; + } + + if(!$foundAddresses[$val['EMAIL']]) { + $address = $val['PERSONAL_NAME'] != 'NIL' ? $val['RFC822_EMAIL'] : $val['EMAIL']; + $address = $this->bofelamimail->decode_header($address); + $this->sessionData['to'][] = $address; + $foundAddresses[$val['EMAIL']] = true; + } + } + #} + + #if($headers->from) { + foreach($headers['FROM'] as $val) { + if($val['MAILBOX_NAME'] == 'undisclosed-recipients' || (empty($val['MAILBOX_NAME']) && empty($val['HOST_NAME'])) ) { + continue; + } + + if($userEMailAddresses[$val['EMAIL']]) { + continue; + } + + if(!$foundAddresses[$val['EMAIL']]) { + $address = $val['PERSONAL_NAME'] != 'NIL' ? $val['RFC822_EMAIL'] : $val['EMAIL']; + $address = $this->bofelamimail->decode_header($address); + $this->sessionData['to'][] = $address; + $foundAddresses[$val['EMAIL']] = true; + } + } + #} + } + + // check for Re: in subject header + if(strtolower(substr(trim($bofelamimail->decode_header($headers['SUBJECT'])), 0, 3)) == "re:") { + $this->sessionData['subject'] = $bofelamimail->decode_header($headers['SUBJECT']); + } else { + $this->sessionData['subject'] = "Re: " . $bofelamimail->decode_header($headers['SUBJECT']); + } + + //_debug_array($headers); + $bodyParts = $bofelamimail->getMessageBody($_uid, $this->preferencesArray['always_display'], $_partID); + //_debug_array($bodyParts); + + $fromAddress = ($headers['FROM'][0]['PERSONAL_NAME'] != 'NIL') ? $headers['FROM'][0]['RFC822_EMAIL'] : $headers['FROM'][0]['EMAIL']; + $toAddressA = array(); + $toAddress = ''; + foreach ($headers['TO'] as $mailheader) { + $toAddressA[] = ($mailheader['PERSONAL_NAME'] != 'NIL') ? $mailheader['RFC822_EMAIL'] : $mailheader['EMAIL']; + } + if (count($toAddressA)>0) $toAddress = @htmlspecialchars(lang("to").": ".$bofelamimail->decode_header(implode(', ', $toAddressA)),ENT_QUOTES).($bodyParts['0']['mimeType'] == 'text/html'?"\r\n
    ":"\r\n"); + $ccAddressA = array(); + $ccAddress = ''; + foreach ($headers['CC'] as $mailheader) { + $ccAddressA[] = ($mailheader['PERSONAL_NAME'] != 'NIL') ? $mailheader['RFC822_EMAIL'] : $mailheader['EMAIL']; + } + if (count($ccAddressA)>0) $ccAddress = @htmlspecialchars(lang("cc").": ".$bofelamimail->decode_header(implode(', ', $ccAddressA)),ENT_QUOTES).($bodyParts['0']['mimeType'] == 'text/html'?"\r\n
    ":"\r\n"); + if($bodyParts['0']['mimeType'] == 'text/html') { + $this->sessionData['body'] = "
     \r\n

    ".'----------------'.lang("original message").'-----------------'."\r\n".'
    '. + @htmlspecialchars(lang("from").": ".$bofelamimail->decode_header($fromAddress),ENT_QUOTES)."\r\n
    ". + $toAddress.$ccAddress. + @htmlspecialchars(lang("date").": ".$headers['DATE'],ENT_QUOTES)."\r\n
    ". + '----------------------------------------------------------'."\r\n

    "; + $this->sessionData['mimeType'] = 'html'; + $this->sessionData['body'] .= '
    '; + + for($i=0; $i0) { + $this->sessionData['body'] .= '
    '; + } + if($bodyParts[$i]['mimeType'] == 'text/plain') { + #$bodyParts[$i]['body'] = nl2br($bodyParts[$i]['body'])."
    "; + $bodyParts[$i]['body'] = "
    ".$bodyParts[$i]['body']."
    "; + } + $this->sessionData['body'] .= "
    ".self::_getCleanHTML($GLOBALS['egw']->translation->convert($bodyParts[$i]['body'], $bodyParts[$i]['charSet'])); + #error_log( "GetReplyData (HTML) CharSet:".mb_detect_encoding($bodyParts[$i]['body'] . 'a' , strtoupper($bodyParts[$i]['charSet']).','.strtoupper($this->displayCharset).',UTF-8, ISO-8859-1')); + + } + + $this->sessionData['body'] .= '

    '; + } else { + #$this->sessionData['body'] = @htmlspecialchars(lang("on")." ".$headers['DATE']." ".$bofelamimail->decode_header($fromAddress), ENT_QUOTES) . " ".lang("wrote").":\r\n"; + $this->sessionData['body'] = " \r\n \r\n".'----------------'.lang("original message").'-----------------'."\r\n". + @htmlspecialchars(lang("from").": ".$bofelamimail->decode_header($fromAddress),ENT_QUOTES)."\r\n". + $toAddress.$ccAddress. + @htmlspecialchars(lang("date").": ".$headers['DATE'], ENT_QUOTES)."\r\n". + '-------------------------------------------------'."\r\n \r\n "; + + $this->sessionData['mimeType'] = 'plain'; + + for($i=0; $i0) { + $this->sessionData['body'] .= "
    "; + } + + // add line breaks to $bodyParts + $newBody = $GLOBALS['egw']->translation->convert($bodyParts[$i]['body'], $bodyParts[$i]['charSet']); + #error_log( "GetReplyData (Plain) CharSet:".mb_detect_encoding($bodyParts[$i]['body'] . 'a' , strtoupper($bodyParts[$i]['charSet']).','.strtoupper($this->displayCharset).',UTF-8, ISO-8859-1')); + + $newBody = explode("\n",$newBody); + $this->sessionData['body'] .= "\r\n"; + // create body new, with good line breaks and indention + foreach($newBody as $value) { + // the explode is removing the character + if (trim($value) != '') { + #if ($value != "\r") $value .= "\n"; + } + $numberOfChars = strspn(trim($value), ">"); + $appendString = str_repeat('>', $numberOfChars + 1); + + $bodyAppend = $this->bofelamimail->wordwrap($value, 76-strlen("\r\n$appendString "), "\r\n$appendString "); + + if($bodyAppend[0] == '>') { + $bodyAppend = '>'. $bodyAppend; + } else { + $bodyAppend = '> '. $bodyAppend; + } + + $this->sessionData['body'] .= $bodyAppend; + } + } + } + + $bofelamimail->closeConnection(); + + $this->saveSessionData(); + } + + static function _getCleanHTML($_body) + { + static $nonDisplayAbleCharacters = array('[\016]','[\017]', + '[\020]','[\021]','[\022]','[\023]','[\024]','[\025]','[\026]','[\027]', + '[\030]','[\031]','[\032]','[\033]','[\034]','[\035]','[\036]','[\037]'); + bofelamimail::getCleanHTML($_body); + $_body = preg_replace($nonDisplayAbleCharacters, '', $_body); + + return $_body; + } + + function getSessionData() + { + return $this->sessionData; + } + + // get the user name, will will use for the FROM field + function getUserName() + { + $retData = sprintf("%s <%s>",$this->preferences['realname'],$this->preferences['emailAddress']); + return $retData; + } + + function removeAttachment($_attachmentID) { + if (parse_url($this->sessionData['attachments'][$_attachmentID]['file'],PHP_URL_SCHEME) != 'vfs') { + unlink($this->sessionData['attachments'][$_attachmentID]['file']); + } + unset($this->sessionData['attachments'][$_attachmentID]); + $this->saveSessionData(); + } + + function restoreSessionData() + { + $this->sessionData = $GLOBALS['egw']->session->appsession('compose_session_data_'.$this->composeID, 'felamimail'); + } + + function saveSessionData() + { + $GLOBALS['egw']->session->appsession('compose_session_data_'.$this->composeID,'felamimail',$this->sessionData); + } + + function createMessage(&$_mailObject, $_formData, $_identity, $_signature = false) + { + $bofelamimail =& $this->bofelamimail; //CreateObject('felamimail.bofelamimail',$this->displayCharset); + $userLang = $GLOBALS['egw_info']['user']['preferences']['common']['lang']; + $langFile = EGW_SERVER_ROOT."/phpgwapi/setup/phpmailer.lang-$userLang.php"; + if(file_exists($langFile)) { + $_mailObject->SetLanguage($userLang, EGW_SERVER_ROOT."/phpgwapi/setup/"); + } else { + $_mailObject->SetLanguage("en", EGW_SERVER_ROOT."/phpgwapi/setup/"); + } + $_mailObject->PluginDir = EGW_SERVER_ROOT."/phpgwapi/inc/"; + $activeMailProfile = $this->preferences->getIdentity(0); + $_mailObject->IsSMTP(); + $_mailObject->CharSet = $this->displayCharset; + // you need to set the sender, if you work with different identities, since most smtp servers, dont allow + // sending in the name of someone else + $_mailObject->Sender = $activeMailProfile->emailAddress; + $_mailObject->From = $_identity->emailAddress; + $_mailObject->FromName = $_mailObject->EncodeHeader($_identity->realName); + $_mailObject->Priority = $_formData['priority']; + $_mailObject->Encoding = 'quoted-printable'; + $_mailObject->AddCustomHeader('X-Mailer: FeLaMiMail'); + if(isset($this->sessionData['in-reply-to'])) { + $_mailObject->AddCustomHeader('In-Reply-To: '. $this->sessionData['in-reply-to']); + } + if($_formData['disposition']) { + $_mailObject->AddCustomHeader('Disposition-Notification-To: '. $_identity->emailAddress); + } + if(!empty($_identity->organization)) { + #$_mailObject->AddCustomHeader('Organization: '. $bofelamimail->encodeHeader($_identity->organization, 'q')); + $_mailObject->AddCustomHeader('Organization: '. $_identity->organization); + } + + foreach((array)$_formData['to'] as $address) { + $address_array = imap_rfc822_parse_adrlist((get_magic_quotes_gpc()?stripslashes($address):$address), ''); + foreach((array)$address_array as $addressObject) { + $emailAddress = $addressObject->mailbox. (!empty($addressObject->host) ? '@'.$addressObject->host : ''); + #$emailName = $bofelamimail->encodeHeader($addressObject->personal, 'q'); + #$_mailObject->AddAddress($emailAddress, $emailName); + $_mailObject->AddAddress($emailAddress, $addressObject->personal); + } + } + + foreach((array)$_formData['cc'] as $address) { + $address_array = imap_rfc822_parse_adrlist((get_magic_quotes_gpc()?stripslashes($address):$address),''); + foreach((array)$address_array as $addressObject) { + $emailAddress = $addressObject->mailbox. (!empty($addressObject->host) ? '@'.$addressObject->host : ''); + #$emailName = $bofelamimail->encodeHeader($addressObject->personal, 'q'); + #$_mailObject->AddCC($emailAddress, $emailName); + $_mailObject->AddCC($emailAddress, $addressObject->personal); + } + } + + foreach((array)$_formData['bcc'] as $address) { + $address_array = imap_rfc822_parse_adrlist((get_magic_quotes_gpc()?stripslashes($address):$address),''); + foreach((array)$address_array as $addressObject) { + $emailAddress = $addressObject->mailbox. (!empty($addressObject->host) ? '@'.$addressObject->host : ''); + #$emailName = $bofelamimail->encodeHeader($addressObject->personal, 'q'); + #$_mailObject->AddBCC($emailAddress, $emailName); + $_mailObject->AddBCC($emailAddress, $addressObject->personal); + } + } + + foreach((array)$_formData['replyto'] as $address) { + $address_array = imap_rfc822_parse_adrlist((get_magic_quotes_gpc()?stripslashes($address):$address),''); + foreach((array)$address_array as $addressObject) { + $emailAddress = $addressObject->mailbox. (!empty($addressObject->host) ? '@'.$addressObject->host : ''); + #$emailName = $bofelamimail->encodeHeader($addressObject->personal, 'q'); + #$_mailObject->AddBCC($emailAddress, $emailName); + $_mailObject->AddReplyto($emailAddress, $addressObject->personal); + } + } + + $_mailObject->WordWrap = 76; + #$_mailObject->Subject = $bofelamimail->encodeHeader($_formData['subject'], 'q'); + $_mailObject->Subject = $_formData['subject']; + #$realCharset = mb_detect_encoding($_formData['body'] . 'a' , strtoupper($this->displayCharset).',UTF-8, ISO-8859-1'); + #error_log("bocompose::createMessage:".$realCharset); + // this should never happen since we come from the edit dialog + if (bofelamimail::detect_qp($_formData['body'])) { + error_log("Error: bocompose::createMessage found QUOTED-PRINTABLE while Composing Message. Charset:$realCharset Message:".print_r($_formData['body'],true)); + $_formData['body'] = preg_replace('/=\r\n/', '', $_formData['body']); + $_formData['body'] = quoted_printable_decode($_formData['body']); + } + #if ($realCharset != $this->displayCharset) error_log("Error: bocompose::createMessage found Charset ($realCharset) differs from DisplayCharset (".$this->displayCharset.")"); + $signature = $_signature->fm_signature; + $signature = bofelamimail::merge($signature,array($GLOBALS['egw']->accounts->id2name($GLOBALS['egw_info']['user']['account_id'],'person_id'))); + if($_formData['mimeType'] =='html') { + $_mailObject->IsHTML(true); + if(!empty($signature)) { + #$_mailObject->Body = array($_formData['body'], $_signature['signature']); + if($this->sessionData['stationeryID']) { + $bostationery = new felamimail_bostationery(); + $_mailObject->Body = $bostationery->render($this->sessionData['stationeryID'],$_formData['body'],$signature); + } else { + $_mailObject->Body = $_formData['body'] .'
    '. $signature; + } + $_mailObject->AltBody = $this->convertHTMLToText($_formData['body']). + "\r\n-- \r\n". + $this->convertHTMLToText($signature); + #print "
    $_mailObject->AltBody
    "; + #print htmlentities($_signature['signature']); + } else { + if($this->sessionData['stationeryID']) { + $bostationery = new felamimail_bostationery(); + $_mailObject->Body = $bostationery->render($this->sessionData['stationeryID'],$_formData['body']); + } else { + $_mailObject->Body = $_formData['body']; + } + $_mailObject->AltBody = $this->convertHTMLToText($_formData['body']); + } + } else { + $_mailObject->IsHTML(false); + $_mailObject->Body = $this->convertHTMLToText($_formData['body'],false); + #$_mailObject->Body = $_formData['body']; + if(!empty($signature)) { + $_mailObject->Body .= "\r\n-- \r\n". $this->convertHTMLToText($signature); + } + } + + // add the attachments + $bofelamimail->openConnection(); + foreach((array)$this->sessionData['attachments'] as $attachment) { + if(!empty($attachment['uid']) && !empty($attachment['folder'])) { + switch($attachment['type']) { + case 'MESSAGE/RFC822': + $rawHeader=''; + $bofelamimail->reopen($attachment['folder']); + if (isset($attachment['partID'])) { + $rawHeader = $bofelamimail->getMessageRawHeader($attachment['uid'], $attachment['partID']); + } + $rawBody = $bofelamimail->getMessageRawBody($attachment['uid'], $attachment['partID']); + $_mailObject->AddStringAttachment($rawHeader.$rawBody, $_mailObject->EncodeHeader($attachment['name']), '7bit', 'message/rfc822'); + break; + default: + $bofelamimail->reopen($attachment['folder']); + $attachmentData = $bofelamimail->getAttachment($attachment['uid'], $attachment['partID']); + + $_mailObject->AddStringAttachment($attachmentData['attachment'], $_mailObject->EncodeHeader($attachment['name']), 'base64', $attachment['type']); + break; + + } + } else { + if (parse_url($attachment['file'],PHP_URL_SCHEME) == 'vfs') + { + egw_vfs::load_wrapper('vfs'); + } + $_mailObject->AddAttachment ( + $attachment['file'], + $_mailObject->EncodeHeader($attachment['name']), + 'base64', + $attachment['type'] + ); + } + } + $bofelamimail->closeConnection(); + } + + function saveAsDraft($_formData) + { + $bofelamimail =& $this->bofelamimail; //CreateObject('felamimail.bofelamimail',$this->displayCharset); + $mail = CreateObject('phpgwapi.phpmailer'); + $identity = $this->preferences->getIdentity((int)$this->sessionData['identity']); + $flags = '\\Seen \\Draft'; + $BCCmail = ''; + + $this->createMessage($mail, $_formData, $identity); + // preserve the bcc and if possible the save to folder information + $this->sessionData['folder'] = $_formData['folder']; + $this->sessionData['bcc'] = $_formData['bcc']; + $this->sessionData['signatureID'] = $_formData['signatureID']; + $this->sessionData['stationeryID'] = $_formData['stationeryID']; + $this->sessionData['identity'] = $_formData['identity']; + foreach((array)$this->sessionData['bcc'] as $address) { + $address_array = imap_rfc822_parse_adrlist((get_magic_quotes_gpc()?stripslashes($address):$address),''); + foreach((array)$address_array as $addressObject) { + $emailAddress = $addressObject->mailbox. (!empty($addressObject->host) ? '@'.$addressObject->host : ''); + $mailAddr[] = array($emailAddress, $addressObject->personal); + } + } + // folder list as Customheader + if (!empty($this->sessionData['folder'])) + { + $folders = implode('|',array_unique($this->sessionData['folder'])); + $mail->AddCustomHeader("X-Mailfolder: $folders"); + } + $mail->AddCustomHeader('X-Signature: '.$this->sessionData['signatureID']); + $mail->AddCustomHeader('X-Stationery: '.$this->sessionData['stationeryID']); + $mail->AddCustomHeader('X-Identity: '.(int)$this->sessionData['identity']); + // decide where to save the message (default to draft folder, if we find nothing else) + // if the current folder is in draft or template folder save it there + // if it is called from printview then save it with the draft folder + $savingDestination = ($this->preferences->ic_server[0]->draftfolder ? $this->preferences->ic_server[0]->draftfolder : $this->preferencesArray['draftFolder']); + if (empty($this->sessionData['messageFolder']) && !empty($this->sessionData['mailbox'])) $this->sessionData['messageFolder'] = $this->sessionData['mailbox']; + if ($bofelamimail->isDraftFolder($this->sessionData['messageFolder']) + || $bofelamimail->isTemplateFolder($this->sessionData['messageFolder'])) + { + $savingDestination = $this->sessionData['messageFolder']; + } + if ( !empty($_formData['printit']) && $_formData['printit'] == 0 ) $savingDestination = ($this->preferences->ic_server[0]->draftfolder ? $this->preferences->ic_server[0]->draftfolder : $this->preferencesArray['draftFolder']); + + if (count($mailAddr)>0) $BCCmail = $mail->AddrAppend("Bcc",$mailAddr); + $bofelamimail->openConnection(); + if ($bofelamimail->folderExists($savingDestination,true)) { + $messageUid = $bofelamimail->appendMessage($savingDestination, + $BCCmail.$mail->getMessageHeader(), + $mail->getMessageBody(), + $flags); + } else { + error_log("bofelamimail::saveAsDraft->".lang("folder")." ". $savingDestination." ".lang("does not exist on IMAP Server.")); + return false; + } + $bofelamimail->closeConnection(); + return $messageUid; + } + + function send($_formData) + { + $bofelamimail =& $this->bofelamimail; //CreateObject('felamimail.bofelamimail',$this->displayCharset); + $mail =& CreateObject('phpgwapi.phpmailer'); + $messageIsDraft = false; + + $this->sessionData['identity'] = $_formData['identity']; + $this->sessionData['to'] = $_formData['to']; + $this->sessionData['cc'] = $_formData['cc']; + $this->sessionData['bcc'] = $_formData['bcc']; + $this->sessionData['folder'] = $_formData['folder']; + $this->sessionData['replyto'] = $_formData['replyto']; + $this->sessionData['subject'] = trim($_formData['subject']); + $this->sessionData['body'] = $_formData['body']; + $this->sessionData['priority'] = $_formData['priority']; + $this->sessionData['signatureID'] = $_formData['signatureID']; + $this->sessionData['stationeryID'] = $_formData['stationeryID']; + $this->sessionData['disposition'] = $_formData['disposition']; + $this->sessionData['mimeType'] = $_formData['mimeType']; + $this->sessionData['to_infolog'] = $_formData['to_infolog']; + // if the body is empty, maybe someone pasted something with scripts, into the message body + // this should not happen anymore, unless you call send directly, since the check was introduced with the action command + if(empty($this->sessionData['body'])) + { + // this is to be found with the egw_unset_vars array for the _POST['body'] array + $name='_POST'; + $key='body'; + #error_log($GLOBALS['egw_unset_vars'][$name.'['.$key.']']); + if (isset($GLOBALS['egw_unset_vars'][$name.'['.$key.']'])) + { + $this->sessionData['body'] = self::_getCleanHTML( $GLOBALS['egw_unset_vars'][$name.'['.$key.']']); + $_formData['body']=$this->sessionData['body']; + } + #error_log($this->sessionData['body']); + } + if(empty($this->sessionData['to']) && empty($this->sessionData['cc']) && + empty($this->sessionData['bcc']) && empty($this->sessionData['folder'])) { + $messageIsDraft = true; + } + #error_log(print_r($this->preferences,true)); + $identity = $this->preferences->getIdentity((int)$this->sessionData['identity']); + $signature = $this->bosignatures->getSignature((int)$this->sessionData['signatureID']); + #error_log($this->sessionData['identity']); + #error_log(print_r($identity,true)); + // create the messages + $this->createMessage($mail, $_formData, $identity, $signature); + #print "
    ". $mail->getMessageHeader() ."


    "; + #print "
    ". $mail->getMessageBody() ."


    "; + #exit; + + $ogServer = $this->preferences->getOutgoingServer(0); + #_debug_array($ogServer); + $mail->Host = $ogServer->host; + $mail->Port = $ogServer->port; + // SMTP Auth?? + if($ogServer->smtpAuth) { + $mail->SMTPAuth = true; + // check if username contains a ; -> then a sender is specified (and probably needed) + list($username,$senderadress) = explode(';', $ogServer->username,2); + if (isset($senderadress) && !empty($senderadress)) $mail->Sender = $senderadress; + $mail->Username = $username; + $mail->Password = $ogServer->password; + } + + // set a higher timeout for big messages + @set_time_limit(120); + //$mail->SMTPDebug = 10; + #error_log("Folder:".count(array($this->sessionData['folder']))."To:".count((array)$this->sessionData['to'])."CC:". count((array)$this->sessionData['cc']) ."bcc:".count((array)$this->sessionData['bcc'])); + if(count((array)$this->sessionData['to']) > 0 || count((array)$this->sessionData['cc']) > 0 || count((array)$this->sessionData['bcc']) > 0) { + if(!$mail->Send()) { + $this->errorInfo = $mail->ErrorInfo; + #error_log($this->errorInfo); + return false; + } + } else { + if (count(array($this->sessionData['folder']))>0 && !empty($this->sessionData['folder'])) { + #error_log("Folders:".print_r($this->sessionData['folder'],true)); + } else { + $this->errorInfo = lang("Error: ").lang("No Address TO/CC/BCC supplied, and no folder to save message to provided."); + #error_log($this->errorInfo); + return false; + } + } + #error_log("Mail Sent.!"); + $folder = (array)$this->sessionData['folder']; + if(isset($this->preferences->preferences['sentFolder']) && + $this->preferences->preferences['sentFolder'] != 'none' && + $messageIsDraft == false) { + $folder[] = $this->preferences->preferences['sentFolder']; + } + if($messageIsDraft == true) { + if(!empty($this->preferences->preferences['draftFolder'])) { + $folder[] = $this->sessionData['folder'] = array($this->preferences->preferences['draftFolder']); + } + } + $folder = array_unique($folder); + #error_log("Number of Folders to move copy the message to:".count($folder)); + if ((count($folder) > 0) || (isset($this->sessionData['uid']) && isset($this->sessionData['messageFolder'])) + || (isset($this->sessionData['forwardFlag']) && isset($this->sessionData['sourceFolder']))) { + $bofelamimail =& $this->bofelamimail; //CreateObject('felamimail.bofelamimail'); + $bofelamimail->openConnection(); + //$bofelamimail->reopen($this->sessionData['messageFolder']); + #error_log("(re)opened Connection"); + } + if (count($folder) > 0) { + + foreach((array)$this->sessionData['bcc'] as $address) { + $address_array = imap_rfc822_parse_adrlist((get_magic_quotes_gpc()?stripslashes($address):$address),''); + foreach((array)$address_array as $addressObject) { + $emailAddress = $addressObject->mailbox. (!empty($addressObject->host) ? '@'.$addressObject->host : ''); + $mailAddr[] = array($emailAddress, $addressObject->personal); + } + } + $BCCmail=''; + if (count($mailAddr)>0) $BCCmail = $mail->AddrAppend("Bcc",$mailAddr); + //$bofelamimail =& CreateObject('felamimail.bofelamimail'); + //$bofelamimail->openConnection(); + foreach($folder as $folderName) { + if($bofelamimail->isSentFolder($folderName)) { + $flags = '\\Seen'; + } elseif($bofelamimail->isDraftFolder($folderName)) { + $flags = '\\Draft'; + } else { + $flags = ''; + } + #$mailHeader=explode('From:',$mail->getMessageHeader()); + #$mailHeader[0].$mail->AddrAppend("Bcc",$mailAddr).'From:'.$mailHeader[1], + if ($bofelamimail->folderExists($folderName,true)) { + $bofelamimail->appendMessage($folderName, + $BCCmail.$mail->getMessageHeader(), + $mail->getMessageBody(), + $flags); + } + } + //$bofelamimail->closeConnection(); + } + #error_log("handling draft messages, flagging and such"); + if((isset($this->sessionData['uid']) && isset($this->sessionData['messageFolder'])) + || (isset($this->sessionData['forwardFlag']) && isset($this->sessionData['sourceFolder']))) { + // mark message as answered + //$bofelamimail =& CreateObject('felamimail.bofelamimail'); + $bofelamimail->openConnection(); + $bofelamimail->reopen($this->sessionData['messageFolder']); + // if the draft folder is a starting part of the messages folder, the draft message will be deleted after the send + // unless your templatefolder is a subfolder of your draftfolder, and the message is in there + if ($bofelamimail->isDraftFolder($this->sessionData['messageFolder']) && !$bofelamimail->isTemplateFolder($this->sessionData['messageFolder'])) + { + $bofelamimail->deleteMessages(array($this->sessionData['uid'])); + } else { + $bofelamimail->flagMessages("answered", array($this->sessionData['uid'])); + if (array_key_exists('forwardFlag',$this->sessionData) && $this->sessionData['forwardFlag']=='forwarded') + { + $bofelamimail->flagMessages("forwarded", array($this->sessionData['forwardedUID'])); + } + } + //$bofelamimail->closeConnection(); + } + if ($bofelamimail) $bofelamimail->closeConnection(); + //error_log("performing Infolog Stuff"); + //error_log(print_r($this->sessionData['to'],true)); + //error_log(print_r($this->sessionData['cc'],true)); + //error_log(print_r($this->sessionData['bcc'],true)); + if (is_array($this->sessionData['to'])) + { + $mailaddresses = $this->sessionData['to']; + } + else + { + $mailaddresses = array(); + } + if (is_array($this->sessionData['cc'])) $mailaddresses = array_merge($mailaddresses,$this->sessionData['cc']); + if (is_array($this->sessionData['bcc'])) $mailaddresses = array_merge($mailaddresses,$this->sessionData['bcc']); + // attention: we dont return from infolog. cleanups will be done there. + if ($_formData['to_infolog'] == 'on') { + $uiinfolog =& CreateObject('infolog.infolog_ui'); + $uiinfolog->import_mail( + $mailaddresses, + $this->sessionData['subject'], + $this->convertHTMLToText($this->sessionData['body']), + $this->sessionData['attachments'] + ); + } + + if(is_array($this->sessionData['attachments'])) { + reset($this->sessionData['attachments']); + while(list($key,$value) = @each($this->sessionData['attachments'])) { + #print "$key: ".$value['file']."
    "; + if (!empty($value['file']) && parse_url($value['file'],PHP_URL_SCHEME) != 'vfs') { // happens when forwarding mails + unlink($value['file']); + } + } + } + + $this->sessionData = ''; + $this->saveSessionData(); + + return true; + } + + function setDefaults() + { + require_once(EGW_INCLUDE_ROOT.'/felamimail/inc/class.felamimail_bosignatures.inc.php'); + $boSignatures = new felamimail_bosignatures(); + + if($signatureData = $boSignatures->getDefaultSignature()) { + if (is_array($signatureData)) { + $this->sessionData['signatureID'] = $signatureData['signatureid']; + } else { + $this->sessionData['signatureID'] = $signatureData; + } + } else { + $this->sessionData['signatureID'] = -1; + } + // retrieve the signature accociated with the identity + $accountData = $this->bopreferences->getAccountData($this->preferences,'active'); + if ($accountData['identity']->signature) $this->sessionData['signatureID'] = $accountData['identity']->signature; + // apply the current mailbox to the compose session data of the/a new email + $appsessionData = $GLOBALS['egw']->session->appsession('session_data'); + $this->sessionData['mailbox'] = $appsessionData['mailbox']; + + $this->sessionData['mimeType'] = 'html'; + if (!empty($this->preferencesArray['composeOptions']) && $this->preferencesArray['composeOptions']=="text") $this->sessionData['mimeType'] = 'text/plain'; + + $this->saveSessionData(); + } + + function stripSlashes($_string) + { + if (get_magic_quotes_gpc()) { + return stripslashes($_string); + } else { + return $_string; + } + } +} diff --git a/felamimail/inc/class.bofelamimail.inc.php b/felamimail/inc/class.bofelamimail.inc.php index b19ab6989d..5fe7cbcdf7 100644 --- a/felamimail/inc/class.bofelamimail.inc.php +++ b/felamimail/inc/class.bofelamimail.inc.php @@ -2706,7 +2706,7 @@ return $userACL; } - static function wordwrap($str, $cols, $cut) + static function wordwrap($str, $cols, $cut, $dontbreaklinesstartingwith=false) { $lines = explode("\n", $str); $newStr = ''; @@ -2716,7 +2716,14 @@ //$line = str_replace("\t"," ",$line); //$newStr .= wordwrap($line, $cols, $cut); $allowedLength = $cols-strlen($cut); - if (strlen($line) > $allowedLength) { + if (strlen($line) > $allowedLength && + ($dontbreaklinesstartingwith==false || + ($dontbreaklinesstartingwith && + strlen($dontbreaklinesstartingwith)>=1 && + substr($line,0,strlen($dontbreaklinesstartingwith)) != $dontbreaklinesstartingwith + ) + ) + ) { $s=explode(" ", $line); $line = ""; $linecnt = 0; @@ -2932,21 +2939,26 @@ /** * Helper function to handle wrong or unrecognized timezones * returns the date as it is parseable by strtotime, or current timestamp if everything failes + * @param string date to be parsed/formatted + * @param string format string, if none is passed, use the users common dateformat supplemented by the time hour:minute:second + * @return string returns the date as it is parseable by strtotime, or current timestamp if everything failes */ - static function _strtotime($date='') + static function _strtotime($date='',$format=NULL) { - if (strtotime($date)===false) + if ($format==NULL) $format = $GLOBALS['egw_info']['user']['preferences']['common']['dateformat'].' '.'H:i:s'; + $date2return = egw_time::to($date,$format); + if ($date2return==null) { $dtarr = explode(' ',$date); - $test = false; - while ($test===false && count($dtarr)>=1) + $test = null; + while ($test===null && count($dtarr)>=1) { array_pop($dtarr); - $test=strtotime(implode(' ',$dtarr)); - if ($test) $date = implode(' ',$dtarr); + $test= egw_time::to(implode(' ',$dtarr),$format); + if ($test) $date2return = $test; } - if ($test===false) $date = strtotime('now'); + if ($test===null) $date2return = egw_time::to('now',$format); } - return $date; + return $date2return; } } diff --git a/felamimail/inc/class.uidisplay.inc.php b/felamimail/inc/class.uidisplay.inc.php new file mode 100644 index 0000000000..67bca95bab --- /dev/null +++ b/felamimail/inc/class.uidisplay.inc.php @@ -0,0 +1,1649 @@ + + * + * See the enclosed file COPYING for license information (LGPL). If you + * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html. + * + */ + + /* $Id$ */ + + class uidisplay + { + + var $public_functions = array + ( + 'display' => True, + 'displayBody' => True, + 'displayHeader' => True, + 'displayImage' => True, + 'displayAttachments' => True, + 'printMessage' => True, + 'saveMessage' => True, + 'showHeader' => True, + 'getAttachment' => True, + ); + + var $icServerID=0; + + // the object storing the data about the incoming imap server + var $icServer=0; + + // the non permanent id of the message + var $id; + + // the permanent id of the message + var $uid; + var $bofelamimail; + var $bopreferences; + + function uidisplay() + { + /* 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 + * + * RFC2822 (and RFC822) defines the left side of an email address as (roughly): + * 1*atext *("." 1*atext) + * where atext is: a-zA-Z0-9!#$%&'*+-/=?^_`{|}~ + * + * Here's pretty sophisticated IP matching: + * $IPMatch = '(2[0-5][0-9]|1?[0-9]{1,2})'; + * $IPMatch = '\[?' . $IPMatch . '(\.' . $IPMatch . '){3}\]?'; + */ + /* Here's enough: */ + global $IP_RegExp_Match, $Host_RegExp_Match, $Email_RegExp_Match; + $IP_RegExp_Match = '\\[?[0-9]{1,3}(\\.[0-9]{1,3}){3}\\]?'; + $Host_RegExp_Match = '('.$IP_RegExp_Match.'|[0-9a-z]([-.]?[0-9a-z])*\\.[a-z][a-z]+)'; + #$atext = '([a-z0-9!#$&%*+/=?^_`{|}~-]|&)'; + $atext = '([a-zA-Z0-9_\-\.])'; + $dot_atom = $atext.'+(\.'.$atext.'+)*'; + $Email_RegExp_Match = '~'.$dot_atom.'(%'.$Host_RegExp_Match.')?@'.$Host_RegExp_Match.'~i'; + + $this->t = CreateObject('phpgwapi.Template',EGW_APP_TPL); + $this->displayCharset = $GLOBALS['egw']->translation->charset(); + $this->bofelamimail = CreateObject('felamimail.bofelamimail',$this->displayCharset); + $this->bopreferences = $this->bofelamimail->bopreferences; //CreateObject('felamimail.bopreferences'); + + $this->mailPreferences = $this->bopreferences->getPreferences(); + + $this->bofelamimail->openConnection($this->icServerID); + + $this->mailbox = $this->bofelamimail->sessionData['mailbox']; + if (!empty($_GET['mailbox'])) $this->mailbox = base64_decode($_GET['mailbox']); + + $this->sort = $this->bofelamimail->sessionData['sort']; + + if(isset($_GET['uid'])) { + $this->uid = (int)$_GET['uid']; + } + + if(isset($_GET['id'])) { + $this->id = (int)$_GET['id']; + } + + if(isset($this->id) && !isset($this->uid)) { + if($uid = $this->bofelamimail->idToUid($this->mailbox, $this->id)) { + $this->uid = $uid; + } + } + + if(isset($_GET['part'])) { + $this->partID = (int)$_GET['part']; + } + + $this->rowColor[0] = $GLOBALS['egw_info']["theme"]["bg01"]; + $this->rowColor[1] = $GLOBALS['egw_info']["theme"]["bg02"]; + } + + /** + * Parses a body and converts all found email addresses to clickable links. + * + * @param string body the body to process, by ref + * @return int the number of unique addresses found + */ + function parseEmail (&$body) { + global $Email_RegExp_Match; + $sbody = $body; + $addresses = array(); + $i = 0; + /* Find all the email addresses in the body */ + // stop cold after 100 adresses, as this is very time consuming + while(preg_match($Email_RegExp_Match, $sbody, $regs) && $i<=100) { + //_debug_array($regs); + $addresses[$regs[0]] = strtr($regs[0], array('&' => '&')); + $start = strpos($sbody, $regs[0]) + strlen($regs[0]); + $sbody = substr($sbody, $start); + $i++; + } + + /* Replace each email address with a compose URL */ + $lmail=''; + if (is_array($addresses)) ksort($addresses); + foreach ($addresses as $text => $email) { + if ($lmail == $email) next($addresses); + //echo __METHOD__.' Text:'.$text."#
    "; + //echo $email."#
    "; + $comp_uri = $this->makeComposeLink($email, $text); + //echo __METHOD__.' Uri:'.$comp_uri.'#
    '; + $body = str_replace($text, $comp_uri, $body); + $lmail=$email; + } + + /* Return number of unique addresses found */ + return count($addresses); + } + function parseHREF (&$body) { + #echo __METHOD__."called
    "; + $webserverURL = $GLOBALS['egw_info']['server']['webserver_url']; + $alnum = 'a-z0-9'; + #$domain = "(http(s?):\/\/)*"; + #$domain .= "([$alnum]([-$alnum]*[$alnum]+)?)"; + #$domain = "^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*[^\.\,\)\(\s]$ "; + $domain = "(http(s?):\/\/)+([[:alpha:]][-[:alnum:]]*[[:alnum:]])(\.[[:alpha:]][-[:alnum:]]*[[:alpha:]])*(\.[[:alpha:]][-[:alnum:]]*[[:alpha:]])+"; + #$dir = "(/[[:alpha:]][-[:alnum:]]*[[:alnum:]])*"; + #$trailingslash = "(\/?)"; + #$page = "(/[[:alpha:]][-[:alnum:]]*\.[[:alpha:]]{3,5})?"; + #$getstring = "(\?([[:alnum:]][-_%[:alnum:]]*=[-_%[:alnum:]]+) + # (&([[:alnum:]][-_%[:alnum:]]*=[-_%[:alnum:]]+))*)?"; + #$pattern = "^".$domain.$dir.$trailingslash.$page.$getstring."$"; + $pattern = "~\ $link) { + if (empty($link)) continue; + if ($llink == $link) next($addresses); + #echo $text."#
    "; + #echo $link."#
    \n"; + $comp_uri = "
    '.$text.''; + } + + function highlightQuotes($text, $level = 5) + { + // Use a global var since the class is called statically. + $GLOBALS['_tmp_maxQuoteChars'] = 0; + + // Tack a newline onto the beginning of the string so that we + // correctly highlight when the first character in the string + // is a quote character. + $text = "\n$text"; + + preg_replace_callback("/^\s*((>\s?)+)/m", array(&$this, '_countQuoteChars'), $text); + + // Go through each level of quote block and put the + // appropriate style around it. Important to work downwards so + // blocks with fewer quote chars aren't matched until their + // turn. + for ($i = $GLOBALS['_tmp_maxQuoteChars']; $i > 0; $i--) + { + $text = preg_replace( + // Finds a quote block across multiple newlines. + "/(\n)( *(>\s?)\{$i}(?! ?>).*?)(\n|$)(?! *(> ?)\{$i})/s", + '\1\2\4',$text); + } + + /* Unset the global variable. */ + unset($GLOBALS['_tmp_maxQuoteChars']); + + /* Remove the leading newline we added above. */ + return substr($text, 1); + } + + function _countQuoteChars($matches) + { + $num = count(preg_split('/>\s?/', $matches[1])) - 1; + if ($num > $GLOBALS['_tmp_maxQuoteChars']) + { + $GLOBALS['_tmp_maxQuoteChars'] = $num; + } + } + + function display() + { + $partID = $_GET['part']; + if (!empty($_GET['mailbox'])) $this->mailbox = base64_decode($_GET['mailbox']); + + //$transformdate =& CreateObject('felamimail.transformdate'); + //$htmlFilter =& CreateObject('felamimail.htmlfilter'); + $uiWidgets = CreateObject('felamimail.uiwidgets'); + // (regis) seems to be necessary to reopen... + $this->bofelamimail->reopen($this->mailbox); + // retrieve the flags of the message, before touching it. + if (!empty($this->uid)) $flags = $this->bofelamimail->getFlags($this->uid); + #print "$this->mailbox, $this->uid, $partID
    "; + $headers = $this->bofelamimail->getMessageHeader($this->uid, $partID); + if (PEAR::isError($headers)) { + print lang("ERROR: Message could not be displayed.")."
    "; + print "In Mailbox: $this->mailbox, with ID: $this->uid, and PartID: $partID
    "; + print $headers->message."
    "; + _debug_array($headers->backtrace[0]); + exit; + } + #_debug_array($headers);exit; + $rawheaders = $this->bofelamimail->getMessageRawHeader($this->uid, $partID); + #_debug_array($rawheaders);exit; + $attachments = $this->bofelamimail->getMessageAttachments($this->uid, $partID); + #_debug_array($attachments); exit; + $envelope = $this->bofelamimail->getMessageEnvelope($this->uid, $partID); + #_debug_array($envelope); exit; + // if not using iFrames, we need to retrieve the messageBody here + // by now this is a fixed value and controls the use/loading of the template and how the vars are set. + // Problem is: the iFrame Layout provides the scrollbars. + #$bodyParts = $this->bofelamimail->getMessageBody($this->uid,'',$partID); + #_debug_array($bodyParts); exit; + #_debug_array($this->uid); + #_debug_array($this->bofelamimail->getFlags($this->uid)); #exit; + // flag the message as read/seen (if not already flagged) + if (!empty($this->uid) && strpos( array2string($flags),'Seen')===false) $this->bofelamimail->flagMessages('read', $this->uid); + + $nextMessage = $this->bofelamimail->getNextMessage($this->mailbox, $this->uid); + $webserverURL = $GLOBALS['egw_info']['server']['webserver_url']; + + $nonDisplayAbleCharacters = array('[\016]','[\017]', + '[\020]','[\021]','[\022]','[\023]','[\024]','[\025]','[\026]','[\027]', + '[\030]','[\031]','[\032]','[\033]','[\034]','[\035]','[\036]','[\037]'); + + #print "
    ";print_r($rawheaders);print"
    ";exit; + + // add line breaks to $rawheaders + $newRawHeaders = explode("\n",$rawheaders); + reset($newRawHeaders); + + if(isset($headers['ORGANIZATION'])) { + $organization = $this->bofelamimail->decode_header(trim($headers['ORGANIZATION'])); + } + + if ( isset($headers['DISPOSITION-NOTIFICATION-TO']) ) { + $sent_not = $this->bofelamimail->decode_header(trim($headers['DISPOSITION-NOTIFICATION-TO'])); + } else if ( isset($headers['RETURN-RECEIPT-TO']) ) { + $sent_not = $this->bofelamimail->decode_header(trim($headers['RETURN-RECEIPT-TO'])); + } else if ( isset($headers['X-CONFIRM-READING-TO']) ) { + $sent_not = $this->bofelamimail->decode_header(trim($headers['X-CONFIRM-READING-TO'])); + } else $sent_not = ""; + + // reset $rawheaders + $rawheaders = ""; + // create it new, with good line breaks + reset($newRawHeaders); + while(list($key,$value) = @each($newRawHeaders)) { + $rawheaders .= wordwrap($value, 90, "\n "); + } + + $this->display_app_header(); + if(!isset($_GET['printable'])) { + $this->t->set_file(array("displayMsg" => "view_message.tpl")); + } else { + $this->t->set_file(array("displayMsg" => "view_message_printable.tpl")); + $this->t->set_var('charset',$GLOBALS['egw']->translation->charset()); + } + // only notify when requested, notify flag (MDNSent/MDNnotSent) not set, and message not already seen (some servers do not support the MDNSent/MDNnotSent flag) + if ( $sent_not != "" && $this->bofelamimail->getNotifyFlags($this->uid) === null && strpos( array2string($flags),'Seen')===false) { + $this->t->set_var('sentNotify','sendNotify("'.$this->uid.'");'); + $this->t->set_var('lang_sendnotify',lang('The message sender has requested a response to indicate that you have read this message. Would you like to send a receipt?')); + } else { + $this->t->set_var('sentNotify',''); + $this->t->set_var('lang_sendnotify',''); + } + $this->bofelamimail->closeConnection(); + + $this->t->set_block('displayMsg','message_main'); + $this->t->set_block('displayMsg','message_main_attachment'); + $this->t->set_block('displayMsg','message_header'); + $this->t->set_block('displayMsg','message_raw_header'); + $this->t->set_block('displayMsg','message_navbar'); + $this->t->set_block('displayMsg','message_onbehalfof'); + $this->t->set_block('displayMsg','message_cc'); + $this->t->set_block('displayMsg','message_bcc'); + $this->t->set_block('displayMsg','message_attachement_row'); + $this->t->set_block('displayMsg','previous_message_block'); + $this->t->set_block('displayMsg','next_message_block'); + //$this->t->set_block('displayMsg','message_org'); + + $this->t->egroupware_hack = False; + + $this->translate(); + + // navBar buttons + $headerData = array('uid'=>$this->uid); + if($partID != '') { + $headerData['partid'] = $partID; + } + $this->t->set_var('navbarButtonsLeft',$uiWidgets->displayMessageActions($headerData, $this->mailbox, $this->icServer)); + + $navbarButtons = ''; + $navbarImages = array(); + #_debug_array($nextMessage); exit; + + if($nextMessage['previous']) { + $linkData = array ( + 'menuaction' => 'felamimail.uidisplay.display', + 'showHeader' => 'false', + 'uid' => $nextMessage['previous'], + 'mailbox' => base64_encode($this->mailbox) + ); + $previousURL = $GLOBALS['egw']->link('/index.php',$linkData); + $previousURL = "goToMessage('$previousURL')"; + $navbarImages['up.button'] = array( + 'action' => $previousURL, + 'tooltip' => lang('previous message'), + ); + } else { + $previousURL = '#'; + $navbarImages['up.grey'] = array( + 'action' => $previousURL, + 'tooltip' => lang('previous message'), + ); + } + + if($nextMessage['next']) { + $linkData = array ( + 'menuaction' => 'felamimail.uidisplay.display', + 'showHeader' => 'false', + 'uid' => $nextMessage['next'], + 'mailbox' => base64_encode($this->mailbox) + ); + $nextURL = $GLOBALS['egw']->link('/index.php',$linkData); + $nextURL = "goToMessage('$nextURL')"; + $navbarImages['down.button'] = array( + 'action' => $nextURL, + 'tooltip' => lang('next message'), + ); + } else { + $nextURL = '#'; + $navbarImages['down.grey'] = array( + #'action' => $nextURL, + 'tooltip' => lang('next message'), + ); + } + + + foreach($navbarImages as $buttonName => $buttonData) { + $navbarButtons .= $uiWidgets->navbarButton($buttonName, $buttonData['action'], $buttonData['tooltip'], 'right'); + } + + $this->t->set_var('navbarButtonsRight',$navbarButtons); + + $this->t->parse('navbar','message_navbar',True); + + // navbar end + // header + // sent by a mailinglist?? + // parse the from header + if($envelope['FROM'][0] != $envelope['SENDER'][0]) { + $senderAddress = self::emailAddressToHTML($envelope['SENDER']); + $fromAddress = self::emailAddressToHTML($envelope['FROM'], $organization); + $this->t->set_var("from_data",$senderAddress); + $this->t->set_var("onbehalfof_data",$fromAddress); + $this->t->parse('on_behalf_of_part','message_onbehalfof',True); + } else { + $fromAddress = self::emailAddressToHTML($envelope['FROM'], $organization); + $this->t->set_var("from_data", $fromAddress); + $this->t->set_var('on_behalf_of_part',''); + } + + // parse the to header + $toAddress = self::emailAddressToHTML($envelope['TO']); + $this->t->set_var("to_data",$toAddress); + + // parse the cc header + if(count($envelope['CC'])) { + $ccAddress = self::emailAddressToHTML($envelope['CC']); + $this->t->set_var("cc_data",$ccAddress); + $this->t->parse('cc_data_part','message_cc',True); + } else { + $this->t->set_var("cc_data_part",''); + } + + // parse the bcc header + if(count($envelope['BCC'])) { + $bccAddress = self::emailAddressToHTML($envelope['BCC']); + $this->t->set_var("bcc_data",$bccAddress); + $this->t->parse('bcc_data_part','message_bcc',True); + } else { + $this->t->set_var("bcc_data_part",''); + } + $this->t->set_var("date_received", + @htmlspecialchars(bofelamimail::_strtotime($headers['DATE'],$GLOBALS['egw_info']['user']['preferences']['common']['dateformat']).' - '.bofelamimail::_strtotime($headers['DATE'],'H:i:s'), + ENT_QUOTES,$this->displayCharset)); + + $this->t->set_var("subject_data", + @htmlspecialchars($this->bofelamimail->decode_subject(preg_replace($nonDisplayAbleCharacters,'',$envelope['SUBJECT'])), + ENT_QUOTES,$this->displayCharset)); + + $this->t->parse("header","message_header",True); + + $this->t->set_var("rawheader",@htmlentities(preg_replace($nonDisplayAbleCharacters,'',$rawheaders),ENT_QUOTES,$this->displayCharset)); + + $linkData = array ( + 'menuaction' => 'felamimail.uidisplay.displayBody', + 'uid' => $this->uid, + 'part' => $partID, + 'mailbox' => base64_encode($this->mailbox) + ); + $this->t->set_var('url_displayBody', $GLOBALS['egw']->link('/index.php',$linkData)); + + // attachments + if(is_array($attachments) && count($attachments) > 0) { + $this->t->set_var('attachment_count',count($attachments)); + } else { + $this->t->set_var('attachment_count','0'); + } + + if (is_array($attachments) && count($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->set_var('url_img_save',html::image('felamimail','fileexport', lang('save'))); + $url_img_vfs = html::image('filemanager','navbar', lang('Filemanager'), ' height="16"'); + $url_img_vfs_save_all = html::image('felamimail','save_all', lang('Save all')); + #$this->t->parse('attachment_rows','attachment_row_bold',True); + + $detectedCharSet=$charset2use=$this->displayCharset; + foreach ($attachments as $key => $value) + { + #$detectedCharSet = mb_detect_encoding($value['name'].'a',strtoupper($this->displayCharset).",UTF-8, ISO-8559-1"); + if (function_exists('mb_convert_variables')) mb_convert_variables("UTF-8","ISO-8559-1",$value['name']); # iso 2 UTF8 + //if (mb_convert_variables("ISO-8859-1","UTF-8",$value['name'])){echo "Juhu utf8 2 ISO\n";}; + //echo $value['name']."\n"; + $filename=htmlentities($value['name'], ENT_QUOTES, $detectedCharSet); + + $this->t->set_var('row_color',$this->rowColor[($key+1)%2]); + $this->t->set_var('filename',($value['name'] ? ( $filename ? $filename : $value['name'] ) : lang('(no subject)'))); + $this->t->set_var('mimetype',mime_magic::mime2label($value['mimeType'])); + $this->t->set_var('size',egw_vfs::hsize($value['size'])); + $this->t->set_var('attachment_number',$key); + + switch(strtoupper($value['mimeType'])) + { + case 'MESSAGE/RFC822': + $linkData = array + ( + 'menuaction' => 'felamimail.uidisplay.display', + 'uid' => $this->uid, + 'part' => $value['partID'], + 'mailbox' => base64_encode($this->mailbox), + 'is_winmail' => $value['is_winmail'] + ); + $windowName = 'displayMessage_'. $this->uid.'_'.$value['partID']; + $linkView = "egw_openWindowCentered('".$GLOBALS['egw']->link('/index.php',$linkData)."','$windowName',700,egw_getWindowOuterHeight());"; + break; + case 'IMAGE/JPEG': + case 'IMAGE/PNG': + case 'IMAGE/GIF': + case 'IMAGE/BMP': + case 'APPLICATION/PDF': + case 'TEXT/PLAIN': + case 'TEXT/HTML': + case 'TEXT/CALENDAR': + case 'TEXT/X-VCARD': + $linkData = array + ( + 'menuaction' => 'felamimail.uidisplay.getAttachment', + 'uid' => $this->uid, + 'part' => $value['partID'], + 'is_winmail' => $value['is_winmail'], + 'mailbox' => base64_encode($this->mailbox), + ); + $windowName = 'displayAttachment_'. $this->uid; + $reg = '800x600'; + // handle calendar/vcard + if (strtoupper($value['mimeType'])=='TEXT/CALENDAR') + { + $windowName = 'displayEvent_'. $this->uid; + $reg2 = egw_link::get_registry('calendar','view_popup'); + } + if (strtoupper($value['mimeType'])=='TEXT/X-VCARD') + { + $windowName = 'displayContact_'. $this->uid; + $reg2 = egw_link::get_registry('addressbook','add_popup'); + } + // apply to action + list($width,$height) = explode('x',(!empty($reg2) ? $reg2 : $reg)); + $linkView = "egw_openWindowCentered('".$GLOBALS['egw']->link('/index.php',$linkData)."','$windowName',$width,$height);"; + break; + default: + $linkData = array + ( + 'menuaction' => 'felamimail.uidisplay.getAttachment', + 'uid' => $this->uid, + 'part' => $value['partID'], + 'is_winmail' => $value['is_winmail'], + 'mailbox' => base64_encode($this->mailbox), + ); + $linkView = "window.location.href = '".$GLOBALS['egw']->link('/index.php',$linkData)."';"; + break; + } + $this->t->set_var("link_view",$linkView); + $this->t->set_var("target",$target); + + $linkData = array + ( + 'menuaction' => 'felamimail.uidisplay.getAttachment', + 'mode' => 'save', + 'uid' => $this->uid, + 'part' => $value['partID'], + 'is_winmail' => $value['is_winmail'], + 'mailbox' => base64_encode($this->mailbox), + ); + $this->t->set_var("link_save",$GLOBALS['egw']->link('/index.php',$linkData)); + + if ($GLOBALS['egw_info']['user']['apps']['filemanager']) + { + $link_vfs_save = egw::link('/index.php',array( + 'menuaction' => 'filemanager.filemanager_select.select', + 'mode' => 'saveas', + 'name' => $value['name'], + 'mime' => strtolower($value['mimeType']), + 'method' => 'felamimail.uidisplay.vfsSaveAttachment', + 'id' => $this->mailbox.'::'.$this->uid.'::'.$value['partID'].'::'.$value['is_winmail'], + 'label' => lang('Save'), + )); + $vfs_save = "$url_img_vfs"; + // add save-all icon for first attachment + if (!$key && count($attachments) > 1) + { + foreach ($attachments as $key => $value) + { + $ids["id[$key]"] = $this->mailbox.'::'.$this->uid.'::'.$value['partID'].'::'.$value['is_winmail'].'::'.$value['name']; + } + $link_vfs_save = egw::link('/index.php',array( + 'menuaction' => 'filemanager.filemanager_select.select', + 'mode' => 'select-dir', + 'method' => 'felamimail.uidisplay.vfsSaveAttachment', + 'label' => lang('Save all'), + )+$ids); + $vfs_save .= "\n$url_img_vfs_save_all"; + } + $this->t->set_var('vfs_save',$vfs_save); + } + else + { + $this->t->set_var('vfs_save',''); + } + $this->t->parse('attachment_rows','message_attachement_row',True); + } + } else { + $this->t->set_var('attachment_rows',''); + } + + #$this->t->pparse("out","message_attachment_rows"); + + // print it out + if(is_array($attachments) && count($attachments) > 0) { + $this->t->pparse('out','message_main_attachment'); + } else { + $this->t->pparse('out','message_main'); + } + + } + + function displayBody() + { + $partID = $_GET['part']; + if (empty($this->uid) && !empty($_GET['uid']) ) $this->uid = 9247;//$_GET['uid']; + if (!empty($_GET['mailbox'])) $this->mailbox = base64_decode($_GET['mailbox']); + + $this->bofelamimail->reopen($this->mailbox); + $bodyParts = $this->bofelamimail->getMessageBody($this->uid,'',$partID); + $this->bofelamimail->closeConnection(); + + $this->display_app_header(); + $this->showBody($this->getdisplayableBody($bodyParts), true); + } + + function showBody(&$body, $print=true) + { + $BeginBody = ' +
    '; + + $EndBody = '
    '; + $EndBody .= ""; + if ($print) { + print $BeginBody. $body .$EndBody; + } else { + return $BeginBody. $body .$EndBody; + } + } + + function displayHeader() + { + $partID = $_GET['part']; + if (!empty($_GET['mailbox'])) $this->mailbox = base64_decode($_GET['mailbox']); + + //$transformdate =& CreateObject('felamimail.transformdate'); + //$htmlFilter =& CreateObject('felamimail.htmlfilter'); + //$uiWidgets =& CreateObject('felamimail.uiwidgets'); + // (regis) seems to be necessary to reopen... + $this->bofelamimail->reopen($this->mailbox); + #$headers = $this->bofelamimail->getMessageHeader($this->mailbox, $this->uid, $partID); + $rawheaders = $this->bofelamimail->getMessageRawHeader($this->uid, $partID); + + $webserverURL = $GLOBALS['egw_info']['server']['webserver_url']; + + #$nonDisplayAbleCharacters = array('[\016]','[\017]', + # '[\020]','[\021]','[\022]','[\023]','[\024]','[\025]','[\026]','[\027]', + # '[\030]','[\031]','[\032]','[\033]','[\034]','[\035]','[\036]','[\037]'); + + #print "
    ";print_r($rawheaders);print"
    ";exit; + + // add line breaks to $rawheaders + $newRawHeaders = explode("\n",$rawheaders); + reset($newRawHeaders); + + // reset $rawheaders + $rawheaders = ""; + // create it new, with good line breaks + reset($newRawHeaders); + while(list($key,$value) = @each($newRawHeaders)) { + $rawheaders .= wordwrap($value, 90, "\n "); + } + + $this->bofelamimail->closeConnection(); + + header('Content-type: text/html; charset=iso-8859-1'); + print '
    '. htmlspecialchars($rawheaders, ENT_NOQUOTES, 'iso-8859-1') .'
    '; + + } + + function displayAttachments() + { + $partID = $_GET['part']; + if (!empty($_GET['mailbox'])) $this->mailbox = base64_decode($_GET['mailbox']); + $nonDisplayAbleCharacters = array('[\016]','[\017]', + '[\020]','[\021]','[\022]','[\023]','[\024]','[\025]','[\026]','[\027]', + '[\030]','[\031]','[\032]','[\033]','[\034]','[\035]','[\036]','[\037]'); + + //$transformdate =& CreateObject('felamimail.transformdate'); + //$htmlFilter =& CreateObject('felamimail.htmlfilter'); + // (regis) seems to be necessary to reopen... + $this->bofelamimail->reopen($this->mailbox); + $headers = $this->bofelamimail->getMessageHeader($this->uid, $partID); + $envelope = $this->bofelamimail->getMessageEnvelope($this->uid, $partID); + if (PEAR::isError($headers)) { + print lang("ERROR: Message could not be displayed.")."
    "; + print "In Mailbox: $this->mailbox, with ID: $this->uid, and PartID: $partID
    "; + print $headers->message."
    "; + _debug_array($headers->backtrace[0]); + exit; + } + $attachments = $this->bofelamimail->getMessageAttachments($this->uid, $partID); + #_debug_array($attachments); exit; + + $this->display_app_header(); + $this->t->set_file(array("displayMsg" => "view_attachments.tpl")); + $this->t->set_var('charset',$GLOBALS['egw']->translation->charset()); + $this->t->set_block('displayMsg','message_main_attachment'); + $this->t->set_block('displayMsg','message_attachement_row'); + $this->bofelamimail->closeConnection(); + + $this->t->egroupware_hack = False; + + $this->translate(); + $this->t->set_var("subject_data", + @htmlspecialchars($this->bofelamimail->decode_subject(preg_replace($nonDisplayAbleCharacters,'',$envelope['SUBJECT'])), + ENT_QUOTES,$this->displayCharset)); + + // attachments + if(is_array($attachments) && count($attachments) > 0) { + $this->t->set_var('attachment_count',count($attachments)); + } else { + $this->t->set_var('attachment_count','0'); + } + + if (is_array($attachments) && count($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->set_var('url_img_save',html::image('felamimail','fileexport', lang('save'))); + $url_img_vfs = html::image('filemanager','navbar', lang('Filemanager'), ' height="16"'); + $url_img_vfs_save_all = html::image('felamimail','save_all', lang('Save all')); + #$this->t->parse('attachment_rows','attachment_row_bold',True); + + $detectedCharSet=$charset2use=$this->displayCharset; + foreach ($attachments as $key => $value) + { + #$detectedCharSet = mb_detect_encoding($value['name'].'a',strtoupper($this->displayCharset).",UTF-8, ISO-8559-1"); + if (function_exists('mb_convert_variables')) mb_convert_variables("UTF-8","ISO-8559-1",$value['name']); # iso 2 UTF8 + //if (mb_convert_variables("ISO-8859-1","UTF-8",$value['name'])){echo "Juhu utf8 2 ISO\n";}; + //echo $value['name']."\n"; + $filename=htmlentities($value['name'], ENT_QUOTES, $detectedCharSet); + + $this->t->set_var('row_color',$this->rowColor[($key+1)%2]); + $this->t->set_var('filename',($value['name'] ? ( $filename ? $filename : $value['name'] ) : lang('(no subject)'))); + $this->t->set_var('mimetype',mime_magic::mime2label($value['mimeType'])); + $this->t->set_var('size',egw_vfs::hsize($value['size'])); + $this->t->set_var('attachment_number',$key); + + switch(strtoupper($value['mimeType'])) + { + case 'MESSAGE/RFC822': + $linkData = array + ( + 'menuaction' => 'felamimail.uidisplay.display', + 'uid' => $this->uid, + 'part' => $value['partID'], + 'mailbox' => base64_encode($this->mailbox), + 'is_winmail' => $value['is_winmail'] + ); + $windowName = 'displayMessage_'. $this->uid.'_'.$value['partID']; + $linkView = "egw_openWindowCentered('".$GLOBALS['egw']->link('/index.php',$linkData)."','$windowName',700,screen.availHeight-50);"; + break; + case 'IMAGE/JPEG': + case 'IMAGE/PNG': + case 'IMAGE/GIF': + case 'IMAGE/BMP': + case 'APPLICATION/PDF': + case 'TEXT/PLAIN': + case 'TEXT/HTML': + case 'TEXT/CALENDAR': + case 'TEXT/X-VCALENDAR': + case 'TEXT/X-VCARD': + $linkData = array + ( + 'menuaction' => 'felamimail.uidisplay.getAttachment', + 'uid' => $this->uid, + 'part' => $value['partID'], + 'is_winmail' => $value['is_winmail'], + 'mailbox' => base64_encode($this->mailbox), + ); + $windowName = 'displayAttachment_'. $this->uid; + $reg = '800x600'; + // handle calendar/vcard + if (strtoupper($value['mimeType'])=='TEXT/CALENDAR' || strtoupper($value['mimeType'])=='TEXT/X-VCALENDAR') + { + $windowName = 'displayEvent_'. $this->uid; + $reg2 = egw_link::get_registry('calendar','view_popup'); + } + if (strtoupper($value['mimeType'])=='TEXT/X-VCARD') + { + $windowName = 'displayContact_'. $this->uid; + $reg2 = egw_link::get_registry('addressbook','add_popup'); + } + // apply to action + list($width,$height) = explode('x',(!empty($reg2) ? $reg2 : $reg)); + $linkView = "egw_openWindowCentered('".$GLOBALS['egw']->link('/index.php',$linkData)."','$windowName',$width,$height);"; + break; + default: + $linkData = array + ( + 'menuaction' => 'felamimail.uidisplay.getAttachment', + 'uid' => $this->uid, + 'part' => $value['partID'], + 'is_winmail' => $value['is_winmail'], + 'mailbox' => base64_encode($this->mailbox), + ); + $linkView = "window.location.href = '".$GLOBALS['egw']->link('/index.php',$linkData)."';"; + break; + } + $this->t->set_var("link_view",$linkView); + $this->t->set_var("target",$target); + + $linkData = array + ( + 'menuaction' => 'felamimail.uidisplay.getAttachment', + 'mode' => 'save', + 'uid' => $this->uid, + 'part' => $value['partID'], + 'is_winmail' => $value['is_winmail'], + 'mailbox' => base64_encode($this->mailbox), + ); + $this->t->set_var("link_save",$GLOBALS['egw']->link('/index.php',$linkData)); + + if ($GLOBALS['egw_info']['user']['apps']['filemanager']) + { + $link_vfs_save = egw::link('/index.php',array( + 'menuaction' => 'filemanager.filemanager_select.select', + 'mode' => 'saveas', + 'name' => $value['name'], + 'mime' => strtolower($value['mimeType']), + 'method' => 'felamimail.uidisplay.vfsSaveAttachment', + 'id' => $this->mailbox.'::'.$this->uid.'::'.$value['partID'].'::'.$value['is_winmail'], + 'label' => lang('Save'), + )); + $vfs_save = "$url_img_vfs"; + // add save-all icon for first attachment + if (!$key && count($attachments) > 1) + { + foreach ($attachments as $key => $value) + { + $ids["id[$key]"] = $this->mailbox.'::'.$this->uid.'::'.$value['partID'].'::'.$value['is_winmail'].'::'.$value['name']; + } + $link_vfs_save = egw::link('/index.php',array( + 'menuaction' => 'filemanager.filemanager_select.select', + 'mode' => 'select-dir', + 'method' => 'felamimail.uidisplay.vfsSaveAttachment', + 'label' => lang('Save all'), + )+$ids); + $vfs_save .= "\n$url_img_vfs_save_all"; + } + $this->t->set_var('vfs_save',$vfs_save); + } + else + { + $this->t->set_var('vfs_save',''); + } + $this->t->parse('attachment_rows','message_attachement_row',True); + } + } else { + $this->t->set_var('attachment_rows',''); + } + + $this->t->pparse('out','message_main_attachment'); + + } + + function displayImage() + { + $cid = base64_decode($_GET['cid']); + $partID = urldecode($_GET['partID']); + if (!empty($_GET['mailbox'])) $this->mailbox = base64_decode($_GET['mailbox']); + + $this->bofelamimail->reopen($this->mailbox); + + $attachment = $this->bofelamimail->getAttachmentByCID($this->uid, $cid, $partID); + + $this->bofelamimail->closeConnection(); + + $GLOBALS['egw']->session->commit_session(); + + if(is_array($attachment)) { + //error_log("Content-Type: ".$attachment['type']."; name=\"". $attachment['filename'] ."\""); + header ("Content-Type: ". strtolower($attachment['type']) ."; name=\"". $attachment['filename'] ."\""); + header ('Content-Disposition: inline; filename="'. $attachment['filename'] .'"'); + header("Expires: 0"); + // the next headers are for IE and SSL + header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); + header("Pragma: public"); + + echo trim($attachment['attachment']); + exit; + } + + $GLOBALS['egw']->common->egw_exit(); + + exit; + } + + function display_app_header($printing = NULL) + { + if ($_GET['menuaction'] != 'felamimail.uidisplay.printMessage' && + $_GET['menuaction'] != 'felamimail.uidisplay.displayBody' && + $_GET['menuaction'] != 'felamimail.uidisplay.displayAttachments' && + empty($printing)) + { + $GLOBALS['egw']->js->validate_file('tabs','tabs'); + $GLOBALS['egw']->js->validate_file('jscode','view_message','felamimail'); + $GLOBALS['egw']->js->set_onload('javascript:initAll();'); + } + + if(($_GET['menuaction'] == 'felamimail.uidisplay.printMessage') || (!empty($printing) && $printing == 1)) { + $GLOBALS['egw']->js->set_onload('javascript:updateTitle();javascript:window.print();'); + } + + if($_GET['menuaction'] == 'felamimail.uidisplay.printMessage' || (!empty($printing) && $printing == 1) || + $_GET['menuaction'] == 'felamimail.uidisplay.displayBody' || + $_GET['menuaction'] == 'felamimail.uidisplay.displayAttachments' ) { + $GLOBALS['egw_info']['flags']['nofooter'] = true; + } + $GLOBALS['egw_info']['flags']['include_xajax'] = True; + $GLOBALS['egw']->common->egw_header(); + } + + static function emailAddressToHTML($_emailAddress, $_organisation='', $allwaysShowMailAddress=false, $showAddToAdrdessbookLink=true) { + #_debug_array($_emailAddress); + // create some nice formated HTML for senderaddress + #if($_emailAddress['EMAIL'] == 'undisclosed-recipients: ;') + # return $_emailAddress['EMAIL']; + + #$addressData = imap_rfc822_parse_adrlist + # ($this->bofelamimail->decode_header($_emailAddress),''); + if(is_array($_emailAddress)) { + $senderAddress = ''; + foreach($_emailAddress as $addressData) { + #_debug_array($addressData); + if($addressData['MAILBOX_NAME'] == 'NIL') { + continue; + } + + if(!empty($senderAddress)) $senderAddress .= ', '; + + if(strtolower($addressData['MAILBOX_NAME']) == 'undisclosed-recipients') { + $senderAddress .= 'undisclosed-recipients'; + continue; + } + + if($addressData['PERSONAL_NAME'] != 'NIL') { + $newSenderAddress = $addressData['RFC822_EMAIL'] != 'NIL' ? $addressData['RFC822_EMAIL'] : $addressData['EMAIL']; + $newSenderAddress = bofelamimail::decode_header($newSenderAddress); + $decodedPersonalName = bofelamimail::decode_header($addressData['PERSONAL_NAME']); + + $realName = $decodedPersonalName; + // add mailaddress + if ($allwaysShowMailAddress) { + $realName .= ' <'.$addressData['EMAIL'].'>'; + } + // add organization + if(!empty($_organisation)) { + $realName .= ' ('. $_organisation . ')'; + } + + $linkData = array ( + 'menuaction' => 'felamimail.uicompose.compose', + 'send_to' => base64_encode($newSenderAddress) + ); + $link = $GLOBALS['egw']->link('/index.php',$linkData); + $senderAddress .= sprintf('%s', + $link, + @htmlentities($newSenderAddress,ENT_QUOTES,bofelamimail::$displayCharset), + @htmlentities($realName, ENT_QUOTES, bofelamimail::$displayCharset)); + + $linkData = array ( + 'menuaction' => 'addressbook.addressbook_ui.edit', + 'presets[email]' => $addressData['EMAIL'], + 'presets[org_name]' => $_organisation, + 'referer' => $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'] + ); + if (!empty($decodedPersonalName)) { + if($spacePos = strrpos($decodedPersonalName, ' ')) { + $linkData['presets[n_family]'] = substr($decodedPersonalName, $spacePos+1); + $linkData['presets[n_given]'] = substr($decodedPersonalName, 0, $spacePos); + } else { + $linkData['presets[n_family]'] = $decodedPersonalName; + } + $linkData['presets[n_fn]'] = $decodedPersonalName; + } + if ($showAddToAdrdessbookLink && $GLOBALS['egw_info']['user']['apps']['addressbook']) { + $urlAddToAddressbook = $GLOBALS['egw']->link('/index.php',$linkData); + $onClick = "window.open(this,this.target,'dependent=yes,width=850,height=440,location=no,menubar=no,toolbar=no,scrollbars=yes,status=yes'); return false;"; + $image = $GLOBALS['egw']->common->image('felamimail','sm_envelope'); + $senderAddress .= sprintf(' + %s', + $urlAddToAddressbook, + $onClick, + $image, + lang('add to addressbook'), + lang('add to addressbook')); + } + } else { + $linkData = array ( + 'menuaction' => 'felamimail.uicompose.compose', + 'send_to' => base64_encode($addressData['EMAIL']) + ); + $link = $GLOBALS['egw']->link('/index.php',$linkData); + $senderAddress .= sprintf('%s', + $link,@htmlentities($addressData['EMAIL'], ENT_QUOTES, bofelamimail::$displayCharset)); + //TODO: This uses old addressbook code, which should be removed in Version 1.4 + //Please use addressbook.addressbook_ui.edit with proper paramenters + $linkData = array + ( + 'menuaction' => 'addressbook.addressbook_ui.edit', + 'presets[email]' => $addressData['EMAIL'], + 'presets[org_name]' => $_organisation, + 'referer' => $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'] + ); + + if ($showAddToAdrdessbookLink && $GLOBALS['egw_info']['user']['apps']['addressbook']) { + $urlAddToAddressbook = $GLOBALS['egw']->link('/index.php',$linkData); + $onClick = "window.open(this,this.target,'dependent=yes,width=850,height=440,location=no,menubar=no,toolbar=no,scrollbars=yes,status=yes'); return false;"; + $image = $GLOBALS['egw']->common->image('felamimail','sm_envelope'); + $senderAddress .= sprintf(' + %s', + $urlAddToAddressbook, + $onClick, + $image, + lang('add to addressbook'), + lang('add to addressbook')); + } + } + } + + return $senderAddress; + } + + // if something goes wrong, just return the original address + return $_emailAddress; + } + + /** + * Save an attachment in the vfs + * + * @param string|array $ids '::' delemited mailbox::uid::part-id::is_winmail::name (::name for multiple id's) + * @param string $path path in vfs (no egw_vfs::PREFIX!), only directory for multiple id's ($ids is an array) + * @return string javascript eg. to close the selector window + */ + function vfsSaveAttachment($ids,$path) + { + //return "alert('".__METHOD__.'("'.array2string($id).'","'.$path."\")'); window.close();"; + + if (is_array($ids) && !egw_vfs::is_writable($path) || !is_array($ids) && !egw_vfs::is_writable(dirname($path))) + { + return 'alert("'.addslashes(lang('%1 is NOT writable by you!',$path)).'"); window.close();'; + } + foreach((array)$ids as $id) + { + list($this->mailbox,$this->uid,$part,$is_winmail,$name) = explode('::',$id,5); + if ($mb != $this->mailbox) $this->bofelamimail->reopen($mb = $this->mailbox); + $attachment = $this->bofelamimail->getAttachment($this->uid,$part,$is_winmail); + + if (!($fp = egw_vfs::fopen($file=$path.($name ? '/'.$name : ''),'wb')) || + !fwrite($fp,$attachment['attachment'])) + { + $err .= 'alert("'.addslashes(lang('Error saving %1!',$file)).'");'; + } + if ($fp) fclose($fp); + } + $this->bofelamimail->closeConnection(); + + return $err.'window.close();'; + } + + function getAttachment() + { + + $part = $_GET['part']; + $is_winmail = $_GET['is_winmail'] ? $_GET['is_winmail'] : 0; + if (!empty($_GET['mailbox'])) $this->mailbox = base64_decode($_GET['mailbox']); + + $this->bofelamimail->reopen($this->mailbox); + #$attachment = $this->bofelamimail->getAttachment($this->uid,$part); + $attachment = $this->bofelamimail->getAttachment($this->uid,$part,$is_winmail); + $this->bofelamimail->closeConnection(); + + $GLOBALS['egw']->session->commit_session(); + if ($_GET['mode'] != "save") + { + //error_log(__METHOD__.print_r($attachment,true)); + if (strtoupper($attachment['type']) == 'TEXT/CALENDAR' || strtoupper($attachment['type']) == 'TEXT/X-VCALENDAR') + { + //error_log(__METHOD__."about to call calendar_ical"); + $calendar_ical = new calendar_ical(); + $eventid = $calendar_ical->search($attachment['attachment'],-1); + //error_log(__METHOD__.array2string($eventid)); + if (!$eventid) $eventid = -1; + $event = $calendar_ical->importVCal($attachment['attachment'],(is_array($eventid)?$eventid[0]:$eventid),null,true); + //error_log(__METHOD__.$event); + if ((int)$event > 0) + { + $vars = array( + 'menuaction' => 'calendar.calendar_uiforms.edit', + 'cal_id' => $event, + ); + $GLOBALS['egw']->redirect_link('../index.php',$vars); + } + //Import failed, download content anyway + } + if (strtoupper($attachment['type']) == 'TEXT/X-VCARD') + { + $addressbook_vcal = new addressbook_vcal(); + $vcard = $addressbook_vcal->vcardtoegw($attachment['attachment']); + //error_log(print_r($vcard,true)); + if ($vcard['uid']) $contact = $addressbook_vcal->find_contact($vcard,false); + if (!$contact) $contact = null; + // if there are not enough fields in the vcard (or the parser was unable to correctly parse the vcard (as of VERSION:3.0 created by MSO)) + if ($contact || count($vcard)>2) $contact = $addressbook_vcal->addVCard($attachment['attachment'],$contact,true); + //error_log(__METHOD__.$contact); + if ((int)$contact > 0) + { + $vars = array( + 'menuaction' => 'addressbook.addressbook_ui.edit', + 'contact_id' => $contact, + ); + $GLOBALS['egw']->redirect_link('../index.php',$vars); + } + //Import failed, download content anyway + } + } + header ("Content-Type: ".$attachment['type']."; name=\"". $attachment['filename'] ."\""); + if($_GET['mode'] == "save") { + // ask for download + header ("Content-Disposition: attachment; filename=\"". $attachment['filename'] ."\""); + } else { + // display it + header ("Content-Disposition: inline; filename=\"". $attachment['filename'] ."\""); + } + header("Expires: 0"); + // the next headers are for IE and SSL + header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); + header("Pragma: public"); + + echo $attachment['attachment']; + + $GLOBALS['egw']->common->egw_exit(); + exit; + } + + function &getdisplayableBody($_bodyParts) + { + $bodyParts = $_bodyParts; + + $webserverURL = $GLOBALS['egw_info']['server']['webserver_url']; + + $nonDisplayAbleCharacters = array('[\016]','[\017]', + '[\020]','[\021]','[\022]','[\023]','[\024]','[\025]','[\026]','[\027]', + '[\030]','[\031]','[\032]','[\033]','[\034]','[\035]','[\036]','[\037]'); + + $body = ''; + + //error_log(__METHOD__.array2string($bodyParts)); //exit; + + foreach($bodyParts as $singleBodyPart) { + if (!isset($singleBodyPart['body'])) { + $singleBodyPart['body'] = $this->getdisplayableBody($singleBodyPart); + $body .= $singleBodyPart['body']; + continue; + } + if(!empty($body)) { + $body .= '
    '; + } + #_debug_array($singleBodyPart['charSet']); + #_debug_array($singleBodyPart['mimeType']); + //error_log($singleBodyPart['body']); + // some characterreplacements, as they fail to translate + $sar = array( + '@(\x84|\x93|\x94)@', + '@(\x96|\x97)@', + '@(\x82|\x91|\x92)@', + '@(\x85)@', + '@(\x86)@', + ); + $rar = array( + '"', + '-', + '\'', + '...', + '+', + ); + if($singleBodyPart['mimeType'] == 'text/html' && strtoupper($singleBodyPart['charSet']) != 'UTF-8') $singleBodyPart['body'] = preg_replace($sar,$rar,$singleBodyPart['body']); + $singleBodyPart['body'] = $GLOBALS['egw']->translation->convert( + $singleBodyPart['body'], + strtolower($singleBodyPart['charSet']) + ); + //error_log($singleBodyPart['body']); + #$CharSetUsed = mb_detect_encoding($singleBodyPart['body'] . 'a' , strtoupper($singleBodyPart['charSet']).','.strtoupper($this->displayCharset).',UTF-8, ISO-8859-1'); + + if($singleBodyPart['mimeType'] == 'text/plain') + { + //$newBody = $singleBodyPart['body']; + + $newBody = @htmlentities($singleBodyPart['body'],ENT_QUOTES, strtoupper($this->displayCharset)); + // if empty and charset is utf8 try sanitizing the string in question + if (empty($newBody) && strtolower($singleBodyPart['charSet'])=='utf-8') $newBody = @htmlentities(iconv('utf-8', 'utf-8', $singleBodyPart['body']),ENT_QUOTES, strtoupper($this->displayCharset)); + // if the conversion to htmlentities fails somehow, try without specifying the charset, which defaults to iso- + if (empty($newBody)) $newBody = htmlentities($singleBodyPart['body'],ENT_QUOTES); + #$newBody = $this->bofelamimail->wordwrap($newBody, 90, "\n"); + + // search http[s] links and make them as links available again + // to understand what's going on here, have a look at + // http://www.php.net/manual/en/function.preg-replace.php + + // create links for websites + $newBody = html::activate_links($newBody); + // redirect links for websites if you use no cookies + #if (!($GLOBALS['egw_info']['server']['usecookies'])) + # $newBody = preg_replace("/href=(\"|\')((http(s?):\/\/)|(www\.))([\w,\-,\/,\?,\=,\.,&,!\n,\%,@,\(,\),\*,#,:,~,\+]+)(\"|\')/ie", + # "'href=\"$webserverURL/redirect.php?go='.@htmlentities(urlencode('http$4://$5$6'),ENT_QUOTES,\"$this->displayCharset\").'\"'", $newBody); + + // create links for email addresses + $this->parseEmail($newBody); + $newBody = $this->highlightQuotes($newBody); + // to display a mailpart of mimetype plain/text, may be better taged as preformatted + #$newBody = nl2br($newBody); + // since we do not display the message as HTML anymore we may want to insert good linebreaking (for visibility). + //error_log($newBody); + // dont break lines that start with > (> as the text was processed with htmlentities before) + $newBody = "
    ".bofelamimail::wordwrap($newBody,90,"\n",'>')."
    "; + //$newBody = "
    ".$newBody."
    "; + } + else + { + $newBody = $singleBodyPart['body']; + $newBody = $this->highlightQuotes($newBody); + #error_log(print_r($newBody,true)); + + // do the cleanup, set for the use of purifier + $usepurifier = true; + bofelamimail::getCleanHTML($newBody,$usepurifier); + // removes stuff between http and ?http + $Protocol = '(http:\/\/|(ftp:\/\/|https:\/\/))'; // only http:// gets removed, other protocolls are shown + $newBody = preg_replace('~'.$Protocol.'[^>]*\?'.$Protocol.'~sim','$1',$newBody); // removes stuff between http:// and ?http:// + // spamsaver emailaddress, needed to be able to apply email compose links later + $newBody = preg_replace('/'.'(?\\1 AT \\2 DOT \\3', + $newBody); + + // redirect links for websites if you use no cookies + #if (!($GLOBALS['egw_info']['server']['usecookies'])) { //do it all the time, since it does mask the mailadresses in urls + $this->parseHREF($newBody); + #} + // create links for inline images + $linkData = array ( + 'menuaction' => 'felamimail.uidisplay.displayImage', + 'uid' => $this->uid, + 'mailbox' => base64_encode($this->mailbox) + ); + $imageURL = $GLOBALS['egw']->link('/index.php', $linkData); + if ($this->partID) { + $newBody = preg_replace("/src=(\"|\')cid:(.*)(\"|\')/iUe", + "'src=\"$imageURL&cid='.base64_encode('$2').'&partID='.urlencode($this->partID).'\"'", $newBody); + } else { + $newBody = preg_replace("/src=(\"|\')cid:(.*)(\"|\')/iUe", + "'src=\"$imageURL&cid='.base64_encode('$2').'&partID='.'\"'", $newBody); + } + + // create links for email addresses + $linkData = array + ( + 'menuaction' => 'felamimail.uicompose.compose' + ); + $link = $GLOBALS['egw']->link('/index.php',$linkData); + $newBody = preg_replace("/href=(\"|\')mailto:([\w,\-,\/,\?,\=,\.,&,!\n,\%,@,\*,#,:,~,\+]+)(\"|\')/ie", + "'href=\"$link&send_to='.base64_encode('$2').'\"'", $newBody); + #print "
    ".htmlentities($newBody)."

    "; + + // replace emails within the text with clickable links. + $this->parseEmail($newBody); + } + $body .= $newBody; + #print "
    $body

    "; + } + + // create links for windows shares + // \\\\\\\\ == '\\' in real life!! :) + $body = preg_replace("/(\\\\\\\\)([\w,\\\\,-]+)/i", + "$1$2", $body); + + $body = preg_replace($nonDisplayAbleCharacters,'',$body); + + return $body; + } + + function printMessage($messageId = NULL, $callfromcompose = NULL) + { + if (!empty($messageId) && empty($this->uid)) $this->uid = $messageId; + $partID = $_GET['part']; + if (!empty($_GET['folder'])) $this->mailbox = base64_decode($_GET['folder']); + + //$transformdate =& CreateObject('felamimail.transformdate'); + //$htmlFilter =& CreateObject('felamimail.htmlfilter'); + //$uiWidgets =& CreateObject('felamimail.uiwidgets'); + // (regis) seems to be necessary to reopen... + $folder = $this->mailbox; + // the folder for callfromcompose is hardcoded, because the message to be printed from the compose window is saved as draft, and can be + // reopened for composing (only) from there + if ($callfromcompose) + { + if (isset($this->mailPreferences->preferences['draftFolder']) && + $this->mailPreferences->preferences['draftFolder'] != 'none') + { + $folder = $this->mailPreferences->preferences['draftFolder']; + } + else + { + $folder = $GLOBALS['egw_info']['user']['preferences']['felamimail']['draftFolder']; + } + } + $this->bofelamimail->reopen($folder); +# print "$this->mailbox, $this->uid, $partID
    "; + $headers = $this->bofelamimail->getMessageHeader($this->uid, $partID); + $envelope = $this->bofelamimail->getMessageEnvelope($this->uid, $partID); +# _debug_array($headers);exit; + $rawheaders = $this->bofelamimail->getMessageRawHeader($this->uid, $partID); + $bodyParts = $this->bofelamimail->getMessageBody($this->uid,'',$partID); + $attachments = $this->bofelamimail->getMessageAttachments($this->uid,$partID); +# _debug_array($nextMessage); exit; + + $webserverURL = $GLOBALS['egw_info']['server']['webserver_url']; + + $nonDisplayAbleCharacters = array('[\016]','[\017]', + '[\020]','[\021]','[\022]','[\023]','[\024]','[\025]','[\026]','[\027]', + '[\030]','[\031]','[\032]','[\033]','[\034]','[\035]','[\036]','[\037]'); + + #print "
    ";print_r($rawheaders);print"
    ";exit; + + // add line breaks to $rawheaders + $newRawHeaders = explode("\n",$rawheaders); + reset($newRawHeaders); + + // find the Organization header + // the header can also span multiple rows + while(is_array($newRawHeaders) && list($key,$value) = each($newRawHeaders)) { + #print $value."
    "; + if(preg_match("/Organization: (.*)/",$value,$matches)) { + $organization = $this->bofelamimail->decode_header(chop($matches[1])); + continue; + } + if(!empty($organization) && preg_match("/^\s+(.*)/",$value,$matches)) { + $organization .= $this->bofelamimail->decode_header(chop($matches[1])); + break; + } elseif(!empty($organization)) { + break; + } + } + + $this->bofelamimail->closeConnection(); + + $this->display_app_header($callfromcompose); + $this->t->set_file(array("displayMsg" => "view_message_printable.tpl")); + # $this->t->set_var('charset',$GLOBALS['egw']->translation->charset()); + + $this->t->set_block('displayMsg','message_main'); + # $this->t->set_block('displayMsg','message_main_attachment'); + $this->t->set_block('displayMsg','message_header'); + # $this->t->set_block('displayMsg','message_raw_header'); + # $this->t->set_block('displayMsg','message_navbar'); + $this->t->set_block('displayMsg','message_onbehalfof'); + $this->t->set_block('displayMsg','message_cc'); + $this->t->set_block('displayMsg','message_attachement_row'); + # $this->t->set_block('displayMsg','previous_message_block'); + # $this->t->set_block('displayMsg','next_message_block'); + $this->t->set_block('displayMsg','message_org'); + + # $this->t->egroupware_hack = False; + + $this->translate(); + + if($envelope['FROM'][0] != $envelope['SENDER'][0]) { + $senderAddress = self::emailAddressToHTML($envelope['SENDER'], '', true, false); + $fromAddress = self::emailAddressToHTML($envelope['FROM'], $organization, true, false); + $this->t->set_var("from_data",$senderAddress); + $this->t->set_var("onbehalfof_data",$fromAddress); + $this->t->parse('on_behalf_of_part','message_onbehalfof',True); + } else { + $fromAddress = self::emailAddressToHTML($envelope['FROM'], $organization, true, false); + $this->t->set_var("from_data", $fromAddress); + $this->t->set_var('on_behalf_of_part',''); + } + + // parse the to header + $toAddress = self::emailAddressToHTML($envelope['TO'], '', true, false); + $this->t->set_var("to_data",$toAddress); + + // parse the cc header + if(count($envelope['CC'])) { + $ccAddress = self::emailAddressToHTML($envelope['CC'], '', true, false); + $this->t->set_var("cc_data",$ccAddress); + $this->t->parse('cc_data_part','message_cc',True); + } else { + $this->t->set_var("cc_data_part",''); + } + $this->t->set_var("date_data", + @htmlspecialchars(bofelamimail::_strtotime($headers['DATE'],$GLOBALS['egw_info']['user']['preferences']['common']['dateformat']).' - '.bofelamimail::_strtotime($headers['DATE'],'H:i:s'), ENT_QUOTES,$this->displayCharset)); + + // link to go back to the message view. the link differs if the print was called from a normal viewing window, or from compose + $subject = @htmlspecialchars($this->bofelamimail->decode_subject(preg_replace($nonDisplayAbleCharacters, '', $envelope['SUBJECT'])), ENT_QUOTES, $this->displayCharset); + $this->t->set_var("subject_data", $subject); + $this->t->set_var("full_subject_data", $subject); + $linkData = array ( + 'menuaction' => 'felamimail.uidisplay.display', + 'showHeader' => 'false', + 'mailbox' => base64_encode($folder), + 'uid' => $this->uid, + 'id' => $this->id, + ); + if ($callfromcompose) { + $linkData['menuaction'] = 'felamimail.uicompose.composeFromDraft'; + $linkData['folder'] = base64_encode($folder); + } + $_readInNewWindow = $this->mailPreferences->preferences['message_newwindow']; + $this->t->set_var('url_read_message', $GLOBALS['egw']->link('/index.php',$linkData)); + + $target = 'displayMessage'; + $windowName = ($_readInNewWindow == 1 ? $target : $target.'_'.$this->uid); + #if ($callfromcompose) $target = 'composeFromDraft'; + if ($callfromcompose) $windowName = '_top'; + $this->t->set_var('read_message_windowName', $windowName); + + //if(isset($organization)) exit; + $this->t->parse("header","message_header",True); + + $this->t->set_var('body', $this->getdisplayableBody($bodyParts)); + + // attachments + if(is_array($attachments)) + $this->t->set_var('attachment_count',count($attachments)); + else + $this->t->set_var('attachment_count','0'); + + if (is_array($attachments) && count($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->set_var('url_img_save',$GLOBALS['egw']->common->image('felamimail','fileexport')); + #$this->t->parse('attachment_rows','attachment_row_bold',True); + foreach ($attachments as $key => $value) { + $this->t->set_var('row_color',$this->rowColor[($key+1)%2]); + $this->t->set_var('filename',@htmlentities($this->bofelamimail->decode_header($value['name']),ENT_QUOTES,$this->displayCharset)); + $this->t->set_var('mimetype',$value['mimeType']); + $this->t->set_var('size',$value['size']); + $this->t->set_var('attachment_number',$key); + + switch(strtolower($value['mimeType'])) + { + case 'message/rfc822': + $linkData = array + ( + 'menuaction' => 'felamimail.uidisplay.display', + 'uid' => $this->uid, + 'part' => $value['partID'], + 'mailbox' => base64_encode($folder), + ); + $windowName = 'displayMessage_'.$this->uid; + $linkView = "egw_openWindowCentered('".$GLOBALS['egw']->link('/index.php',$linkData)."','$windowName',700,egw_getWindowOuterHeight());"; + break; + case 'image/jpeg': + case 'image/png': + case 'image/gif': + case 'image/bmp': + #case 'application/pdf': + $linkData = array + ( + 'menuaction' => 'felamimail.uidisplay.getAttachment', + 'uid' => $this->uid, + 'part' => $value['partID'], + 'mailbox' => base64_encode($folder), + ); + $windowName = 'displayAttachment_'.$this->uid; + $linkView = "egw_openWindowCentered('".$GLOBALS['egw']->link('/index.php',$linkData)."','$windowName',800,600);"; + break; + default: + $linkData = array + ( + 'menuaction' => 'felamimail.uidisplay.getAttachment', + 'uid' => $this->uid, + 'part' => $value['partID'], + 'mailbox' => base64_encode($folder), + ); + $linkView = "window.location.href = '".$GLOBALS['egw']->link('/index.php',$linkData)."';"; + break; + } + $this->t->set_var("link_view",$linkView); + $this->t->set_var("target",$target); + + $linkData = array + ( + 'menuaction' => 'felamimail.uidisplay.getAttachment', + 'mode' => 'save', + 'uid' => $this->uid, + 'part' => $value['partID'], + 'mailbox' => base64_encode($folder), + ); + $this->t->set_var("link_save",$GLOBALS['egw']->link('/index.php',$linkData)); + + $this->t->parse('attachment_rows','message_attachement_row',True); + } + } + else + { + $this->t->set_var('attachment_rows',''); + } + + #$this->t->pparse("out","message_attachment_rows"); + + // print it out + # if(is_array($attachments)) { + # $this->t->pparse('out','message_main_attachment'); + # } else { + $this->t->pparse('out','message_main'); + # } + print ""; + + } + + function saveMessage() + { + $partID = $_GET['part']; + if (!empty($_GET['mailbox'])) $this->mailbox = base64_decode($_GET['mailbox']); + + // (regis) seems to be necessary to reopen... + $this->bofelamimail->reopen($this->mailbox); + + $message = $this->bofelamimail->getMessageRawBody($this->uid, $partID); + $headers = $this->bofelamimail->getMessageHeader($this->uid, $partID); + + $this->bofelamimail->closeConnection(); + + $GLOBALS['egw']->session->commit_session(); + + header ("Content-Type: message/rfc822; name=\"". $headers['SUBJECT'] .".eml\""); + header ("Content-Disposition: attachment; filename=\"". $headers['SUBJECT'] .".eml\""); + header("Expires: 0"); + // the next headers are for IE and SSL + header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); + header("Pragma: public"); + + echo $message; + + $GLOBALS['egw']->common->egw_exit(); + exit; + } + + function showHeader() + { + if($this->bofelamimail->sessionData['showHeader'] == 'True') + { + $this->bofelamimail->sessionData['showHeader'] = 'False'; + } + else + { + $this->bofelamimail->sessionData['showHeader'] = 'True'; + } + $this->bofelamimail->saveSessionData(); + + $this->display(); + } + + 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_from",lang('from')); + $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_search",lang('search')); + $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("lang_compose",lang('compose')); + $this->t->set_var("lang_date",lang('date')); + $this->t->set_var("lang_view",lang('view')); + $this->t->set_var("lang_organization",lang('organization')); + $this->t->set_var("lang_save",lang('save')); + $this->t->set_var("lang_printable",lang('print it')); + $this->t->set_var("lang_reply",lang('reply')); + $this->t->set_var("lang_reply_all",lang('reply all')); + $this->t->set_var("lang_forward",lang('forward')); + $this->t->set_var("lang_delete",lang('delete')); + $this->t->set_var("lang_previous_message",lang('previous message')); + $this->t->set_var("lang_next_message",lang('next message')); + $this->t->set_var("lang_organisation",lang('organisation')); + $this->t->set_var("lang_on_behalf_of",lang('on behalf of')); + $this->t->set_var("lang_Message", lang('Message')); + $this->t->set_var("lang_Attachment", lang('attachments')); + $this->t->set_var("lang_Header_Lines", lang('Header Lines')); + + $this->t->set_var("th_bg",$GLOBALS['egw_info']["theme"]["th_bg"]); + $this->t->set_var("bg01",$GLOBALS['egw_info']["theme"]["bg01"]); + $this->t->set_var("bg02",$GLOBALS['egw_info']["theme"]["bg02"]); + $this->t->set_var("bg03",$GLOBALS['egw_info']["theme"]["bg03"]); + } +} + +?> diff --git a/felamimail/inc/class.uiwidgets.inc.php b/felamimail/inc/class.uiwidgets.inc.php new file mode 100644 index 0000000000..a198817377 --- /dev/null +++ b/felamimail/inc/class.uiwidgets.inc.php @@ -0,0 +1,1019 @@ +template = $template; + $this->template->set_file(array("body" => 'uiwidgets.tpl')); + $this->charset = $GLOBALS['egw']->translation->charset(); + $this->bofelamimail =& CreateObject('felamimail.bofelamimail',$GLOBALS['egw']->translation->charset()); + if (!is_object($GLOBALS['egw']->html)) { + $GLOBALS['egw']->html = CreateObject('phpgwapi.html'); + } + } + + function encodeFolderName($_folderName) + { + return $GLOBALS['egw']->translation->convert($_folderName, 'UTF7-IMAP', $this->charset); + } + + /** + * create a folder tree + * + * this function will create a foldertree based on javascript + * on click the sorounding form gets submitted + * + * @param _folders array containing the list of folders + * @param _selected string containing the selected folder + * @param _selectedFolderCount integer contains the count of unread messages in the selected folder + * @param _topFolderName string containing the top folder name + * @param _topFolderDescription string containing the description for the top folder + * @param _formName string name of the sorounding form + * @param _hiddenVar string hidden form value, transports the selected folder + * @param _useDisplayCharset bool use displaycharset for foldernames (used by uisieve only) + * + * @return string the html code, to be added into the template + */ + function createHTMLFolder($_folders, $_selected, $_selectedFolderCount, $_topFolderName, $_topFolderDescription, $_divName, $_displayCheckBox, $_useDisplayCharset = false) { + $preferences = $this->bofelamimail->mailPreferences; + //_debug_array(bofelamimail::$autoFolders); + $userDefinedFunctionFolders = array(); + if (isset($preferences->preferences['trashFolder']) && + $preferences->preferences['trashFolder'] != 'none') $userDefinedFunctionFolders['Trash'] = $preferences->preferences['trashFolder']; + if (isset($preferences->preferences['sentFolder']) && + $preferences->preferences['sentFolder'] != 'none') $userDefinedFunctionFolders['Sent'] = $preferences->preferences['sentFolder']; + if (isset($preferences->preferences['draftFolder']) && + $preferences->preferences['draftFolder'] != 'none') $userDefinedFunctionFolders['Drafts'] = $preferences->preferences['draftFolder']; + if (isset($preferences->preferences['templateFolder']) && + $preferences->preferences['templateFolder'] != 'none') $userDefinedFunctionFolders['Templates'] = $preferences->preferences['templateFolder']; + // create a list of all folders, also the ones which are not subscribed + foreach($_folders as $key => $obj) { + $folderParts = explode($obj->delimiter,$key); + if(is_array($folderParts)) { + $partCount = count($folderParts); + $string = ''; + for($i = 0; $i < $partCount-1; $i++) { + if(!empty($string)) $string .= $obj->delimiter; + $string .= $folderParts[$i]; + if(!$allFolders[$string]) { + $allFolders[$string] = clone($obj); + $allFolders[$string]->folderName = $string; + $allFolders[$string]->shortFolderName = array_pop(explode($obj->delimiter, $string)); + $allFolders[$string]->displayName = $this->encodeFolderName($allFolders[$string]->folderName); + $allFolders[$string]->shortDisplayName = $this->encodeFolderName($allFolders[$string]->shortFolderName); + } + } + } + $allFolders[$key] = $obj; + } + + $folderImageDir = $GLOBALS['egw_info']['server']['webserver_url'].'/phpgwapi/templates/default/images/'; + + // careful! "d = new..." MUST be on a new line!!! + $folder_tree_new = ''; + $folder_tree_new .= ""; + + return $folder_tree_new; + } + + function createSignatureTable($_signatureList) + { + $linkData = array + ( + 'menuaction' => 'felamimail.uipreferences.editSignature' + ); + $urlEditSignature = $GLOBALS['egw']->link('/index.php',$linkData); + + if(is_array($_signatureList) && !empty($_signatureList)) { + foreach($_signatureList as $signature) { + $description = ($signature['fm_defaultsignature'] == true) ? $signature['fm_description'] .' ('. lang('default') .')' : $signature['fm_description']; + $tableRows[] = array( + '1' => $signature['fm_signatureid'] != -1 ? html::checkbox('signatureID', false, $signature['fm_signatureid']) : '', + '.1' => 'style="width:30px"', + '2' => ''. @htmlspecialchars($description, ENT_QUOTES, $this->charset) .'', + ); + } + + return html::table($tableRows, 'style="width:100%;"'); + } + + return ''; + } + + function createAccountDataTable($_identities) + { + $linkData = array + ( + 'menuaction' => 'felamimail.uipreferences.editAccountData' + ); + $urlEditAccountData = $GLOBALS['egw']->link('/index.php',$linkData); + + if(is_array($_identities) && !empty($_identities)) { + foreach($_identities as $identity) { + $description = $identity['id'].":".$identity['realName']." ".$identity['organization']." <".$identity['emailAddress'].">"; + $description = ($identity['default'] == true) ? $description .' ('. lang('default') .')' : $description; + $tableRows[] = array( + '1' => $identity['id'] != -1 ? html::checkbox('accountID', false, $identity['id']) : '', + '.1' => 'style="width:30px"', + '2' => ''. @htmlspecialchars($description, ENT_QUOTES, $this->charset) .'', + ); + } + + return html::table($tableRows, 'style="width:100%;"'); + } + + return ''; + } + + // $_folderType 0: normal imap folder 1: sent folder 2: draft folder 3: template folder + // $_rowStyle felamimail or outlook + function messageTable($_headers, $_folderType, $_folderName, $_readInNewWindow, $_rowStyle='felamimail',$messageToBePreviewed=0) + { + //error_log(__METHOD__); + $this->t = CreateObject('phpgwapi.Template',EGW_APP_TPL); + $this->t->set_file(array("body" => 'mainscreen.tpl')); + $this->t->set_block('body','header_row_felamimail'); + $this->t->set_block('body','header_row_outlook'); + $this->t->set_block('body','message_table'); + $timestamp7DaysAgo = + mktime(date("H"), date("i"), date("s"), date("m"), date("d")-7, date("Y")); + $timestampNow = + mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y")); + $dateToday = date("Y-m-d"); + + + $i=0; + $firstuid = null; + foreach((array)$_headers['header'] as $header) + { + //_debug_array($header); + #if($i<10) {$i++;continue;} + #if($i>20) {continue;} $i++; + // create the listing of subjects + $maxSubjectLength = 60; + $maxAddressLength = 20; + $maxSubjectLengthBold = 50; + $maxAddressLengthBold = 14; + + $flags = ""; + if(!empty($header['recent'])) $flags .= "R"; + if(!empty($header['flagged'])) $flags .= "F"; + if(!empty($header['answered'])) $flags .= "A"; + if(!empty($header['forwarded'])) $flags .= "W"; + if(!empty($header['deleted'])) $flags .= "D"; + if(!empty($header['seen'])) $flags .= "S"; + + $this->t->set_var('row_text', ''); + + // the status icon + if($header['deleted']) { + $this->t->set_var('image_url',html::image('felamimail','kmmsgdel')); + } elseif($header['recent']) { + $this->t->set_var('image_url',html::image('felamimail','kmmsgnew')); + } elseif($header['forwarded']) { + $this->t->set_var('image_url',html::image('felamimail','kmmsgforwarded')); + } elseif($header['answered']) { + $this->t->set_var('image_url',html::image('felamimail','kmmsgreplied')); + } elseif($header['seen']) { + $this->t->set_var('image_url',html::image('felamimail','kmmsgread')); + } else { + $this->t->set_var('image_url',html::image('felamimail','kmmsgunseen')); + } + + // the css for this row + if($header['deleted']) { + $this->t->set_var('row_css_class','header_row_D'); + } elseif($header['recent'] && !$header['seen']) { + $this->t->set_var('row_css_class','header_row_R'); + } elseif($header['flagged']) { + if($header['seen']) { + $this->t->set_var('row_css_class','header_row_FS'); + } else { + $this->t->set_var('row_css_class','header_row_F'); + } + } elseif($header['seen']) { + $this->t->set_var('row_css_class','header_row_S'); + } else { + $this->t->set_var('row_css_class','header_row_'); + } + + // filter out undisplayable characters + $search = array('[\016]','[\017]', + '[\020]','[\021]','[\022]','[\023]','[\024]','[\025]','[\026]','[\027]', + '[\030]','[\031]','[\032]','[\033]','[\034]','[\035]','[\036]','[\037]'); + $replace = ''; + + $header['subject'] = preg_replace($search,$replace,$header['subject']); + $header['subject'] = @htmlspecialchars($header['subject'],ENT_QUOTES,$this->displayCharset); + // curly brackets get messed up by the template! + $header['subject'] = str_replace(array('{','}'),array('{','}'),$header['subject']); + + if (!empty($header['subject'])) { + // make the subject shorter if it is to long + $fullSubject = $header['subject']; + #if(strlen($header['subject']) > $maxSubjectLength) + #{ + # $header['subject'] = substr($header['subject'],0,$maxSubjectLength)."..."; + #} + $this->t->set_var('header_subject', $header['subject']); + #$this->t->set_var('attachments', $header['attachment']); + $this->t->set_var('full_subject', $fullSubject); + } else { + $this->t->set_var('header_subject', @htmlspecialchars('('. lang('no subject') .')', ENT_QUOTES, $this->displayCharset)); + } + + #_debug_array($header); + if($header['mimetype'] == 'multipart/mixed' || + $header['mimetype'] == 'multipart/related' || + substr($header['mimetype'],0,11) == 'application' || + substr($header['mimetype'],0,5) == 'audio') { + $image = html::image('felamimail','attach'); + $this->t->set_var('attachment_image', $image); + } else { + $this->t->set_var('attachment_image', ' '); + } + // show priority flag + if ($header['priority'] < 3) { + $image = html::image('felamimail','prio_high'); + } elseif ($header['priority'] > 3) { + $image = html::image('felamimail','prio_low'); + } else { + $image = ''; + } + $this->t->set_var('prio_image', $image); + + if ($_folderType > 0) { + // sent or drafts or template folder + if (!empty($header['to_name'])) { + $sender_name = $header['to_name']; + $full_address = $header['to_name'].' <'.$header['to_address'].'>'; + } else { + $sender_name = $header['to_address']; + $full_address = $header['to_address']; + } + } else { + if (!empty($header['sender_name'])) { + $sender_name = $header['sender_name']; + $full_address = $header['sender_name'].' <'.$header['sender_address'].'>'; + } else { + $sender_name = $header['sender_address']; + $full_address = $header['sender_address']; + } + } + + $this->t->set_var('sender_name', @htmlspecialchars($sender_name, ENT_QUOTES, $this->charset)); + $this->t->set_var('full_address', @htmlspecialchars($full_address, ENT_QUOTES, $this->charset)); + + $this->t->set_var('message_counter', $i); + $this->t->set_var('message_uid', $header['uid']); + + if ($dateToday == bofelamimail::_strtotime($header['date'],'Y-m-d')) { + $this->t->set_var('date', bofelamimail::_strtotime($header['date'],'H:i:s')); //$GLOBALS['egw']->common->show_date($header['date'],'H:i:s')); + } else { + $this->t->set_var('date', bofelamimail::_strtotime($header['date'],$GLOBALS['egw_info']['user']['preferences']['common']['dateformat'])); + } + $this->t->set_var('datetime', bofelamimail::_strtotime($header['date'],$GLOBALS['egw_info']['user']['preferences']['common']['dateformat']). + ' - '.bofelamimail::_strtotime($header['date'],'H:i:s')); + + $this->t->set_var('size', $this->show_readable_size($header['size'])); + if ($firstuid === null) + { + //_debug_array($header); + $firstuid = $header['uid']; + $firstheader = $header; + } + if ($messageToBePreviewed>0 + && $GLOBALS['egw_info']['user']['preferences']['felamimail']['PreViewFrameHeight']>0 + && $messageToBePreviewed == $header['uid']) + { + //error_log(__METHOD__.$header['uid']); + $firstheader = $header; + } + if($_folderType == 2 || $_folderType == 3) { + $linkData = array ( + 'menuaction' => 'felamimail.uicompose.composeFromDraft', + 'icServer' => 0, + 'folder' => base64_encode($_folderName), + 'uid' => $header['uid'], + 'id' => $header['id'], + ); + $this->t->set_var('url_read_message', $GLOBALS['egw']->link('/index.php',$linkData)); + + $windowName = 'composeFromDraft_'.$header['uid']; + $this->t->set_var('read_message_windowName', $windowName); + $this->t->set_var('preview_message_windowName', $windowName); + } else { + # _debug_array($header); + $linkData = array ( + 'menuaction' => 'felamimail.uidisplay.display', + 'showHeader' => 'false', + 'mailbox' => base64_encode($_folderName), + 'uid' => $header['uid'], + 'id' => $header['id'], + ); + $this->t->set_var('url_read_message', $GLOBALS['egw']->link('/index.php',$linkData)); + + $windowName = ($_readInNewWindow == 1 ? 'displayMessage' : 'displayMessage_'.$header['uid']); + $this->t->set_var('read_message_windowName', $windowName); + + if ($GLOBALS['egw_info']['user']['preferences']['felamimail']['PreViewFrameHeight']>0) $windowName = 'MessagePreview_'.$header['uid'].'_'.$_folderType; + + $this->t->set_var('preview_message_windowName', $windowName); + } + + if($_folderType > 0) { + // sent or draft or template folder + if(!empty($header['to_name'])) { + list($mailbox, $host) = explode('@',$header['to_address']); + $senderAddress = imap_rfc822_write_address($mailbox, + $host, + $header['to_name']); + } else { + $senderAddress = $header['to_address']; + } + } else { + if(!empty($header['sender_name'])) { + list($mailbox, $host) = explode('@',$header['sender_address']); + $senderAddress = imap_rfc822_write_address($mailbox, + $host, + $header['sender_name']); + } else { + $senderAddress = $header['sender_address']; + } + } + + $linkData = array + ( + 'menuaction' => 'felamimail.uicompose.compose', + 'send_to' => base64_encode($senderAddress) + ); + $windowName = 'compose'.$header['uid']; + $this->t->set_var('url_compose',"egw_openWindowCentered('".$GLOBALS['egw']->link('/index.php',$linkData)."','$windowName',700,egw_getWindowOuterHeight());"); + /* + $linkData = array + ( + 'menuaction' => 'addressbook.addressbook_ui.edit', + 'presets[email]' => urlencode($header['sender_address']), + 'presets[n_given]' => urlencode($header['sender_name']), + 'referer' => urlencode($_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']) + ); + //TODO: url_add_to_addressbook isn't in any of the templates. + //If you want to use it, you need to adopt syntax to the new addressbook (popup) + $this->t->set_var('url_add_to_addressbook',$GLOBALS['egw']->link('/index.php',$linkData)); + */ + $this->t->set_var('msg_icon_sm',$msg_icon_sm); + + $this->t->set_var('phpgw_images',EGW_IMAGES); + + switch($_rowStyle) { + case 'outlook': + $this->t->parse('message_rows','header_row_outlook',True); + break; + default: + $this->t->parse('message_rows','header_row_felamimail',True); + break; + } + } + + $IFRAMEBody = $this->updateMessagePreview($firstheader,$_folderType,$_folderName); + + $this->t->set_var('IFrameForPreview',$IFRAMEBody); + $this->t->set_var('messagelist_height',($GLOBALS['egw_info']['user']['preferences']['felamimail']['PreViewFrameHeight']>0 ? ($GLOBALS['egw_info']['user']['preferences']['felamimail']['PreViewFrameHeight']).'px':'auto')); + + $this->t->parse("out","message_table"); + + return $this->t->get('out','message_table'); + } + + function updateMessagePreview($headerData,$_folderType,$_folderName,$_icServer=0) + { + // IFrame for Preview .... + if ($headerData['uid'] && $GLOBALS['egw_info']['user']['preferences']['felamimail']['PreViewFrameHeight']>0) + { + $jscall =''; + $this->bofelamimail->openConnection($_icServer); + $this->bofelamimail->reopen($_folderName); + $flags = $this->bofelamimail->getFlags($headerData['uid']); + if ($this->bofelamimail->getNotifyFlags($headerData['uid']) === null) + { + $headers = $this->bofelamimail->getMessageHeader($headerData['uid']); + if ( isset($headers['DISPOSITION-NOTIFICATION-TO']) ) { + $sent_not = $this->bofelamimail->decode_header(trim($headers['DISPOSITION-NOTIFICATION-TO'])); + } else if ( isset($headers['RETURN-RECEIPT-TO']) ) { + $sent_not = $this->bofelamimail->decode_header(trim($headers['RETURN-RECEIPT-TO'])); + } else if ( isset($headers['X-CONFIRM-READING-TO']) ) { + $sent_not = $this->bofelamimail->decode_header(trim($headers['X-CONFIRM-READING-TO'])); + } else $sent_not = ""; + if ( $sent_not != "" && strpos( array2string($flags),'Seen')===false) + { + $jscall= " onload='javascript:sendNotifyMS(".$headerData['uid'].")'"; + } + } + //if (strpos( array2string($flags),'Seen')===false) $this->bofelamimail->flagMessages('read', $headerData['uid']); + if ($_folderType > 0) { + // sent or drafts or template folder + if (!empty($headerData['to_name'])) { + $sender_name = $headerData['to_name']; + $sender_address = $headerData['to_address']; + $full_address = $headerData['to_name'].' <'.$headerData['to_address'].'>'; + } else { + $sender_name = $headerData['to_address']; + $sender_address = $headerData['to_address']; + $full_address = $headerData['to_address']; + } + } else { + if (!empty($headerData['sender_name'])) { + $sender_name = $headerData['sender_name']; + $sender_address = $headerData['sender_address']; + $full_address = $headerData['sender_name'].' <'.$headerData['sender_address'].'>'; + } else { + $sender_name = $headerData['sender_address']; + $sender_address = $headerData['sender_address']; + $full_address = $headerData['sender_address']; + } + } + //$fromAddress = uidisplay::emailAddressToHTML(array('PERSONAL_NAME'=>$sender_name,'EMAIL'=>$sender_address,'RFC822_EMAIL'=>$full_address),''); + if ($GLOBALS['egw_info']['user']['apps']['addressbook']) { + $addresslinkData = array ( + 'menuaction' => 'addressbook.addressbook_ui.edit', + 'presets[email]' => $sender_address, + 'referer' => $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'] + ); + $decodedPersonalName = $sender_name; + if (!empty($decodedPersonalName)) { + if($spacePos = strrpos($decodedPersonalName, ' ')) { + $addresslinkData['presets[n_family]'] = substr($decodedPersonalName, $spacePos+1); + $addresslinkData['presets[n_given]'] = substr($decodedPersonalName, 0, $spacePos); + } else { + $addresslinkData['presets[n_family]'] = $decodedPersonalName; + } + $addresslinkData['presets[n_fn]'] = $decodedPersonalName; + } + + $urlAddToAddressbook = $GLOBALS['egw']->link('/index.php',$addresslinkData); + $onClick = "window.open(this,this.target,'dependent=yes,width=850,height=440,location=no,menubar=no,toolbar=no,scrollbars=yes,status=yes'); return false;"; + $image = $GLOBALS['egw']->common->image('felamimail','sm_envelope'); + $fromAddress .= sprintf(' + %s', + $urlAddToAddressbook, + $onClick, + $image, + lang('add to addressbook'), + lang('add to addressbook')); + } + + $linkData = array ( + 'menuaction' => 'felamimail.uidisplay.display', + 'showHeader' => 'false', + 'mailbox' => base64_encode($_folderName), + 'uid' => $headerData['uid'], + 'id' => $headerData['id'], + ); + $linkDataAttachments = array ( + 'menuaction' => 'felamimail.uidisplay.displayAttachments', + 'showHeader' => 'false', + 'mailbox' => base64_encode($_folderName), + 'uid' => $headerData['uid'], + 'id' => $headerData['id'], + ); + $windowName = 'displayMessage_'.$headerData['uid']; + if($headerData['mimetype'] == 'multipart/mixed' || + $headerData['mimetype'] == 'multipart/related' || + substr($headerData['mimetype'],0,11) == 'application' || + substr($headerData['mimetype'],0,5) == 'audio') { + $image = html::image('felamimail','attach'); + + $image = "link('/index.php',$linkDataAttachments)."', '".$windowName."', this); return false;\" + title=\"".$headerData['subject']."\">".$image.""; + + $windowName = ($_readInNewWindow == 1 ? 'displayMessage' : 'displayMessage_'.$header['uid']); + } else { + $image = ''; + } + $subject = "link('/index.php',$linkData)."', '".$windowName."', this); return false;\" + title=\"".$headerData['subject']."\">".$headerData['subject'].""; + $IFrameHeight = $GLOBALS['egw_info']['user']['preferences']['felamimail']['PreViewFrameHeight']; + $linkData = array ( + 'menuaction' => 'felamimail.uidisplay.displayBody', + 'uid' => $headerData['uid'], + 'mailbox' => base64_encode($_folderName) + ); + //_debug_array($GLOBALS['egw']->link('/index.php',$linkData)); + $IFRAMEBody = " + + + + + + + + +
    + ".($_folderType > 0?lang('to'):lang('from')).':'.$full_address.' '.($fromAddress?$fromAddress:'') .'
    '. + lang('date').':'.bofelamimail::_strtotime($headerData['date'],$GLOBALS['egw_info']['user']['preferences']['common']['dateformat']). + ' - '.bofelamimail::_strtotime($headerData['date'],'H:i:s')."
    + ".lang('subject').":".$subject." +
    + $image + + + ".$this->navbarSeparator().$this->displayMessageActions($headerData, $_folderName, $_icServer,true)." + +
    + +
    "; + } + else + { + $IFRAMEBody = " "; + } + return $IFRAMEBody; + } + + function displayMessageActions($_headerData, $_folderName, $_icServer, $_forceNewWindow=false) + { + if ($_forceNewWindow) + { + list($fm_width,$fm_height) = explode('x',egw_link::get_registry('felamimail','view_popup')); + } + // navbar start + // compose as new URL + $linkData = array ( + 'menuaction' => 'felamimail.uicompose.composeAsNew', + 'icServer' => $_icServer, + 'folder' => base64_encode($_folderName), + 'reply_id' => $_headerData['uid'], + ); + if($_headerData['partid'] != '') { + $linkData['part_id'] = $_headerData['partid']; + } + $asnewURL = $GLOBALS['egw']->link('/index.php',$linkData); + + // reply url + $linkData = array ( + 'menuaction' => 'felamimail.uicompose.reply', + 'icServer' => $_icServer, + 'folder' => base64_encode($_folderName), + 'reply_id' => $_headerData['uid'], + ); + if($_headerData['partid'] != '') { + $linkData['part_id'] = $_headerData['partid']; + } + $replyURL = $GLOBALS['egw']->link('/index.php',$linkData); + + // reply all url + $linkData = array ( + 'menuaction' => 'felamimail.uicompose.replyAll', + 'icServer' => $_icServer, + 'folder' => base64_encode($_folderName), + 'reply_id' => $_headerData['uid'], + ); + if($_headerData['partid'] != '') { + $linkData['part_id'] = $_headerData['partid']; + } + $replyAllURL = $GLOBALS['egw']->link('/index.php',$linkData); + + // forward url + $linkData = array ( + 'menuaction' => 'felamimail.uicompose.forward', + 'reply_id' => $_headerData['uid'], + 'folder' => base64_encode($_folderName), + ); + if($_headerData['partid'] != '') { + $linkData['part_id'] = $_headerData['partid']; + } + $forwardURL = $GLOBALS['egw']->link('/index.php',$linkData); + + //delete url + $linkData = array ( + 'menuaction' => 'felamimail.uifelamimail.deleteMessage', + 'icServer' => $_icServer, + 'folder' => base64_encode($_folderName), + 'message' => $_headerData['uid'], + ); + $deleteURL = $GLOBALS['egw']->link('/index.php',$linkData); + + $navbarImages = array( + 'new' => array( + 'action' => ($_forceNewWindow ? "egw_openWindowCentered('$asnewURL','composeasnew_".$_headerData['uid']."',".$fm_width.",".$fm_height.");": "window.location.href = '$asnewURL'"), + 'tooltip' => lang('compose as new'), + ), + 'mail_reply' => array( + 'action' => ($_forceNewWindow ? "egw_openWindowCentered('$replyURL','reply_".$_headerData['uid']."',".$fm_width.",".$fm_height.");": "window.location.href = '$replyURL'"), + 'tooltip' => lang('reply'), + ), + 'mail_replyall' => array( + 'action' => ($_forceNewWindow ? "egw_openWindowCentered('$replyAllURL','replyAll_".$_headerData['uid']."',".$fm_width.",".$fm_height.");": "window.location.href = '$replyAllURL'"), + 'tooltip' => lang('reply all'), + ), + 'mail_forward' => array( + 'action' => ($_forceNewWindow ? "egw_openWindowCentered('$forwardURL','forward_".$_headerData['uid']."',".$fm_width.",".$fm_height.");": "window.location.href = '$forwardURL'"), + 'tooltip' => lang('forward'), + ), + 'delete' => array( + 'action' => ($_forceNewWindow ? "window.open('$deleteURL','_blank','dependent=yes,width=100,height=100,toolbar=no,scrollbars=no,status=no')": "window.location.href = '$deleteURL'"), + 'tooltip' => lang('delete'), + ), + ); + foreach($navbarImages as $buttonName => $buttonInfo) { + $navbarButtons .= $this->navbarButton($buttonName, $buttonInfo['action'], $buttonInfo['tooltip']); + } + $navbarButtons .= $this->navbarSeparator(); + + // print url + $linkData = array ( + 'menuaction' => 'felamimail.uidisplay.printMessage', + 'uid' => $_headerData['uid'], + 'folder' => base64_encode($_folderName), + ); + if($_headerData['partid'] != '') { + $linkData['part'] = $_headerData['partid']; + } + $printURL = $GLOBALS['egw']->link('/index.php',$linkData); + + // infolog URL + $linkData = array( + 'menuaction' => 'infolog.infolog_ui.import_mail', + 'uid' => $_headerData['uid'], + 'mailbox' => base64_encode($_folderName) + ); + if($_headerData['partid'] != '') { + $linkData['part'] = $_headerData['partid']; + } + $to_infologURL = $GLOBALS['egw']->link('/index.php',$linkData); + + // viewheader url + $linkData = array ( + 'menuaction' => 'felamimail.uidisplay.displayHeader', + 'uid' => $_headerData['uid'], + 'mailbox' => base64_encode($_folderName) + ); + if($_headerData['partid'] != '') { + $linkData['part'] = $_headerData['partid']; + } + $viewHeaderURL = $GLOBALS['egw']->link('/index.php',$linkData); + + $navbarImages = array(); + + // save message url + $linkData = array ( + 'menuaction' => 'felamimail.uidisplay.saveMessage', + 'uid' => $_headerData['uid'], + 'mailbox' => base64_encode($_folderName) + ); + if($_headerData['partid'] != '') { + $linkData['part'] = $_headerData['partid']; + } + $saveMessageURL = $GLOBALS['egw']->link('/index.php',$linkData); + + $navbarImages = array(); + + //print email + $navbarImages = array( + 'fileprint' => array( + 'action' => ($_forceNewWindow ? "egw_openWindowCentered('$printURL','forward_".$_headerData['uid']."',".$fm_width.",".$fm_height.");": "window.location.href = '$printURL'"), + 'tooltip' => lang('print it'), + ), + ); + if ($GLOBALS['egw_info']['user']['apps']['infolog']) + { + list($i_width,$i_height) = explode('x',egw_link::get_registry('infolog','add_popup')); + $navbarImages['to_infolog'] = array( + 'action' => "window.open('$to_infologURL','_blank','dependent=yes,width=".$i_width.",height=".$i_height.",scrollbars=yes,status=yes')", + 'tooltip' => lang('save as infolog')); + } + + // save email as + $navbarImages['fileexport'] = array( + 'action' => ($_forceNewWindow ? "window.open('$saveMessageURL','_blank','dependent=yes,width=100,height=100,scrollbars=yes,status=yes')": "window.location.href = '$saveMessageURL'"), + 'tooltip' => lang('save message to disk'), + ); + + // view header lines + $navbarImages['kmmsgread'] = array( + 'action' => "fm_displayHeaderLines('$viewHeaderURL')", + 'tooltip' => lang('view header lines'), + ); + + foreach($navbarImages as $buttonName => $buttonData) { + $navbarButtons .= $this->navbarButton($buttonName, $buttonData['action'], $buttonData['tooltip']); + } + return $navbarButtons; + } + + /** + * create multiselectbox + * + * this function will create a multiselect box. Hard to describe! :) + * + * @param _selectedValues Array of values for already selected values(the left selectbox) + * @param _predefinedValues Array of values for predefined values(the right selectbox) + * @param _valueName name for the variable containing the selected values + * @param _boxWidth the width of the multiselectbox( example: 100px, 100%) + * + * @returns the html code, to be added into the template + */ + function multiSelectBox($_selectedValues, $_predefinedValues, $_valueName, $_boxWidth="100%") + { + $this->template->set_block('body','multiSelectBox'); + + if(is_array($_selectedValues)) + { + foreach($_selectedValues as $key => $value) + { + $options .= ""; + } + $this->template->set_var('multiSelectBox_selected_options',$options); + } + + $options = ''; + if(is_array($_predefinedValues)) + { + foreach($_predefinedValues as $key => $value) + { + if($key != $_selectedValues["$key"]) + $options .= ""; + } + $this->template->set_var('multiSelectBox_predefinded_options',$options); + } + + $this->template->set_var('multiSelectBox_valueName', $_valueName); + $this->template->set_var('multiSelectBox_boxWidth', $_boxWidth); + + + return $this->template->fp('out','multiSelectBox'); + } + + function navbarButton($_imageName, $_imageAction, $_toolTip='', $_float='left') + { + $image = $GLOBALS['egw']->common->image('felamimail',$_imageName); + $float = $_float == 'right' ? 'right' : 'left'; + + return ""; + } + + function navbarSeparator() + { + return ''; + } + + /* Returns a string showing the size of the message/attachment */ + function show_readable_size($bytes, $_mode='short') + { + $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 . ' ' . $type ; + } + + function tableView($_headValues, $_tableWidth="100%") + { + $this->template->set_block('body','tableView'); + $this->template->set_block('body','tableViewHead'); + + if(is_array($_headValues)) + { + foreach($_headValues as $head) + { + $this->template->set_var('tableHeadContent',$head); + $this->template->parse('tableView_Head','tableViewHead',True); + } + } + + if(is_array($this->tableViewRows)) + { + foreach($this->tableViewRows as $tableRow) + { + $rowData .= ""; + foreach($tableRow as $tableData) + { + switch($tableData['type']) + { + default: + $rowData .= ''.$tableData['text'].''; + break; + } + } + $rowData .= ""; + } + } + + $this->template->set_var('tableView_width', $_tableWidth); + $this->template->set_var('tableView_Rows', $rowData); + + return $this->template->fp('out','tableView'); + } + + function tableViewAddRow() + { + $this->tableViewRows[] = array(); + end($this->tableViewRows); + return key($this->tableViewRows); + } + + function tableViewAddTextCell($_rowID,$_text) + { + $this->tableViewRows[$_rowID][]= array + ( + 'type' => 'text', + 'text' => $_text + ); + } + + function quotaDisplay($_usage, $_limit) + { + $this->t = CreateObject('phpgwapi.Template',EGW_APP_TPL); + $this->t->set_file(array("body" => 'mainscreen.tpl')); + $this->t->set_block('body','quota_block'); + + if($_limit == 0) { + $quotaPercent=100; + } else { + $quotaPercent=round(($_usage*100)/$_limit); + } + + $quotaLimit=$this->show_readable_size($_limit*1024); + $quotaUsage=$this->show_readable_size($_usage*1024); + + $this->t->set_var('leftWidth',$quotaPercent); + + if($quotaPercent > 90 && $_limit>0) { + $this->t->set_var('quotaBG','red'); + } elseif($quotaPercent > 80 && $_limit>0) { + $this->t->set_var('quotaBG','yellow'); + } else { + $this->t->set_var('quotaBG','#66ff66'); + } + + if($_limit > 0) { + $quotaText = $quotaUsage .'/'.$quotaLimit; + } else { + $quotaText = $quotaUsage; + } + + if($quotaPercent > 50) { + $this->t->set_var('quotaUsage_left', $quotaText); + $this->t->set_var('quotaUsage_right',''); + } else { + $this->t->set_var('quotaUsage_left',''); + $this->t->set_var('quotaUsage_right', $quotaText); + } + + $this->t->parse('out','quota_block'); + return $this->t->get('out','quota_block'); + } + } +?>