* @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License * @version $Id$ */ use EGroupware\Api; use EGroupware\Api\Mail; /** * Mail User Interface * * As we do NOT want to connect to previous imap server, when a profile change is triggered * by user get_rows and ajax_changeProfile are not static methods and instanciates there own * mail_ui object. * * If they detect a profile change is to be triggered they call: * $mail_ui = new mail_ui(false); // not call constructor / connect to imap server * $mail_ui->changeProfile($_profileID); * If no profile change is needed they just call: * $mail_ui = new mail_ui(); * Afterwards they use $mail_ui instead of $this. */ class mail_ui { /** * Methods callable via menuaction * * @var array */ var $public_functions = array ( 'index' => True, 'displayHeader' => True, 'displayMessage' => True, 'displayImage' => True, 'getAttachment' => True, 'download_zip' => True, 'saveMessage' => True, 'vfsSaveAttachment' => True, 'vfsSaveMessage' => True, 'loadEmailBody' => True, 'importMessage' => True, 'importMessageFromVFS2DraftAndDisplay'=>True, 'subscription' => True, 'folderManagement' => true, ); /** * current icServerID * * @var int */ static $icServerID; /** * delimiter - used to separate profileID from foldertreestructure, and separate keyinformation in rowids * * @var string */ static $delimiter = '::'; /** * nextMatch name for index * * @var string */ static $nm_index = 'nm'; /** * instance of Mail * * @var Mail */ var $mail_bo; /** * definition of available / supported search types * * @var array */ var $searchTypes = array( 'quick' => 'quicksearch', // lang('quicksearch') 'quickwithcc'=> 'quicksearch (with cc)', // lang('quicksearch (with cc)') 'subject' => 'subject', // lang('subject') 'body' => 'message body', // lang('message body') 'from' => 'from', // lang('from') 'to' => 'to', // lang('to') 'cc' => 'cc', // lang('cc') 'text' => 'whole message', // lang('whole message') 'larger' => 'greater than', // lang('greater than') 'smaller' => 'less than', // lang('less than') // 'custom' => 'Selected range',// lang('Selected range') ); /** * definition of available / supported status types * * @var array */ var $statusTypes = array( 'any' => 'any status',// lang('any status') 'flagged' => 'flagged', // lang('flagged') 'unseen' => 'unread', // lang('unread') 'answered' => 'replied', // lang('replied') 'seen' => 'read', // lang('read') 'deleted' => 'deleted', // lang('deleted') ); /** * Constructor * * @param boolean $run_constructor =true false: no not run constructor and therefore do NOT connect to imap server */ function __construct($run_constructor=true) { $this->mail_tree = new mail_tree($this); if (!$run_constructor) return; if (Mail::$debugTimes) $starttime = microtime (true); // no autohide of the sidebox, as we use it for folderlist now. unset($GLOBALS['egw_info']['user']['preferences']['common']['auto_hide_sidebox']); if (isset($GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID']) && !empty($GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID'])) { self::$icServerID = (int)$GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID']; } if ($_GET["resetConnection"]) { unset($_GET["resetConnection"]); if (Mail::$debug) error_log(__METHOD__.__LINE__.' Connection Reset triggered: for Profile with ID:'.self::$icServerID); Mail::unsetCachedObjects(self::$icServerID); } try { $this->mail_bo = Mail::getInstance(true,self::$icServerID, true, false, true); if (Mail::$debug) error_log(__METHOD__.__LINE__.' Fetched IC Server:'.self::$icServerID.'/'.$this->mail_bo->profileID.':'.function_backtrace()); //error_log(__METHOD__.__LINE__.array2string($this->mail_bo->icServer)); // RegEx to minimize extra openConnection $needle = '/^(?!mail)/'; if (!preg_match($needle,$_GET['menuaction']) && !egw_json_request::isJSONRequest()) { //error_log(__METHOD__.__LINE__.' Fetched IC Server openConnection:'.self::$icServerID.'/'.$this->mail_bo->profileID.':'.function_backtrace()); //openConnection gathers SpecialUseFolderInformation and Delimiter Info $this->mail_bo->openConnection(self::$icServerID); } } catch (Exception $e) { // redirect to mail wizard to handle it (redirect works for ajax too) self::callWizard($e->getMessage(),true,'error'); } if (Mail::$debugTimes) Mail::logRunTimes($starttime,null,'',__METHOD__.__LINE__); } /** * callWizard * * @param string $message * @param boolean $exit If true, will call common::egw_exit() after opening the wizardpopup * @param string $msg_type = 'success' message type */ static function callWizard($message, $exit=true, $msg_type='success') { //error_log(__METHOD__."('$message', $exit) ".function_backtrace()); $linkData=(self::$icServerID ? array( 'menuaction' => 'mail.mail_wizard.edit', 'acc_id' => self::$icServerID, ) : array( 'menuaction' => 'mail.mail_wizard.add', )) + array( 'msg' => $message, 'msg_type' => $msg_type ); if (egw_json_response::isJSONResponse()) { $response = egw_json_response::get(); $windowName = "editMailAccount".self::$icServerID; $response->call("egw.open_link", egw::link('/index.php', $linkData), $windowName, "600x480",null,true); egw_framework::message($message, 'error'); if ($_GET['menuaction'] == 'mail.mail_ui.index') { $response->call('framework.setSidebox','mail',array(),'md5'); } if ($exit) { common::egw_exit(); } } else // regular GET request eg. in idots template { egw_framework::popup(egw_framework::link('/index.php',$linkData)); $GLOBALS['egw']->framework->render($message,'',true); if ($exit) { common::egw_exit(); } } } /** * changeProfile * * @param int $_icServerID * @param boolean $unsetCache * * @throws egw_exception */ function changeProfile($_icServerID,$unsetCache=false) { if (Mail::$debugTimes) $starttime = microtime (true); if (self::$icServerID != $_icServerID) { self::$icServerID = $_icServerID; } if (Mail::$debug) error_log(__METHOD__.__LINE__.'->'.self::$icServerID.'<->'.$_icServerID); if ($unsetCache) Mail::unsetCachedObjects(self::$icServerID); $this->mail_bo = Mail::getInstance(false,self::$icServerID,true, false, true); if (Mail::$debug) error_log(__METHOD__.__LINE__.' Fetched IC Server:'.self::$icServerID.'/'.$this->mail_bo->profileID.':'.function_backtrace()); // no icServer Object: something failed big time if (!isset($this->mail_bo->icServer) || $this->mail_bo->icServer->ImapServerId<>$_icServerID) { self::$icServerID = $_icServerID; throw new egw_exception('Profile change failed!'); } // save session varchar $oldicServerID =& egw_cache::getSession('mail','activeProfileID'); if ($oldicServerID <> self::$icServerID) $this->mail_bo->openConnection(self::$icServerID); $oldicServerID = self::$icServerID; if (!Mail::storeActiveProfileIDToPref($this->mail_bo->icServer, self::$icServerID, true )) { throw new egw_exception(__METHOD__." failed to change Profile to $_icServerID"); } if (Mail::$debugTimes) Mail::logRunTimes($starttime,null,'',__METHOD__.__LINE__); } /** * Ajax function to request next branch of a tree branch */ static function ajax_tree_autoloading ($_id = null) { $mail_ui = new mail_ui(); $_id = $_id? $_id:$_GET['id']; etemplate_widget_tree::send_quote_json($mail_ui->mail_tree->getTree($_id,'',1,false)); } /** * Subscription popup window * * @param array $content * @param type $msg */ function subscription(array $content=null ,$msg=null) { $stmpl = new etemplate_new('mail.subscribe'); if(is_array($content)) { $profileId = $content['profileId']; } elseif (!($profileId = (int)$_GET['acc_id'])) { egw_framework::window_close('Missing acc_id!'); } // Initial tree's options, the rest would be loaded dynamicaly by autoloading, // triggered from client-side. Also, we keep this here as $sel_options['foldertree'] = $this->mail_tree->getTree(null,$profileId,1,true,false,true); //Get all subscribed folders // as getting all subscribed folders is very fast operation // we can use it to get a comparison base for folders which // got subscribed or unsubscribed by the user try { $subscribed = $this->mail_bo->icServer->listSubscribedMailboxes('',0,true); } catch (Exception $ex) { egw_framework::message($ex->getMessage()); } if (!is_array($content)) { $content['foldertree'] = array(); foreach ($subscribed as $folder) { $folderName = $profileId . self::$delimiter . $folder['MAILBOX']; array_push($content['foldertree'], $folderName); } } else { list($button) = @each($content['button']); switch ($button) { case 'save': case 'apply': { // do not let user (un)subscribe namespace roots eg. "other", "user" or "INBOX", same for tree-root/account itself $namespace_roots = array($profileId); foreach($this->mail_bo->_getNameSpaces() as $namespace) { $namespace_roots[] = $profileId . self::$delimiter . str_replace($namespace['delimiter'], '', $namespace['prefix']); } $to_unsubscribe = $to_subscribe = array(); foreach ($content['foldertree'] as $path => $value) { list(,$node) = explode($profileId.self::$delimiter, $path); if ($node) { if (is_array($subscribed) && $subscribed[$node] && !$value['value']) $to_unsubscribe []= $node; if (is_array($subscribed) && !$subscribed[$node] && $value['value']) $to_subscribe [] = $node; if ($value['value']) $cont[] = $path; } } $content['foldertree'] = $cont; // set foldertree options to basic node in order to avoid initial autoloading // from client side, as no options would trigger that. $sel_options['foldertree'] = array('id' => '0', 'item'=> array()); foreach(array_merge($to_subscribe, $to_unsubscribe) as $mailbox) { if (in_array($profileId.self::$delimiter.$mailbox, $namespace_roots, true)) { continue; } $subscribe = in_array($mailbox, $to_subscribe); try { $this->mail_bo->icServer->subscribeMailbox($mailbox, $subscribe); } catch (Exception $ex) { $msg_type = 'error'; if ($subscribe) { $msg .= lang('Failed to subscribe folder %1!', $mailbox).' '.$ex->getMessage(); } else { $msg .= lang('Failed to unsubscribe folder %1!', $mailbox).' '.$ex->getMessage(); } } } if (!isset($msg)) { $msg_type = 'success'; if ($to_subscribe || $to_unsubscribe) { $msg = lang('Subscription successfully saved.'); } else { $msg = lang('Nothing to change.'); } } // update foldertree in main window $parentFolder='INBOX'; $refreshData = array( $profileId => lang($parentFolder), ); $response = egw_json_response::get(); foreach($refreshData as $folder => &$name) { $name = $this->mail_tree->getTree($folder, $profileId,1,true,true,true); } // give success/error message to opener and popup itself //$response->call('opener.app.mail.subscription_refresh',$refreshData); $response->call('opener.app.mail.mail_reloadNode',$refreshData); egw_framework::refresh_opener($msg, 'mail', null, null, null, null, null, $msg_type); if ($button == 'apply') { egw_framework::message($msg, $msg_type); break; } } case 'cancel': { egw_framework::window_close(); } } } $preserv['profileId'] = $profileId; $readonlys = array(); $stmpl->exec('mail.mail_ui.subscription', $content,$sel_options,$readonlys,$preserv,2); } /** * Main mail page * * @param array $content * @param string $msg */ function index(array $content=null,$msg=null) { //error_log(__METHOD__.__LINE__.array2string($content)); try { //error_log(__METHOD__.__LINE__.function_backtrace()); if (Mail::$debugTimes) $starttime = microtime (true); $this->mail_bo->restoreSessionData(); $sessionFolder = $this->mail_bo->sessionData['mailbox']; if ($this->mail_bo->folderExists($sessionFolder)) { $this->mail_bo->reopen($sessionFolder); // needed to fetch full set of capabilities } else { $sessionFolder = $this->mail_bo->sessionData['mailbox'] = 'INBOX'; } //error_log(__METHOD__.__LINE__.' SessionFolder:'.$sessionFolder.' isToSchema:'.$toSchema); if (!is_array($content)) { $content = array( self::$nm_index => egw_session::appsession('index','mail'), ); if (!is_array($content[self::$nm_index])) { $content[self::$nm_index] = array( 'filter' => 'any', // filter is used to choose the mailbox 'no_filter2' => false, // I disable the 2. filter (params are the same as for filter) 'no_cat' => false, // I disable the cat-selectbox 'cat_is_select' => true, // true or no_lang 'lettersearch' => false, // I show a lettersearch 'searchletter' => false, // I0 active letter of the lettersearch or false for [all] 'start' => 0, // IO position in list 'order' => 'date', // IO name of the column to sort after (optional for the sortheaders) 'sort' => 'DESC', // IO direction of the sort: 'ASC' or 'DESC' //'default_cols' => 'status,attachments,subject,'.($toSchema?'toaddress':'fromaddress').',date,size', // I columns to use if there's no user or default pref (! as first char uses all but the named columns), default all columns //'default_cols' => 'status,attachments,subject,address,date,size', // I columns to use if there's no user or default pref (! as first char uses all but the named columns), default all columns //'csv_fields' => false, // I false=disable csv export, true or unset=enable it with auto-detected fieldnames, //or array with name=>label or name=>array('label'=>label,'type'=>type) pairs (type is a eT widget-type) 'actions' => self::get_actions(), 'row_id' => 'row_id', // is a concatenation of trim($GLOBALS['egw_info']['user']['account_id']):profileID:base64_encode(FOLDERNAME):uid 'placeholder_actions' => array('composeasnew'), ); } if (html::$ua_mobile) $content[self::$nm_index]['header_row'] = 'mail.index.header_right'; } $content[self::$nm_index]['get_rows'] = 'mail_ui::get_rows'; $content[self::$nm_index]['num_rows'] = 0; // Do not send any rows with initial request $content[self::$nm_index]['default_cols'] = 'status,attachments,subject,address,date,size'; // I columns to use if there's no user or default pref (! as first char uses all but the named columns), default all columns $content[self::$nm_index]['csv_fields'] = false; if ($msg) { $content['msg'] = $msg; } else { unset($msg); unset($content['msg']); } // call getQuotaRoot asynchronously in getRows by initiating a client Server roundtrip $quota = false;//$this->mail_bo->getQuotaRoot(); if($quota !== false && $quota['limit'] != 'NOT SET') { $quotainfo = $this->quotaDisplay($quota['usage'], $quota['limit']); $content[self::$nm_index]['quota'] = $sel_options[self::$nm_index]['quota'] = $quotainfo['text']; $content[self::$nm_index]['quotainpercent'] = $sel_options[self::$nm_index]['quotainpercent'] = (string)$quotainfo['percent']; $content[self::$nm_index]['quotaclass'] = $sel_options[self::$nm_index]['quotaclass'] = $quotainfo['class']; $content[self::$nm_index]['quotanotsupported'] = $sel_options[self::$nm_index]['quotanotsupported'] = ""; } else { $content[self::$nm_index]['quota'] = $sel_options[self::$nm_index]['quota'] = lang("Quota not provided by server"); $content[self::$nm_index]['quotaclass'] = $sel_options[self::$nm_index]['quotaclass'] = "mail_DisplayNone"; $content[self::$nm_index]['quotanotsupported'] = $sel_options[self::$nm_index]['quotanotsupported'] = "mail_DisplayNone"; } // call gatherVacation asynchronously in getRows by initiating a client Server roundtrip $vacation = false;//$this->gatherVacation(); //error_log(__METHOD__.__LINE__.' Server:'.self::$icServerID.' Sieve Enabled:'.array2string($vacation)); if($vacation) { if (is_array($vacation) && ($vacation['status'] == 'on' || $vacation['status']=='by_date' && $vacation['end_date'] > time())) { $dtfrmt = $GLOBALS['egw_info']['user']['preferences']['common']['dateformat']/*.' '.($GLOBALS['egw_info']['user']['preferences']['common']['timeformat']!='24'?'h:i a':'H:i')*/; $content[self::$nm_index]['vacationnotice'] = $sel_options[self::$nm_index]['vacationnotice'] = lang('Vacation notice is active'); $content[self::$nm_index]['vacationrange'] = $sel_options[self::$nm_index]['vacationrange'] = ($vacation['status']=='by_date'? common::show_date($vacation['start_date'],$dtfrmt,true).($vacation['end_date']>$vacation['start_date']?'->'.common::show_date($vacation['end_date']+ 24*3600-1,$dtfrmt,true):''):''); } } if ($vacation==false) { $content[self::$nm_index]['vacationnotice'] = $sel_options[self::$nm_index]['vacationnotice'] = ''; $content[self::$nm_index]['vacationrange'] = $sel_options[self::$nm_index]['vacationrange'] = ''; } //$zstarttime = microtime (true); $sel_options[self::$nm_index]['foldertree'] = $this->mail_tree->getInitialIndexTree(null, $this->mail_bo->profileID, null, !$this->mail_bo->mailPreferences['showAllFoldersInFolderPane'],!$this->mail_bo->mailPreferences['showAllFoldersInFolderPane']); //$zendtime = microtime(true) - $zstarttime; //error_log(__METHOD__.__LINE__. " time used: ".$zendtime); $content[self::$nm_index]['selectedFolder'] = $this->mail_bo->profileID.self::$delimiter.(!empty($this->mail_bo->sessionData['mailbox'])?$this->mail_bo->sessionData['mailbox']:'INBOX'); // since we are connected,(and selected the folder) we check for capabilities SUPPORTS_KEYWORDS to eventually add the keyword filters if ( $this->mail_bo->icServer->hasCapability('SUPPORTS_KEYWORDS')) { $this->statusTypes = array_merge($this->statusTypes,array( 'keyword1' => 'important',//lang('important'), 'keyword2' => 'job', //lang('job'), 'keyword3' => 'personal',//lang('personal'), 'keyword4' => 'to do', //lang('to do'), 'keyword5' => 'later', //lang('later'), )); } else { $keywords = array('keyword1','keyword2','keyword3','keyword4','keyword5'); foreach($keywords as &$k) { if (array_key_exists($k,$this->statusTypes)) unset($this->statusTypes[$k]); } } if (!isset($content[self::$nm_index]['foldertree'])) $content[self::$nm_index]['foldertree'] = $this->mail_bo->profileID.self::$delimiter.'INBOX'; if (!isset($content[self::$nm_index]['selectedFolder'])) $content[self::$nm_index]['selectedFolder'] = $this->mail_bo->profileID.self::$delimiter.'INBOX'; $content[self::$nm_index]['foldertree'] = $content[self::$nm_index]['selectedFolder']; if (is_null(Mail::$supportsORinQuery) || !isset(Mail::$supportsORinQuery[$this->mail_bo->profileID])) { Mail::$supportsORinQuery = egw_cache::getCache(egw_cache::INSTANCE, 'email', 'supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60*60*10); if (!isset(Mail::$supportsORinQuery[$this->mail_bo->profileID])) Mail::$supportsORinQuery[$this->mail_bo->profileID]=true; } if (!Mail::$supportsORinQuery[$this->mail_bo->profileID]) { unset($this->searchTypes['quick']); unset($this->searchTypes['quickwithcc']); } $sel_options['cat_id'] = $this->searchTypes; //error_log(__METHOD__.__LINE__.array2string($sel_options['cat_id'])); //error_log(__METHOD__.__LINE__.array2string($GLOBALS['egw_info']['user']['preferences']['mail']['ActiveSearchType'])); $content[self::$nm_index]['cat_id'] = $GLOBALS['egw_info']['user']['preferences']['mail']['ActiveSearchType']; $sel_options['filter'] = $this->statusTypes; $sel_options['filter2'] = array(''=>'No details',1=>'Details'); $content[self::$nm_index]['filter2'] = $GLOBALS['egw_info']['user']['preferences']['mail']['ShowDetails']; $etpl = new etemplate_new('mail.index'); // Start at 2 so auto-added copy+paste actions show up as second group // Needed because there's no 'select all' action to push things down $group=1; // Set tree actions $tree_actions = array( 'drop_move_mail' => array( 'type' => 'drop', 'acceptedTypes' => 'mail', 'icon' => 'move', 'caption' => 'Move to', 'onExecute' => 'javaScript:app.mail.mail_move' ), 'drop_copy_mail' => array( 'type' => 'drop', 'acceptedTypes' => 'mail', 'icon' => 'copy', 'caption' => 'Copy to', 'onExecute' => 'javaScript:app.mail.mail_copy' ), 'drop_cancel' => array( 'icon' => 'cancel', 'caption' => 'Cancel', 'acceptedTypes' => 'mail', 'type' => 'drop', ), 'drop_move_folder' => array( 'caption' => 'Move folder', 'hideOnDisabled' => true, 'type' => 'drop', 'acceptedTypes' => 'mailFolder', 'onExecute' => 'javaScript:app.mail.mail_MoveFolder' ), // Tree does support this one 'add' => array( 'caption' => 'Add Folder', 'onExecute' => 'javaScript:app.mail.mail_AddFolder', 'enabled' => 'javaScript:app.mail.mail_CheckFolderNoSelect', 'group' => $group, ), 'edit' => array( 'caption' => 'Rename Folder', 'onExecute' => 'javaScript:app.mail.mail_RenameFolder', 'enabled' => 'javaScript:app.mail.mail_CheckFolderNoSelect', 'group' => $group, ), 'move' => array( 'caption' => 'Move Folder', 'type' => 'drag', 'enabled' => 'javaScript:app.mail.mail_CheckFolderNoSelect', 'dragType' => array('mailFolder'), 'group' => $group, ), 'delete' => array( 'caption' => 'Delete Folder', 'enabled' => 'javaScript:app.mail.mail_CheckFolderNoSelect', 'onExecute' => 'javaScript:app.mail.mail_DeleteFolder', 'group' => $group, ), 'subscribe' => array( 'caption' => 'Subscribe folder ...', //'icon' => 'configure', 'enabled' => 'javaScript:app.mail.mail_CheckFolderNoSelect', 'onExecute' => 'javaScript:app.mail.edit_subscribe', 'group' => $group ), 'unsubscribe' => array( 'caption' => 'Unsubscribe folder', 'enabled' => 'javaScript:app.mail.mail_CheckFolderNoSelect', 'onExecute' => 'javaScript:app.mail.unsubscribe_folder', 'group' => $group, ), 'foldermanagement' => array( 'caption' => 'Folder Management ...', 'enabled' => 'javaScript:app.mail.mail_CheckFolderNoSelect', 'onExecute' => 'javaScript:app.mail.folderManagement', 'group' => $group, 'hideOnMobile' => true ), 'sieve' => array( 'caption' => 'Mail filter', 'onExecute' => 'javaScript:app.mail.edit_sieve', 'enabled' => 'javaScript:app.mail.sieve_enabled', 'icon' => 'etemplate/fav_filter', // funnel 'hideOnMobile' => true ), 'vacation' => array( 'caption' => 'Vacation notice', 'icon' => 'mail/navbar', // mail as in admin 'onExecute' => 'javaScript:app.mail.edit_vacation', 'enabled' => 'javaScript:app.mail.sieve_enabled', ), 'edit_account' => array( 'caption' => 'Edit account ...', 'icon' => 'configure', 'onExecute' => 'javaScript:app.mail.edit_account', ), 'edit_acl' => array( 'caption' => 'Edit folder ACL ...', 'icon' => 'lock', 'enabled' => 'javaScript:app.mail.acl_enabled', 'onExecute' => 'javaScript:app.mail.edit_acl', ), ); // the preference prefaskformove controls actually if there is a popup on target or not // if there are multiple options there is a popup on target, 0 for prefaskformove means // that only move is available; 1 stands for move and cancel; 2 (should be the default if // not set); so we are assuming this, when not set if (isset($this->mail_bo->mailPreferences['prefaskformove'])) { switch ($this->mail_bo->mailPreferences['prefaskformove']) { case 0: unset($tree_actions['drop_copy_mail']); unset($tree_actions['drop_cancel']); break; case 1: unset($tree_actions['drop_copy_mail']); break; default: // everything is fine } } //error_log(__METHOD__.__LINE__.' showAllFoldersInFolderPane:'.$this->mail_bo->mailPreferences['showAllFoldersInFolderPane'].'/'.$GLOBALS['egw_info']['user']['preferences']['mail']['showAllFoldersInFolderPane']); if ($this->mail_bo->mailPreferences['showAllFoldersInFolderPane']) { unset($tree_actions['subscribe']); unset($tree_actions['unsubscribe']); } ++$group; // put delete in own group switch($GLOBALS['egw_info']['user']['preferences']['mail']['deleteOptions']) { case 'move_to_trash': $tree_actions['empty_trash'] = array( 'caption' => 'empty trash', 'icon' => 'dhtmlxtree/MailFolderTrash', 'onExecute' => 'javaScript:app.mail.mail_emptyTrash', 'group' => $group, ); break; case 'mark_as_deleted': $tree_actions['compress_folder'] = array( 'caption' => 'compress folder', 'icon' => 'dhtmlxtree/MailFolderTrash', 'onExecute' => 'javaScript:app.mail.mail_compressFolder', 'group' => $group, ); break; } $junkFolder = $this->mail_bo->getJunkFolder(); //error_log(__METHOD__.__LINE__.$junkFolder); if ($junkFolder && !empty($junkFolder)) { $tree_actions['empty_spam'] = array( 'caption' => 'empty junk', 'icon' => 'dhtmlxtree/MailFolderJunk', 'enabled' => 'javaScript:app.mail.spamfolder_enabled', 'onExecute' => 'javaScript:app.mail.mail_emptySpam', 'group' => $group, ); } $tree_actions['sieve']['group'] = $tree_actions['vacation']['group'] = ++$group; // new group for filter $tree_actions['edit_account']['group'] = $tree_actions['edit_acl']['group'] = ++$group; // enforce global (group-specific) ACL if (!mail_hooks::access('aclmanagement')) { unset($tree_actions['edit_acl']); } if (!mail_hooks::access('editfilterrules')) { unset($tree_actions['sieve']); } if (!mail_hooks::access('absentnotice')) { unset($tree_actions['vacation']); } if (!mail_hooks::access('managefolders')) { unset($tree_actions['add']); unset($tree_actions['move']); unset($tree_actions['delete']); unset($tree_actions['foldermanagement']); // manage folders should not affect the ability to subscribe or unsubscribe // to existing folders, it should only affect add/rename/move/delete } $etpl->setElementAttribute(self::$nm_index.'[foldertree]','actions', $tree_actions); // sending preview toolbar actions if ($content['mailSplitter']) $etpl->setElementAttribute('mailPreview[toolbar]', 'actions', $this->get_toolbar_actions()); // We need to send toolbar actions to client-side because view template needs them if (html::$ua_mobile) $sel_options['toolbar'] = $this->get_toolbar_actions(); //we use the category "filter" option as specifier where we want to search (quick, subject, from, to, etc. ....) if (empty($content[self::$nm_index]['cat_id']) || empty($content[self::$nm_index]['search'])) { $content[self::$nm_index]['cat_id']=($content[self::$nm_index]['cat_id']?(!Mail::$supportsORinQuery[$this->mail_bo->profileID]&&($content[self::$nm_index]['cat_id']=='quick'||$content[self::$nm_index]['cat_id']=='quickwithcc')?'subject':$content[self::$nm_index]['cat_id']):(Mail::$supportsORinQuery[$this->mail_bo->profileID]?'quick':'subject')); } $readonlys = $preserv = array(); if (Mail::$debugTimes) Mail::logRunTimes($starttime,null,'',__METHOD__.__LINE__); } catch (Exception $e) { self::callWizard($e->getMessage(),true, 'error'); } // Check preview pane is enabled, then show spliter if ($this->mail_bo->mailPreferences['previewPane']) $etpl->setElementAttribute('mail.index.spliter', 'template', 'mail.index.nospliter'); return $etpl->exec('mail.mail_ui.index',$content,$sel_options,$readonlys,$preserv); } /** * Ajax callback to subscribe / unsubscribe a Mailbox of an account * * @param {int} $_acc_id profile Id of selected mailbox * @param {string} $_folderName name of mailbox needs to be subcribe or unsubscribed * @param {boolean} $_status set true for subscribe and false to unsubscribe */ public function ajax_foldersubscription($_acc_id,$_folderName, $_status) { //Change the Mail object to related profileId $this->changeProfile($_acc_id); if($this->mail_bo->icServer->subscribeMailbox($_folderName, $_status)) { $this->mail_bo->resetFolderObjectCache($_acc_id); $this->ajax_reloadNode($_acc_id,!$this->mail_bo->mailPreferences['showAllFoldersInFolderPane']); } else { error_log(__METHOD__.__LINE__."()". lang('Folder %1 %2 failed!',$_folderName,$_status?'subscribed':'unsubscribed')); } } /** * Ajax callback to fetch folders for given profile * * We currently load all folders of a given profile, tree can also load parts of a tree. * * @param string $_nodeID if of node whos children are requested * @param boolean $_subscribedOnly flag to tell wether to fetch all or only subscribed (default) */ public function ajax_foldertree($_nodeID = null,$_subscribedOnly=null) { $nodeID = $_GET['id']; if (!is_null($_nodeID)) $nodeID = $_nodeID; $subscribedOnly = (bool)(!is_null($_subscribedOnly)?$_subscribedOnly:!$this->mail_bo->mailPreferences['showAllFoldersInFolderPane']); $fetchCounters = !is_null($_nodeID); list($_profileID,$_folderName) = explode(self::$delimiter,$nodeID,2); if (!empty($_folderName)) $fetchCounters = true; // Check if it is called for refresh root // then we need to reinitialized the index tree if(!$nodeID && !$_profileID) { $data = $this->mail_tree->getInitialIndexTree(null,null,null,null,true,!$this->mail_bo->mailPreferences['showAllFoldersInFolderPane']); } else { $data = $this->mail_tree->getTree($nodeID,$_profileID,0, false,$subscribedOnly,!$this->mail_bo->mailPreferences['showAllFoldersInFolderPane']); } if (!is_null($_nodeID)) return $data; etemplate_widget_tree::send_quote_json($data); } /** * findNode - helper function to return only a branch of the tree * * @param array $_out out array (to be searched) * @param string $_nodeID node to search for * @param boolean $childElements return node itself, or only its child items * @return array structured subtree */ static function findNode($_out, $_nodeID, $childElements = false) { foreach($_out['item'] as $node) { if (strcmp($node['id'],$_nodeID)===0) { //error_log(__METHOD__.__LINE__.':'.$_nodeID.'->'.$node['id']); return ($childElements?$node['item']:$node); } elseif (is_array($node['item']) && strncmp($node['id'],$_nodeID,strlen($node['id']))===0 && strlen($_nodeID)>strlen($node['id'])) { //error_log(__METHOD__.__LINE__.' descend into '.$node['id']); return self::findNode($node,$_nodeID,$childElements); } } } /** * Get actions / context menu for index * * Changes here, require to log out, as $content[self::$nm_index] get stored in session! * @return array see nextmatch_widget::egw_actions() */ private function get_actions() { static $accArray=array(); // buffer identity names on single request // duplicated from mail_hooks static $deleteOptions = array( 'move_to_trash' => 'move to trash', 'mark_as_deleted' => 'mark as deleted', 'remove_immediately' => 'remove immediately', ); // todo: real hierarchical folder list $lastFolderUsedForMove = null; $moveactions = array(); $lastFoldersUsedForMoveCont = egw_cache::getCache(egw_cache::INSTANCE,'email','lastFolderUsedForMove'.trim($GLOBALS['egw_info']['user']['account_id']),null,array(),$expiration=60*60*1); //error_log(__METHOD__.__LINE__." StoredFolders->".array2string($lastFoldersUsedForMoveCont)); //error_log(__METHOD__.__LINE__.' ProfileId:'.$this->mail_bo->profileID." StoredFolders->(".count($lastFoldersUsedForMoveCont[$this->mail_bo->profileID]).") ".array2string($lastFoldersUsedForMoveCont[$this->mail_bo->profileID])); if (is_null($accArray)) { foreach(Mail\Account::search($only_current_user=true, false) as $acc_id => $accountObj) { //error_log(__METHOD__.__LINE__.array2string($accountObj)); if (!$accountObj->is_imap()) { // not to be used for IMAP Foldertree, as there is no Imap host continue; } $identity_name = Mail\Account::identity_name($accountObj,true,$GLOBALS['egw_info']['user']['acount_id']); $accArray[$acc_id] = str_replace(array('<','>'),array('[',']'),$identity_name);// as angle brackets are quoted, display in Javascript messages when used is ugly, so use square brackets instead } } if (!is_array($lastFoldersUsedForMoveCont)) $lastFoldersUsedForMoveCont=array(); foreach ($lastFoldersUsedForMoveCont as $pid => $info) { if ($this->mail_bo->profileID==$pid && isset($lastFoldersUsedForMoveCont[$this->mail_bo->profileID])) { $_folder = $this->mail_bo->icServer->getCurrentMailbox(); //error_log(__METHOD__.__LINE__.' '.$_folder."<->".$lastFoldersUsedForMoveCont[$this->mail_bo->profileID].function_backtrace()); $counter =1; foreach ($lastFoldersUsedForMoveCont[$this->mail_bo->profileID] as $i => $lastFolderUsedForMoveCont) { $moveaction = 'move_'; if ($_folder!=$i) { $moveaction .= $lastFolderUsedForMoveCont; if ($this->mail_bo->folderExists($i)) // only 10 entries per mailaccount.Control this on setting the buffered folders { $fS['profileID'] = $this->mail_bo->profileID; $fS['profileName'] = $accArray[$this->mail_bo->profileID]; $fS['shortDisplayName'] = $i; $moveactions[$moveaction] = $fS; $counter ++; } else { unset($lastFoldersUsedForMoveCont[$this->mail_bo->profileID][$i]); } //error_log(array2string($moveactions[$moveaction])); } } } elseif ($this->mail_bo->profileID!=$pid && isset($lastFoldersUsedForMoveCont[$pid]) && !empty($lastFoldersUsedForMoveCont[$pid])) { $counter =1; foreach ($lastFoldersUsedForMoveCont[$pid] as $i => $lastFolderUsedForMoveCont) { //error_log(__METHOD__.__LINE__."$i => $lastFolderUsedForMoveCont"); if (!empty($lastFolderUsedForMoveCont)) // only 10 entries per mailaccount.Control this on setting the buffered folders { $moveaction = 'move_'; $fS = array(); $fS['profileID'] = $pid; $fS['profileName'] = $accArray[$pid]; $fS['shortDisplayName'] = $i; $moveactions[$moveaction] = $fS; $counter ++; } } } } egw_cache::setCache(egw_cache::INSTANCE,'email','lastFolderUsedForMove'.trim($GLOBALS['egw_info']['user']['account_id']),$lastFoldersUsedForMoveCont, $expiration=60*60*1); $group = 0; $actions = array( 'open' => array( 'caption' => lang('Open'), 'icon' => 'view', 'group' => ++$group, 'onExecute' => html::$ua_mobile?'javaScript:app.mail.mobileView':'javaScript:app.mail.mail_open', 'allowOnMultiple' => false, 'default' => true, 'mobileViewTemplate' => 'view' ), 'reply' => array( 'caption' => 'Reply', 'icon' => 'mail_reply', 'group' => ++$group, 'onExecute' => 'javaScript:app.mail.mail_compose', 'allowOnMultiple' => false, 'toolbarDefault' => true ), 'reply_all' => array( 'caption' => 'Reply All', 'icon' => 'mail_replyall', 'group' => $group, 'onExecute' => 'javaScript:app.mail.mail_compose', 'allowOnMultiple' => false, ), 'forward' => array( 'caption' => 'Forward', 'icon' => 'mail_forward', 'group' => $group, 'children' => array( 'forwardinline' => array( 'caption' => 'Inline', 'icon' => 'mail_forward', 'group' => $group, 'hint' => 'forward inline', 'onExecute' => 'javaScript:app.mail.mail_compose', 'allowOnMultiple' => false, 'toolbarDefault' => true ), 'forwardasattach' => array( 'caption' => 'Attachment', 'hint' => 'forward as attachment', 'icon' => 'mail_forward_attach', 'group' => $group, 'onExecute' => 'javaScript:app.mail.mail_compose', ), ), 'hideOnMobile' => true ), 'composeasnew' => array( 'caption' => 'Compose', 'icon' => 'new', 'hint' => 'Compose as new', 'group' => $group, 'onExecute' => 'javaScript:app.mail.mail_compose', 'allowOnMultiple' => false, ) ); $macounter=0; if (!empty($moveactions)) { //error_log(__METHOD__.__LINE__.array2string($moveactions)); $children=array(); $pID=0; foreach ($moveactions as $moveaction => $lastFolderUsedForMove) { $group = ($pID != $lastFolderUsedForMove['profileID'] && $macounter>0? $group+1 : $group); //error_log(__METHOD__.__LINE__."#$pID != ".$lastFolderUsedForMove['profileID']."#".$macounter.'#'.$groupCounter.'#'); $children = array_merge($children, array( $moveaction => array( 'caption' => (!empty($lastFolderUsedForMove['profileName'])?$lastFolderUsedForMove['profileName']:'('.$lastFolderUsedForMove['profileID'].')').': '.(isset($lastFolderUsedForMove['shortDisplayName'])?$lastFolderUsedForMove['shortDisplayName']:''), 'icon' => 'move', 'group' => $group, 'onExecute' => 'javaScript:app.mail.mail_move2folder', 'allowOnMultiple' => true, ) ) ); $pID = $lastFolderUsedForMove['profileID']; $macounter++; } $actions = array_merge($actions,array('moveto' => array( 'caption' => lang('Move selected to'), 'icon' => 'move', 'group' => $group++, 'children' => $children, ) ) ); } $actions = array_merge($actions, array( 'infolog' => array( 'caption' => 'InfoLog', 'hint' => 'Save as InfoLog', 'icon' => 'infolog/navbar', 'group' => ++$group, 'onExecute' => 'javaScript:app.mail.mail_integrate', 'popup' => egw_link::get_registry('infolog', 'add_popup'), 'allowOnMultiple' => false, 'toolbarDefault' => true ), 'tracker' => array( 'caption' => 'Tracker', 'hint' => 'Save as ticket', 'group' => $group, 'icon' => 'tracker/navbar', 'onExecute' => 'javaScript:app.mail.mail_integrate', 'popup' => egw_link::get_registry('tracker', 'add_popup'), 'mail_import' => $GLOBALS['egw']->hooks->single(array('location' => 'mail_import'),'tracker'), 'allowOnMultiple' => false, ), 'calendar' => array( 'caption' => 'Calendar', 'hint' => 'Save as Calendar', 'icon' => 'calendar/navbar', 'group' => $group, 'onExecute' => 'javaScript:app.mail.mail_integrate', 'popup' => egw_link::get_registry('calendar', 'add_popup'), 'allowOnMultiple' => false, 'toolbarDefault' => true ), 'print' => array( 'caption' => 'Print', 'group' => ++$group, 'onExecute' => 'javaScript:app.mail.mail_print', 'allowOnMultiple' => false, 'hideOnMobile' => true ), 'save' => array( 'caption' => 'Save', 'group' => $group, 'icon' => 'fileexport', 'children' => array( 'save2disk' => array( 'caption' => 'Save to disk', 'hint' => 'Save message to disk', 'group' => $group, 'icon' => 'fileexport', 'onExecute' => 'javaScript:app.mail.mail_save', 'allowOnMultiple' => false, 'hideOnMobile' => true ), 'save2filemanager' => array( 'caption' => 'Filemanager', 'hint' => 'Save message to filemanager', 'group' => $group, 'icon' => 'filemanager/navbar', 'onExecute' => 'javaScript:app.mail.mail_save2fm', 'allowOnMultiple' => false, ), ), 'hideOnMobile' => true ), 'view' => array( 'caption' => 'View', 'group' => $group, 'icon' => 'kmmsgread', 'children' => array( 'header' => array( 'caption' => 'Header', 'hint' => 'View header lines', 'group' => $group, 'icon' => 'kmmsgread', 'onExecute' => 'javaScript:app.mail.mail_header', 'allowOnMultiple' => false, ), 'mailsource' => array( 'caption' => 'Source', 'hint' => 'View full Mail Source', 'group' => $group, 'icon' => 'source', 'onExecute' => 'javaScript:app.mail.mail_mailsource', 'allowOnMultiple' => false, ), 'openastext' => array( 'caption' => lang('Text mode'), 'hint' => 'Open in Text mode', 'group' => ++$group, 'icon' => 'textmode', 'onExecute' => 'javaScript:app.mail.mail_openAsText', 'allowOnMultiple' => false, ), 'openashtml' => array( 'caption' => lang('HTML mode'), 'hint' => 'Open in HTML mode', 'group' => $group, 'icon' => 'htmlmode', 'onExecute' => 'javaScript:app.mail.mail_openAsHtml', 'allowOnMultiple' => false, ), ), 'hideOnMobile' => true ), 'mark' => array( 'caption' => 'Set / Remove Flags', 'icon' => 'read_small', 'group' => ++$group, 'children' => array( // icons used from http://creativecommons.org/licenses/by-sa/3.0/ // Artist: Led24 // Iconset Homepage: http://led24.de/iconset // License: CC Attribution 3.0 'setLabel' => array( 'caption' => 'Set / Remove Labels', 'icon' => 'tag_message', 'group' => ++$group, // note this one is NOT a real CAPABILITY reported by the server, but added by selectMailbox 'enabled' => $this->mail_bo->icServer->hasCapability('SUPPORTS_KEYWORDS'), 'hideOnDisabled' => true, 'children' => array( 'unlabel' => array( 'group' => ++$group, 'caption' => "".lang('remove all')."", 'icon' => 'mail_label', 'onExecute' => 'javaScript:app.mail.mail_flag', 'shortcut' => egw_keymanager::shortcut(egw_keymanager::_0, true, true), ), 'label1' => array( 'group' => ++$group, 'caption' => "".lang('important')."", 'icon' => 'mail_label1', 'onExecute' => 'javaScript:app.mail.mail_flag', 'shortcut' => egw_keymanager::shortcut(egw_keymanager::_1, true, true), ), 'label2' => array( 'group' => $group, 'caption' => "".lang('job')."", 'icon' => 'mail_label2', 'onExecute' => 'javaScript:app.mail.mail_flag', 'shortcut' => egw_keymanager::shortcut(egw_keymanager::_2, true, true), ), 'label3' => array( 'group' => $group, 'caption' => "".lang('personal')."", 'icon' => 'mail_label3', 'onExecute' => 'javaScript:app.mail.mail_flag', 'shortcut' => egw_keymanager::shortcut(egw_keymanager::_3, true, true), ), 'label4' => array( 'group' => $group, 'caption' => "".lang('to do')."", 'icon' => 'mail_label4', 'onExecute' => 'javaScript:app.mail.mail_flag', 'shortcut' => egw_keymanager::shortcut(egw_keymanager::_4, true, true), ), 'label5' => array( 'group' => $group, 'caption' => "".lang('later')."", 'icon' => 'mail_label5', 'onExecute' => 'javaScript:app.mail.mail_flag', 'shortcut' => egw_keymanager::shortcut(egw_keymanager::_5, true, true), ), ), ), // modified icons from http://creativecommons.org/licenses/by-sa/3.0/ 'flagged' => array( 'group' => ++$group, 'caption' => 'Flag / Unflag', 'icon' => 'unread_flagged_small', 'onExecute' => 'javaScript:app.mail.mail_flag', 'hint' => 'Flag or Unflag a mail', 'shortcut' => egw_keymanager::shortcut(egw_keymanager::F, true, true), 'toolbarDefault' => true ), 'read' => array( 'group' => $group, 'caption' => 'Read / Unread', 'icon' => 'read_small', 'onExecute' => 'javaScript:app.mail.mail_flag', 'shortcut' => egw_keymanager::shortcut(egw_keymanager::U, true, true), ), 'readall' => array( 'group' => ++$group, 'caption' => "".lang('mark all as read')."", 'icon' => 'read_small', 'onExecute' => 'javaScript:app.mail.mail_flag', 'hint' => 'mark all messages in folder as read', 'toolbarDefault' => false ), 'undelete' => array( 'group' => $group, 'caption' => 'Undelete', 'icon' => 'revert', 'onExecute' => 'javaScript:app.mail.mail_flag', ), ), ), 'delete' => array( 'caption' => 'Delete', 'hint' => $deleteOptions[$this->mail_bo->mailPreferences['deleteOptions']], 'group' => ++$group, 'onExecute' => 'javaScript:app.mail.mail_delete', 'toolbarDefault' => true ), 'drag_mail' => array( 'dragType' => array('mail'), 'type' => 'drag', //'onExecute' => 'javaScript:app.mail.mail_dragStart', ) ) ); //error_log(__METHOD__.__LINE__.array2string(array_keys($actions))); // save as tracker, save as infolog, as this are actions that are either available for all, or not, we do that for all and not via css-class disabling if (!isset($GLOBALS['egw_info']['user']['apps']['infolog'])) { unset($actions['infolog']); } if (!isset($GLOBALS['egw_info']['user']['apps']['tracker'])) { unset($actions['tracker']); } if (!isset($GLOBALS['egw_info']['user']['apps']['calendar'])) { unset($actions['calendar']); } return $actions; } /** * Callback to fetch the rows for the nextmatch widget * * Function is static to not automatic call constructor in case profile is changed. * * @param array $query * @param array &$rows * @param array &$readonlys */ public static function get_rows(&$query,&$rows,&$readonlys) { // handle possible profile change in get_rows if (!empty($query['selectedFolder'])) { list($_profileID,$folderName) = explode(self::$delimiter, $query['selectedFolder'], 2); if (is_numeric(($_profileID)) && $_profileID != $GLOBALS['egw_info']['user']['preferences']['mail']['ActiveProfileID']) { try { $mail_ui = new mail_ui(false); // do NOT run constructor, as we change profile anyway $mail_ui->changeProfile($_profileID); $query['actions'] = $mail_ui->get_actions(); } catch(Exception $e) { $rows=array(); return 0; } if (empty($folderName)) $query['selectedFolder'] = $_profileID.self::$delimiter.'INBOX'; } } if (!isset($mail_ui)) { $mail_ui = new mail_ui(true); // run constructor for current profile if (empty($query['selectedFolder'])) $query['selectedFolder'] = $mail_ui->mail_bo->profileID.self::$delimiter.'INBOX'; } //error_log(__METHOD__.__LINE__.' SelectedFolder:'.$query['selectedFolder'].' Start:'.$query['start'].' NumRows:'.$query['num_rows'].array2string($query['order']).'->'.array2string($query['sort'])); //Mail::$debugTimes=true; if (Mail::$debugTimes) $starttime = microtime(true); //$query['search'] is the phrase in the searchbox $mail_ui->mail_bo->restoreSessionData(); if (isset($query['selectedFolder'])) $mail_ui->mail_bo->sessionData['mailbox']=$query['selectedFolder']; $mail_ui->mail_bo->saveSessionData(); $sRToFetch = null; list($_profileID,$_folderName) = explode(self::$delimiter,$query['selectedFolder'],2); if (strpos($_folderName,self::$delimiter)!==false) { list($app,$_profileID,$_folderName) = explode(self::$delimiter,$_folderName,3); unset($app); } //save selected Folder to sessionData (mailbox)->currentFolder if (isset($query['selectedFolder'])) $mail_ui->mail_bo->sessionData['mailbox']=$_folderName; $toSchema = false;//decides to select list schema with column to selected (if false fromaddress is default) if ($mail_ui->mail_bo->folderExists($_folderName)) { $toSchema = $mail_ui->mail_bo->isDraftFolder($_folderName,false)||$mail_ui->mail_bo->isSentFolder($_folderName,false)||$mail_ui->mail_bo->isTemplateFolder($_folderName,false); } else { // take the extra time on failure if (!$mail_ui->mail_bo->folderExists($_folderName,true)) { //error_log(__METHOD__.__LINE__.' Test on Folder:'.$_folderName.' failed; Using INBOX instead'); $query['selectedFolder']=$mail_ui->mail_bo->sessionData['mailbox']=$_folderName='INBOX'; } } $mail_ui->mail_bo->saveSessionData(); $rowsFetched['messages'] = null; $offset = $query['start']+1; // we always start with 1 $maxMessages = $query['num_rows']; //error_log(__METHOD__.__LINE__.array2string($query)); $sort = ($query['order']=='address'?($toSchema?'toaddress':'fromaddress'):$query['order']); if (!empty($query['search'])) { if (is_null(Mail::$supportsORinQuery) || !isset(Mail::$supportsORinQuery[$mail_ui->mail_bo->profileID])) { Mail::$supportsORinQuery = egw_cache::getCache(egw_cache::INSTANCE,'email','supportsORinQuery'.trim($GLOBALS['egw_info']['user']['account_id']), null, array(), 60*60*10); if (!isset(Mail::$supportsORinQuery[$mail_ui->mail_bo->profileID])) { Mail::$supportsORinQuery[$mail_ui->mail_bo->profileID]=true; } } //$cutoffdate = egw_time::to('now','ts')-(3600*24*3);//SINCE, enddate //$cutoffdate2 = egw_time::to('now','ts');//-(3600*24*2);//BEFORE, startdate $filter = array( 'filterName' => (Mail::$supportsORinQuery[$mail_ui->mail_bo->profileID]?lang('quicksearch'):lang('subject')), 'type' => ($query['cat_id']?$query['cat_id']:(Mail::$supportsORinQuery[$mail_ui->mail_bo->profileID]?'quick':'subject')), 'string' => $query['search'], 'status' => 'any', //'range'=>"BETWEEN",'since'=> date("d-M-Y", $cutoffdate),'before'=> date("d-M-Y", $cutoffdate2) ); } else { $filter = array(); } if ($query['filter']) { $filter['status'] = $query['filter']; } $reverse = ($query['sort']=='ASC'?false:true); $prefchanged = false; if (!isset($GLOBALS['egw_info']['user']['preferences']['mail']['ActiveSearchType']) || ($query['cat_id'] !=$GLOBALS['egw_info']['user']['preferences']['mail']['ActiveSearchType'])) { //error_log(__METHOD__.__LINE__.' Changing userPref ActivesearchType:'.$query['cat_id']); $GLOBALS['egw']->preferences->add('mail','ActiveSearchType',$query['cat_id'],'user'); $prefchanged = true; } if (!isset($GLOBALS['egw_info']['user']['preferences']['mail']['ShowDetails']) || ($query['filter2'] !=$GLOBALS['egw_info']['user']['preferences']['mail']['ShowDetails'])) { $GLOBALS['egw']->preferences->add('mail','ShowDetails',$query['filter2'],'user'); $prefchanged = true; } if ($prefchanged) { // save prefs $GLOBALS['egw']->preferences->save_repository(true); } //error_log(__METHOD__.__LINE__.' maxMessages:'.$maxMessages.' Offset:'.$offset.' Filter:'.array2string($mail_ui->sessionData['messageFilter'])); /* $cutoffdate = egw_time::to('now','ts')-(3600*24*6);//SINCE, enddate $cutoffdate2 = egw_time::to('now','ts')-(3600*24*3);//BEFORE, startdate $filter['range'] = "BETWEEN";// we support SINCE, BEFORE, BETWEEN and ON $filter['since'] = date("d-M-Y", $cutoffdate); $filter['before']= date("d-M-Y", $cutoffdate2); */ try { if ($maxMessages > 75) { $_sR = $mail_ui->mail_bo->getSortedList( $_folderName, $sort, $reverse, $filter, $rByUid=true ); $rowsFetched['messages'] = $_sR['count']; $sR = $_sR['match']->ids; // if $sR is false, something failed fundamentally if($reverse === true) $sR = ($sR===false?array():array_reverse((array)$sR)); $sR = array_slice((array)$sR,($offset==0?0:$offset-1),$maxMessages); // we need only $maxMessages of uids $sRToFetch = $sR;//array_slice($sR,0,50); // we fetch only the headers of a subset of the fetched uids //error_log(__METHOD__.__LINE__.' Rows fetched (UID only):'.count($sR).' Data:'.array2string($sR)); $maxMessages = 75; $sortResultwH['header'] = array(); if (count($sRToFetch)>0) { //error_log(__METHOD__.__LINE__.' Headers to fetch with UIDs:'.count($sRToFetch).' Data:'.array2string($sRToFetch)); $sortResult = array(); // fetch headers $sortResultwH = $mail_ui->mail_bo->getHeaders( $_folderName, $offset, $maxMessages, $sort, $reverse, $filter, $sRToFetch, true, //cacheResult ($query['filter2']?true:false) // fetchPreview ); } } else { $sortResult = array(); // fetch headers $sortResultwH = $mail_ui->mail_bo->getHeaders( $_folderName, $offset, $maxMessages, $sort, $reverse, $filter, null, // this uids only true, // cacheResult ($query['filter2']?true:false) // fetchPreview ); $rowsFetched['messages'] = $sortResultwH['info']['total']; } } catch (Exception $e) { $sortResultwH=array(); $sR=array(); self::callWizard($e->getMessage(), false, 'error'); } $response = egw_json_response::get(); // unlock immediately after fetching the rows if (stripos($_GET['menuaction'],'ajax_get_rows')!==false) { //error_log(__METHOD__.__LINE__.' unlock tree ->'.$_GET['menuaction']); $response->call('app.mail.unlock_tree'); } if (is_array($sR) && count($sR)>0) { foreach ((array)$sR as $key => $v) { if (array_key_exists($key,(array)$sortResultwH['header'])==true) { $sortResult['header'][] = $sortResultwH['header'][$key]; } else { if (!empty($v)) $sortResult['header'][] = array('uid'=>$v); } } } else { $sortResult = $sortResultwH; } $rowsFetched['rowsFetched'] = count($sortResult['header']); if (empty($rowsFetched['messages'])) $rowsFetched['messages'] = $rowsFetched['rowsFetched']; //error_log(__METHOD__.__LINE__.' Rows fetched:'.$rowsFetched.' Data:'.array2string($sortResult)); $cols = array('row_id','uid','status','attachments','subject','address','toaddress','fromaddress','ccaddress','additionaltoaddress','date','size','modified','bodypreview'); if ($GLOBALS['egw_info']['user']['preferences']['common']['select_mode']=='EGW_SELECTMODE_TOGGLE') unset($cols[0]); $rows = $mail_ui->header2gridelements($sortResult['header'],$cols, $_folderName, $folderType=$toSchema); //error_log(__METHOD__.__LINE__.array2string($rows)); if (Mail::$debugTimes) Mail::logRunTimes($starttime,null,'Folder:'.$_folderName.' Start:'.$query['start'].' NumRows:'.$query['num_rows'],__METHOD__.__LINE__); return $rowsFetched['messages']; } /** * function createRowID - create a unique rowID for the grid * * @param string $_folderName used to ensure the uniqueness of the uid over all folders * @param string $message_uid the message_Uid to be used for creating the rowID * @param boolean $_prependApp to indicate that the app 'mail' is to be used for creating the rowID * @return string - a colon separated string in the form [app:]accountID:profileID:folder:message_uid */ function createRowID($_folderName, $message_uid, $_prependApp=false) { return self::generateRowID($this->mail_bo->profileID, $_folderName, $message_uid, $_prependApp); } /** * static function generateRowID - create a unique rowID for the grid * * @param integer $_profileID profile ID for the rowid to be used * @param string $_folderName to ensure the uniqueness of the uid over all folders * @param string $message_uid the message_Uid to be used for creating the rowID * @param boolean $_prependApp to indicate that the app 'mail' is to be used for creating the rowID * @return string - a colon separated string in the form [app:]accountID:profileID:folder:message_uid */ static function generateRowID($_profileID, $_folderName, $message_uid, $_prependApp=false) { return ($_prependApp?'mail'.self::$delimiter:'').trim($GLOBALS['egw_info']['user']['account_id']).self::$delimiter.$_profileID.self::$delimiter.base64_encode($_folderName).self::$delimiter.$message_uid; } /** * function splitRowID - split the rowID into its parts * * @param string $_rowID string - a colon separated string in the form accountID:profileID:folder:message_uid * @return array populated named result array (accountID,profileID,folder,msgUID) */ static function splitRowID($_rowID) { $res = explode(self::$delimiter,$_rowID); // as a rowID is perceeded by app::, should be mail! //error_log(__METHOD__.__LINE__.array2string($res).' [0] isInt:'.is_int($res[0]).' [0] isNumeric:'.is_numeric($res[0]).' [0] isString:'.is_string($res[0]).' Count:'.count($res)); if (count($res)==4 && is_numeric($res[0]) ) { // we have an own created rowID; prepend app=mail array_unshift($res,'mail'); } return array('app'=>$res[0], 'accountID'=>$res[1], 'profileID'=>$res[2], 'folder'=>base64_decode($res[3]), 'msgUID'=>$res[4]); } /** * Get actions for preview toolbar * * @return array */ function get_toolbar_actions() { $actions = $this->get_actions(); $arrActions = array('composeasnew', 'reply', 'reply_all', 'forward', 'flagged', 'delete', 'print', 'infolog', 'tracker', 'calendar', 'save', 'view', 'read', 'label1', 'label2', 'label3', 'label4', 'label5'); foreach( $arrActions as &$act) { //error_log(__METHOD__.__LINE__.' '.$act.'->'.array2string($actions[$act])); switch ($act) { case 'forward': $actionsenabled[$act]=$actions[$act]; break; case 'save': $actionsenabled[$act]=$actions[$act]; break; case 'view': $actionsenabled[$act]=$actions[$act]; break; case 'flagged': $actionsenabled[$act]= $actions['mark']['children'][$act]; break; case 'read': $actionsenabled[$act]= $actions['mark']['children'][$act]; break; case 'label1': $actions['mark']['children']['setLabel']['children'][$act]['caption'] = lang('important'); $actionsenabled[$act]= $actions['mark']['children']['setLabel']['children'][$act]; break; case 'label2': $actions['mark']['children']['setLabel']['children'][$act]['caption'] = lang('job'); $actionsenabled[$act]= $actions['mark']['children']['setLabel']['children'][$act]; break; case 'label3': $actions['mark']['children']['setLabel']['children'][$act]['caption'] = lang('personal'); $actionsenabled[$act]= $actions['mark']['children']['setLabel']['children'][$act]; break; case 'label4': $actions['mark']['children']['setLabel']['children'][$act]['caption'] = lang('to do'); $actionsenabled[$act]= $actions['mark']['children']['setLabel']['children'][$act]; break; case 'label5': $actions['mark']['children']['setLabel']['children'][$act]['caption'] = lang('later'); $actionsenabled[$act]= $actions['mark']['children']['setLabel']['children'][$act]; break; default: if (isset($actions[$act])) $actionsenabled[$act]=$actions[$act]; } } unset($actionsenabled['drag_mail']); //error_log(array2string($actionsenabled['view'])); unset($actionsenabled['view']['children']['openastext']);//not supported in preview unset($actionsenabled['view']['children']['openashtml']);//not supported in preview return $actionsenabled; } /** * function header2gridelements - to populate the grid elements with the collected Data * * @param array $_headers headerdata to process * @param array $cols cols to populate * @param array $_folderName to ensure the uniqueness of the uid over all folders * @param array $_folderType used to determine if we need to populate from/to * @return array populated result array */ public function header2gridelements($_headers, $cols, $_folderName, $_folderType=0) { if (Mail::$debugTimes) $starttime = microtime(true); $rv = array(); $i=0; foreach((array)$_headers as $header) { $i++; $data = array(); //error_log(__METHOD__.array2string($header)); $message_uid = $header['uid']; $data['uid'] = $message_uid; $data['row_id']=$this->createRowID($_folderName,$message_uid); $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"; if(!empty($header['label1'])) $flags .= "1"; if(!empty($header['label2'])) $flags .= "2"; if(!empty($header['label3'])) $flags .= "3"; if(!empty($header['label4'])) $flags .= "4"; if(!empty($header['label5'])) $flags .= "5"; $data["status"] = ""; //error_log(__METHOD__.array2string($header).' Flags:'.$flags); // the css for this row $is_recent=false; $css_styles = array("mail"); if ($header['deleted']) { $css_styles[] = 'deleted'; } if ($header['recent'] && !($header['deleted'] || $header['seen'] || $header['answered'] || $header['forwarded'])) { $css_styles[] = 'recent'; $is_recent=true; } if ($header['priority'] < 3) { $css_styles[] = 'prio_high'; } if ($header['flagged']) { $css_styles[] = 'flagged'; } if (!$header['seen']) { $css_styles[] = 'unseen'; // different status image for recent // solved via css !important } if ($header['answered']) { $css_styles[] = 'replied'; } if ($header['forwarded']) { $css_styles[] = 'forwarded'; } if ($header['label1']) { $css_styles[] = 'labelone'; } if ($header['label2']) { $css_styles[] = 'labeltwo'; } if ($header['label3']) { $css_styles[] = 'labelthree'; } if ($header['label4']) { $css_styles[] = 'labelfour'; } if ($header['label5']) { $css_styles[] = 'labelfive'; } //error_log(__METHOD__.array2string($css_styles)); if (in_array("subject", $cols)) { // 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']); // curly brackets get messed up by the template! if (!empty($header['subject'])) { // make the subject shorter if it is to long $subject = $header['subject']; } else { $subject = '('. lang('no subject') .')'; } $data["subject"] = $subject; // the mailsubject } $imageHTMLBlock = ''; //error_log(__METHOD__.__LINE__.array2string($header)); if (in_array("attachments", $cols)) { if($header['mimetype'] == 'multipart/mixed' || $header['mimetype'] == 'multipart/signed' || $header['mimetype'] == 'multipart/related' || $header['mimetype'] == 'multipart/report' || $header['mimetype'] == 'text/calendar' || $header['mimetype'] == 'text/html' || substr($header['mimetype'],0,11) == 'application' || substr($header['mimetype'],0,5) == 'audio' || substr($header['mimetype'],0,5) == 'video' || $header['mimetype'] == 'multipart/alternative') { $image = html::image('mail','attach'); $imageHTMLBlock = ''; $datarowid = $this->createRowID($_folderName,$message_uid,true); $attachments = $header['attachments']; if (count($attachments)<1) { $image = ' '; } if (count($attachments)==1) { $imageHTMLBlock = self::createAttachmentBlock($attachments, $datarowid, $header['uid'],$_folderName); $image = html::image('mail','attach',$attachments[0]['name'].(!empty($attachments[0]['mimeType'])?' ('.$attachments[0]['mimeType'].')':'')); } if (count($attachments)>1) { $imageHTMLBlock = self::createAttachmentBlock($attachments, $datarowid, $header['uid'],$_folderName); $image = html::image('mail','attach',lang('%1 attachments',count($attachments))); } $attachmentFlag = $image; } else { $attachmentFlag =' '; } // show priority flag if ($header['priority'] < 3) { $image = html::image('mail','prio_high'); } elseif ($header['priority'] > 3) { $image = html::image('mail','prio_low'); } else { $image = ''; } // show a flag for flagged messages $imageflagged =''; if ($header['flagged']) { $imageflagged = html::image('mail','unread_flagged_small'); } $data["attachments"] = $image.$attachmentFlag.$imageflagged; // icon for attachments available } // sent or draft or template folder -> to address if (in_array("toaddress", $cols)) { // sent or drafts or template folder means foldertype > 0, use to address instead of from $data["toaddress"] = $header['to_address'];//Mail::htmlentities($header['to_address'],$this->charset); } if (in_array("additionaltoaddress", $cols)) { $data['additionaltoaddress'] = $header['additional_to_addresses']; } //fromaddress if (in_array("fromaddress", $cols)) { $data["fromaddress"] = $header['sender_address']; } if (in_array("ccaddress", $cols)) { $data['ccaddress'] = $header['cc_addresses']; } if (in_array("date", $cols)) { $data["date"] = $header['date']; } if (in_array("modified", $cols)) { $data["modified"] = $header['internaldate']; } if (in_array("size", $cols)) $data["size"] = $header['size']; /// size $data["class"] = implode(' ', $css_styles); //translate style-classes back to flags $data['flags'] = Array(); if ($header['seen']) $data["flags"]['read'] = 'read'; foreach ($css_styles as &$flag) { if ($flag!='mail') { if ($flag=='labelone') {$data["flags"]['label1'] = 'label1';} elseif ($flag=='labeltwo') {$data["flags"]['label2'] = 'label2';} elseif ($flag=='labelthree') {$data["flags"]['label3'] = 'label3';} elseif ($flag=='labelfour') {$data["flags"]['label4'] = 'label4';} elseif ($flag=='labelfive') {$data["flags"]['label5'] = 'label5';} elseif ($flag=='unseen') {unset($data["flags"]['read']);} else $data["flags"][$flag] = $flag; } } if ($header['disposition-notification-to']) $data['dispositionnotificationto'] = $header['disposition-notification-to']; if (($header['mdnsent']||$header['mdnnotsent']|$header['seen'])&&isset($data['dispositionnotificationto'])) unset($data['dispositionnotificationto']); $data['attachmentsBlock'] = $imageHTMLBlock; $data['address'] = ($_folderType?$data["toaddress"]:$data["fromaddress"]); if (in_array("bodypreview", $cols)&&$header['bodypreview']) { $data["bodypreview"] = $header['bodypreview']; } $rv[] = $data; //error_log(__METHOD__.__LINE__.array2string($data)); } if (Mail::$debugTimes) Mail::logRunTimes($starttime,null,'Folder:'.$_folderName,__METHOD__.__LINE__); // ToDo: call this ONLY if labels change etemplate_widget::setElementAttribute('toolbar', 'actions', $this->get_toolbar_actions()); return $rv; } /** * display messages header lines * * all params are passed as GET Parameters */ function displayHeader() { if(isset($_GET['id'])) $rowID = $_GET['id']; if(isset($_GET['part'])) $partID = $_GET['part']; $hA = self::splitRowID($rowID); $uid = $hA['msgUID']; $mailbox = $hA['folder']; $icServerID = $hA['profileID']; $rememberServerID = $this->mail_bo->profileID; if ($icServerID && $icServerID != $this->mail_bo->profileID) { //error_log(__METHOD__.__LINE__.' change Profile to ->'.$icServerID); $this->changeProfile($icServerID); } $this->mail_bo->reopen($mailbox); $rawheaders = $this->mail_bo->getMessageRawHeader($uid, $partID); // 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->mail_bo->closeConnection(); if ($rememberServerID != $this->mail_bo->profileID) { //error_log(__METHOD__.__LINE__.' change Profile back to where we came from->'.$rememberServerID); $this->changeProfile($rememberServerID); } header('Content-type: text/html; charset=iso-8859-1'); print '
'. htmlspecialchars($rawheaders, ENT_NOQUOTES, 'iso-8859-1') .''; } /** * display messages * @param array $_requesteddata etemplate content * all params are passed as GET Parameters, but can be passed via ExecMethod2 as array too */ function displayMessage($_requesteddata = null) { if (is_null($_requesteddata)) $_requesteddata = $_GET; $preventRedirect=false; if(isset($_requesteddata['id'])) $rowID = $_requesteddata['id']; if(isset($_requesteddata['part'])) $partID = $_requesteddata['part']!='null'?$_requesteddata['part']:null; if(isset($_requesteddata['mode'])) $preventRedirect = (($_requesteddata['mode']=='display' || $_requesteddata['mode'] == 'print')?true:false); $hA = self::splitRowID($rowID); $uid = $hA['msgUID']; $mailbox = $hA['folder']; $icServerID = $hA['profileID']; $rememberServerID = $this->mail_bo->profileID; if ($icServerID && $icServerID != $this->mail_bo->profileID) { //error_log(__METHOD__.__LINE__.' change Profile to ->'.$icServerID); $this->changeProfile($icServerID); } $htmlOptions = $this->mail_bo->htmlOptions; if (!empty($_requesteddata['tryastext'])) $htmlOptions = "only_if_no_text"; if (!empty($_requesteddata['tryashtml'])) $htmlOptions = "always_display"; //error_log(__METHOD__.__LINE__.array2string($hA)); if (($this->mail_bo->isDraftFolder($mailbox)) && $_requesteddata['mode'] == 'print') { $response = egw_json_response::get(); $response->call('app.mail.print_for_compose', $rowID); } if (!$preventRedirect && ($this->mail_bo->isDraftFolder($mailbox) || $this->mail_bo->isTemplateFolder($mailbox))) { egw::redirect_link('/index.php',array('menuaction'=>'mail.mail_compose.compose','id'=>$rowID,'from'=>'composefromdraft')); } $this->mail_bo->reopen($mailbox); // retrieve the flags of the message, before touching it. try { $headers = $this->mail_bo->getMessageHeader($uid, $partID,true,true,$mailbox); } catch (egw_exception $e) { $error_msg[] = lang("ERROR: Message could not be displayed."); $error_msg[] = lang("In Mailbox: %1, with ID: %2, and PartID: %3",$mailbox,$uid,$partID); egw_framework::message($e->getMessage(), 'error'); } if (!empty($uid)) $this->mail_bo->getFlags($uid); $envelope = $this->mail_bo->getMessageEnvelope($uid, $partID,true,$mailbox); //error_log(__METHOD__.__LINE__.array2string($envelope)); $this->mail_bo->getMessageRawHeader($uid, $partID,$mailbox); $fetchEmbeddedImages = false; // if we are in HTML so its likely that we should show the embedded images; as a result // we do NOT want to see those, that are embedded in the list of attachments if ($htmlOptions !='always_display') $fetchEmbeddedImages = true; $attachments = $this->mail_bo->getMessageAttachments($uid, $partID, null, $fetchEmbeddedImages,true,true,$mailbox); //error_log(__METHOD__.__LINE__.array2string($attachments)); $attachmentHTMLBlock = self::createAttachmentBlock($attachments, $rowID, $uid, $mailbox); $nonDisplayAbleCharacters = array('[\016]','[\017]', '[\020]','[\021]','[\022]','[\023]','[\024]','[\025]','[\026]','[\027]', '[\030]','[\031]','[\032]','[\033]','[\034]','[\035]','[\036]','[\037]'); //error_log(__METHOD__.__LINE__.$mailBody); $this->mail_bo->closeConnection(); //$GLOBALS['egw_info']['flags']['currentapp'] = 'mail';//should not be needed $etpl = new etemplate_new('mail.display'); $subject = $this->mail_bo->decode_subject(preg_replace($nonDisplayAbleCharacters,'',$envelope['SUBJECT']),false); // Set up data for taglist widget(s) if ($envelope['FROM']==$envelope['SENDER']) unset($envelope['SENDER']); foreach(array('SENDER','FROM','TO','CC','BCC') as $field) { if (!isset($envelope[$field])) continue; foreach($envelope[$field] as $field_data) { //error_log(__METHOD__.__LINE__.array2string($field_data)); $content[$field][] = $field_data; $sel_options[$field][] = array( // taglist requires these - not optional 'id' => $field_data, 'label' => str_replace('"',"'",$field_data), ); } } $actionsenabled = $this->getDisplayToolbarActions(); $content['displayToolbaractions'] = json_encode($actionsenabled); if (empty($subject)) $subject = lang('no subject'); $content['msg'] = (is_array($error_msg)?implode("
".$row['link_view'].' | ';
$attachmentHTMLBlock .= "".$row['mimetype'].' | '; $attachmentHTMLBlock .= "".$row['size'].' | '; $attachmentHTMLBlock .= "".$row['link_save'].' |
'. htmlspecialchars($message, ENT_NOQUOTES|ENT_SUBSTITUTE, 'utf-8') .''; } } /** * Save an Message in the vfs * * @param string|array $ids use splitRowID, to separate values * @param string $path path in vfs (no egw_vfs::PREFIX!), only directory for multiple id's ($ids is an array) * @param boolean $close Return javascript to close the window * @return string|boolean javascript eg. to close the selector window if $close is true, or success/fail if $close is false */ function vfsSaveMessage($ids,$path, $close = true) { //error_log(__METHOD__.' IDs:'.array2string($ids).' SaveToPath:'.$path); 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)).'"); egw(window).close();'; } translation::add_app('mail'); $rememberServerID = $this->mail_bo->profileID; foreach((array)$ids as $id) { $hA = self::splitRowID($id); $uid = $hA['msgUID']; $mailbox = $hA['folder']; $icServerID = $hA['profileID']; if ($icServerID && $icServerID != $this->mail_bo->profileID) { //error_log(__METHOD__.__LINE__.' change Profile to ->'.$icServerID); $this->changeProfile($icServerID); } $message = $this->mail_bo->getMessageRawBody($uid, $partID='', $mailbox); $err=null; if(egw_vfs::is_dir($path)) { $headers = $this->mail_bo->getMessageHeader($uid,$partID,true,false,$mailbox); $file = $path . '/'.preg_replace('/[\f\n\t\v\\:*#?<>\|]/',"_",$headers['SUBJECT']).'.eml'; } else { $file = $path; } if (!($fp = egw_vfs::fopen($file,'wb')) || !fwrite($fp,$message)) { $err .= lang('Error saving %1!',$file); $succeeded = false; } else { $succeeded = true; } if ($fp) fclose($fp); if ($succeeded) { unset($headers['SUBJECT']);//already in filename $infoSection = Mail::createHeaderInfoSection($headers, 'SUPPRESS', false); $props = array(array('name' => 'comment','val' => $infoSection)); egw_vfs::proppatch($file,$props); } } if ($rememberServerID != $this->mail_bo->profileID) { //error_log(__METHOD__.__LINE__.' change Profile back to where we came from ->'.$rememberServerID); $this->changeProfile($rememberServerID); } if($close) { egw_framework::window_close(($err?$err:null)); } else { return $succeeded; } } /** * Save an attachment in the vfs * * @param string|array $ids '::' delimited 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) { //error_log(__METHOD__.__LINE__.'("'.array2string($ids).'","'.$path."\")');"); 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)).'"); egw(window).close();'; } $err=null; $dupe_count = array(); $rememberServerID = $this->mail_bo->profileID; /** * Extract all parameteres from the given id * @param int $id message id ('::' delimited mailbox::uid::part-id::is_winmail::name) * * @return array an array of parameters */ $getParams = function ($id) { list($app,$user,$serverID,$mailbox,$uid,$part,$is_winmail,$name) = explode('::',$id,8); $lId = implode('::',array($app,$user,$serverID,$mailbox,$uid)); $hA = mail_ui::splitRowID($lId); return array( 'is_winmail' => $is_winmail == "null" || !$is_winmail?false:$is_winmail, 'user' => $user, 'name' => $name, 'part' => $part, 'uid' => $hA['msgUID'], 'mailbox' => $hA['folder'], 'icServer' => $hA['profileID'] ); }; //Examine the first attachment to see if attachment //is winmail.dat embedded attachments. $isMultipleDownload=is_array($ids); $p = $getParams((is_array($ids)?$ids[0]:$ids)); if ($p['is_winmail']) { if ($p['icServer'] && $p['icServer'] != $this->mail_bo->profileID) { $this->changeProfile($p['icServer']); } $this->mail_bo->reopen($p['mailbox']); // Retrive all embedded attachments at once // avoids to fetch heavy winmail.dat content // for each file. $attachments = $this->mail_bo->getTnefAttachments($p['uid'],$p['part']); } foreach((array)$ids as $id) { $params = $getParams($id); // when downloading a single file, name is not set if (!$params['name']&&isset($_GET['name'])&&!$isMultipleDownload) $params['name'] = $_GET['name']; if ($params['icServer'] && $params['icServer'] != $this->mail_bo->profileID) { //error_log(__METHOD__.__LINE__.' change Profile to ->'.$icServerID); $this->changeProfile($params['icServer']); } //error_log(__METHOD__.__LINE__.array2string($hA)); $this->mail_bo->reopen($params['mailbox']); if ($params['is_winmail']) { // Try to find the right content for file id foreach ($attachments as $key => $val) { if ($key == $params['is_winmail']) $attachment = $val; } } else { $attachment = $this->mail_bo->getAttachment($params['uid'],$params['part'],$params['is_winmail'],false); } $file = $params['name']; // when $isMultipleDownload the path holds no filename while(egw_vfs::file_exists($path.($file && $isMultipleDownload ? '/'.$file : ''))) { $dupe_count[$params['name']]++; $file = pathinfo($params['name'], PATHINFO_FILENAME) . ' ('.($dupe_count[$params['name']] + 1).')' . '.' . pathinfo($params['name'], PATHINFO_EXTENSION); } $params['name'] = $file; //error_log(__METHOD__.__LINE__.array2string($attachment)); // when $isMultipleDownload the path holds no filename if (!($fp = egw_vfs::fopen($file=$path.($params['name'] && $isMultipleDownload ? '/'.$params['name'] : ''),'wb')) || !fwrite($fp,$attachment['attachment'])) { $err .= lang('Error saving %1!',$file); } if ($fp) { fclose($fp); } } $this->mail_bo->closeConnection(); if ($rememberServerID != $this->mail_bo->profileID) { //error_log(__METHOD__.__LINE__.' change Profile back to where we came from ->'.$rememberServerID); $this->changeProfile($rememberServerID); } egw_framework::window_close(($err?$err:null)); } /** * Zip all attachments and send to user * @param string $message_id = null */ function download_zip($message_id=null) { //error_log(__METHOD__.__LINE__.array2string($_GET)); // First, get all attachment IDs if(isset($_GET['id'])) $message_id = $_GET['id']; //error_log(__METHOD__.__LINE__.$message_id); $rememberServerID = $this->mail_bo->profileID; if(!is_numeric($message_id)) { $hA = self::splitRowID($message_id); $message_id = $hA['msgUID']; $mailbox = $hA['folder']; $icServerID = $hA['profileID']; if ($icServerID && $icServerID != $this->mail_bo->profileID) { //error_log(__METHOD__.__LINE__.' change Profile to ->'.$icServerID); $this->changeProfile($icServerID); } } else { $mailbox = $this->mail_bo->sessionData['mailbox']; } // always fetch all, even inline (images) $fetchEmbeddedImages = true; $attachments = $this->mail_bo->getMessageAttachments($message_id,null, null, $fetchEmbeddedImages, true,true,$mailbox); // put them in VFS so they can be zipped $header = $this->mail_bo->getMessageHeader($message_id,'',true,false,$mailbox); //get_home_dir may fetch the users startfolder if set; if not writeable, action will fail. TODO: use temp_dir $homedir = '/home/'.$GLOBALS['egw_info']['user']['account_lid']; $temp_path = $homedir/*egw_vfs::get_home_dir()*/ . "/.mail_$message_id"; if(egw_vfs::is_dir($temp_path)) egw_vfs::remove ($temp_path); // Add subject to path, so it gets used as the file name $path = $temp_path . '/' . ($header['SUBJECT'] ? egw_vfs::encodePathComponent($header['SUBJECT']) : lang('mail')) .'/'; if(!egw_vfs::mkdir($path, 0700, true)) { egw_framework::message("Unable to open temp directory $path",'error'); return; } $file_list = array(); $dupe_count = array(); $this->mail_bo->reopen($mailbox); if ($attachments[0]['is_winmail'] && $attachments[0]['is_winmail']!='null') { $tnefAttachments = $this->mail_bo->getTnefAttachments($message_id, $attachments[0]['partID'],true); } foreach($attachments as $file) { if ($file['is_winmail']) { // Try to find the right content for file id foreach ($tnefAttachments as $key => $val) { error_log(__METHOD__.' winmail = '.$key); if ($key == $file['is_winmail']) $attachment = $val; } } else { $attachment = $this->mail_bo->getAttachment($message_id,$file['partID'],$file['is_winmail'],false,true); } $success=true; if (empty($file['filename'])) $file['filename'] = $file['name']; if(in_array($path.$file['filename'], $file_list)) { $dupe_count[$path.$file['filename']]++; $file['filename'] = pathinfo($file['filename'], PATHINFO_FILENAME) . ' ('.($dupe_count[$path.$file['filename']] + 1).')' . '.' . pathinfo($file['filename'], PATHINFO_EXTENSION); } if (!($fp = egw_vfs::fopen($path.$file['filename'],'wb')) || !(!fseek($attachment['attachment'], 0, SEEK_SET) && stream_copy_to_stream($attachment['attachment'], $fp))) { $success=false; egw_framework::message("Unable to zip {$file['filename']}",'error'); } if ($success) $file_list[] = $path.$file['filename']; if ($fp) fclose($fp); } $this->mail_bo->closeConnection(); if ($rememberServerID != $this->mail_bo->profileID) { //error_log(__METHOD__.__LINE__.' change Profile back to where we came from ->'.$rememberServerID); $this->changeProfile($rememberServerID); } // Zip it up egw_vfs::download_zip($file_list); // Clean up egw_vfs::remove($temp_path); common::egw_exit(); } function get_load_email_data($uid, $partID, $mailbox,$htmlOptions=null) { // seems to be needed, as if we open a mail from notification popup that is // located in a different folder, we experience: could not parse message $this->mail_bo->reopen($mailbox); $this->mailbox = $mailbox; $this->uid = $uid; $this->partID = $partID; $bufferHtmlOptions = $this->mail_bo->htmlOptions; if (empty($htmlOptions)) $htmlOptions = $this->mail_bo->htmlOptions; // fetching structure now, to supply it to getMessageBody and getMessageAttachment, so it does not get fetched twice $structure = $this->mail_bo->getStructure($uid, $partID, $mailbox, false); $bodyParts = $this->mail_bo->getMessageBody($uid, ($htmlOptions?$htmlOptions:''), $partID, $structure, false, $mailbox); //error_log(__METHOD__.__LINE__.array2string($bodyParts)); // attachments here are only fetched to determine if there is a meeting request // and if. use the appropriate action. so we do not need embedded images $fetchEmbeddedImages = false; $attachments = (array)$this->mail_bo->getMessageAttachments($uid, $partID, $structure, $fetchEmbeddedImages, true,true,$mailbox); //error_log(__METHOD__.__LINE__.array2string($attachments)); foreach ($attachments as &$attach) { if (strtolower($attach['mimeType']) == 'text/calendar' && isset($GLOBALS['egw_info']['user']['apps']['calendar']) && ($attachment = $this->mail_bo->getAttachment($uid, $attach['partID'],$attach['is_winmail'],(strtolower($attach['mimeType']) == 'text/calendar'?false:true)))) { //error_log(__METHOD__.__LINE__.array2string($attachment)); egw_cache::setSession('calendar', 'ical', array( 'charset' => $attach['charset'] ? $attach['charset'] : 'utf-8', 'attachment' => $attachment['attachment'], 'method' => $attach['method'], 'sender' => $mailbox, )); $this->mail_bo->htmlOptions = $bufferHtmlOptions; translation::add_app('calendar'); return ExecMethod( 'calendar.calendar_uiforms.meeting', array('event'=>null,'msg'=>'','useSession'=>true) ); } } // Compose the content of the frame $frameHtml = $this->get_email_header($this->mail_bo->getStyles($bodyParts)). $this->showBody($this->getdisplayableBody($bodyParts,true,false), false); //IE10 eats away linebreaks preceeded by a whitespace in PRE sections $frameHtml = str_replace(" \r\n","\r\n",$frameHtml); $this->mail_bo->htmlOptions = $bufferHtmlOptions; return $frameHtml; } static function get_email_header($additionalStyle='') { // egw_info[flags][css] already include