public function getMessages($from = 0, $count = 2) { $total = $this->getTotalMessages(); if ($from + $count > $total) { $count = $total - $from; } $headers = array(); $fetch_query = new \Horde_Imap_Client_Fetch_Query(); $fetch_query->envelope(); $fetch_query->flags(); $fetch_query->seq(); $fetch_query->size(); $fetch_query->uid(); $fetch_query->imapDate(); $headers = array_merge($headers, array('importance', 'list-post', 'x-priority')); $headers[] = 'content-type'; $fetch_query->headers('imp', $headers, array('cache' => true, 'peek' => true)); $opt = array('ids' => $from + 1 . ':' . ($from + 1 + $count)); $opt = array(); // $list is an array of Horde_Imap_Client_Data_Fetch objects. $headers = $this->conn->fetch($this->folder_id, $fetch_query, $opt); ob_start(); // fix for Horde warnings $messages = array(); foreach ($headers as $message_id => $header) { $message = new Message($this->conn, $this->folder_id, $message_id); $message->setInfo($header); $messages[] = $message->getListArray(); } ob_clean(); return $messages; }
public function getMessages($from = 0, $count = 2, $filter = '') { if ($filter instanceof Horde_Imap_Client_Search_Query) { $query = $filter; } else { $query = new Horde_Imap_Client_Search_Query(); if ($filter) { $query->text($filter, false); } } if ($this->getSpecialRole() !== 'trash') { $query->flag(Horde_Imap_Client::FLAG_DELETED, false); } $result = $this->conn->search($this->mailBox, $query, ['sort' => [Horde_Imap_Client::SORT_DATE]]); $ids = array_reverse($result['match']->ids); if ($from >= 0 && $count >= 0) { $ids = array_slice($ids, $from, $count); } $ids = new \Horde_Imap_Client_Ids($ids, false); $headers = []; $fetch_query = new \Horde_Imap_Client_Fetch_Query(); $fetch_query->envelope(); $fetch_query->flags(); $fetch_query->size(); $fetch_query->uid(); $fetch_query->imapDate(); $fetch_query->structure(); $headers = array_merge($headers, ['importance', 'list-post', 'x-priority']); $headers[] = 'content-type'; $fetch_query->headers('imp', $headers, ['cache' => true, 'peek' => true]); $options = ['ids' => $ids]; // $list is an array of Horde_Imap_Client_Data_Fetch objects. $headers = $this->conn->fetch($this->mailBox, $fetch_query, $options); ob_start(); // fix for Horde warnings $messages = []; foreach ($headers->ids() as $message_id) { $header = $headers[$message_id]; $message = new Message($this->conn, $this->mailBox, $message_id, $header); $messages[] = $message->getListArray(); } ob_get_clean(); // sort by time usort($messages, function ($a, $b) { return $a['dateInt'] < $b['dateInt']; }); return $messages; }
/** */ public function getLog(IMP_Maillog_Message $msg, array $types = array()) { $log_ob = new IMP_Maillog_Log_Mdn(); if (!empty($types) && !in_array('IMP_Maillog_Log_Mdn', $types) || !$this->isAvailable($msg, $log_ob)) { return array(); } list($mbox, $uid) = $msg->indices->getSingle(); $imp_imap = $mbox->imp_imap; $query = new Horde_Imap_Client_Fetch_Query(); $query->flags(); try { $flags = $imp_imap->fetch($mbox, $query, array('ids' => $imp_imap->getIdsOb($uid)))->first()->getFlags(); } catch (IMP_Imap_Exception $e) { $flags = array(); } return in_array(Horde_Imap_Client::FLAG_MDNSENT, $flags) ? array($log_ob) : array(); }
/** */ public function getLog(IMP_Maillog_Message $msg, array $filter = array()) { if (!$msg->indices || in_array('mdn', $filter)) { return array(); } list($mbox, $uid) = $msg->indices->getSingle(); if (!$mbox->permflags->allowed(Horde_Imap_Client::FLAG_MDNSENT)) { return array(); } $query = new Horde_Imap_Client_Fetch_Query(); $query->flags(); $imp_imap = $mbox->imp_imap; try { $flags = $imp_imap->fetch($mbox, $query, array('ids' => $imp_imap->getIdsOb($uid)))->first()->getFlags(); } catch (IMP_Imap_Exception $e) { $flags = array(); } return in_array(Horde_Imap_Client::FLAG_MDNSENT, $flags) ? array(new IMP_Maillog_Log_Mdn()) : array(); }
/** * Return a folder object containing all IMAP server change information. * * @param array $options An array of options. * @see Horde_ActiveSync_Imap_Adapter::getMessageChanges * * @return Horde_ActiveSync_Folder_Base The populated folder object. */ public function getChanges(array $options) { $this->_logger->info(sprintf('[%s] NO CONDSTORE or per mailbox MODSEQ. minuid: %s, total_messages: %s', $this->_procid, $this->_folder->minuid(), $this->_status['messages'])); $query = new Horde_Imap_Client_Search_Query(); if (!empty($options['sincedate'])) { $query->dateSearch(new Horde_Date($options['sincedate']), Horde_Imap_Client_Search_Query::DATE_SINCE); } try { $search_ret = $this->_imap_ob->search($this->_mbox, $query, array('results' => array(Horde_Imap_Client::SEARCH_RESULTS_MATCH))); } catch (Horde_Imap_Client_Exception $e) { $this->_logger->err($e->getMessage()); throw new Horde_ActiveSync_Exception($e); } $cnt = $search_ret['count'] / Horde_ActiveSync_Imap_Adapter::MAX_FETCH + 1; $query = new Horde_Imap_Client_Fetch_Query(); $query->flags(); $flags = array(); for ($i = 0; $i <= $cnt; $i++) { $ids = new Horde_Imap_Client_Ids(array_slice($search_ret['match']->ids, $i * Horde_ActiveSync_Imap_Adapter::MAX_FETCH, Horde_ActiveSync_Imap_Adapter::MAX_FETCH)); try { $fetch_ret = $this->_imap_ob->fetch($this->_mbox, $query, array('ids' => $ids)); } catch (Horde_Imap_Client_Exception $e) { $this->_logger->err($e->getMessage()); throw new Horde_ActiveSync_Exception($e); } foreach ($fetch_ret as $uid => $data) { $flags[$uid] = array('read' => array_search(Horde_Imap_Client::FLAG_SEEN, $data->getFlags()) !== false ? 1 : 0); if ($options['protocolversion'] > Horde_ActiveSync::VERSION_TWOFIVE) { $flags[$uid]['flagged'] = array_search(Horde_Imap_Client::FLAG_FLAGGED, $data->getFlags()) !== false ? 1 : 0; } } } if (!empty($flags)) { $this->_folder->setChanges($search_ret['match']->ids, $flags); } $this->_folder->setRemoved($this->_imap_ob->vanished($this->_mbox, null, array('ids' => new Horde_Imap_Client_Ids($this->_folder->messages())))->ids); return $this->_folder; }
private function getmsg() { $headers = array(); $fetch_query = new \Horde_Imap_Client_Fetch_Query(); $fetch_query->envelope(); // $fetch_query->fullText(); $fetch_query->bodyText(); $fetch_query->flags(); $fetch_query->seq(); $fetch_query->size(); $fetch_query->uid(); $fetch_query->imapDate(); $headers = array_merge($headers, array('importance', 'list-post', 'x-priority')); $headers[] = 'content-type'; $fetch_query->headers('imp', $headers, array('cache' => true, 'peek' => true)); // $list is an array of Horde_Imap_Client_Data_Fetch objects. $ids = new \Horde_Imap_Client_Ids($this->message_id); $headers = $this->conn->fetch($this->folder_id, $fetch_query, array('ids' => $ids)); $this->plainmsg = $headers[$this->message_id]->getBodyText(); // // // HEADER // $this->header = $this->conn->fetchHeader($this->folder_id, $this->message_id); // // // BODY // $bodystructure= $this->conn->getStructure($this->folder_id, $this->message_id); // $a= \rcube_imap_generic::getStructurePartData($bodystructure, 0); // if ($a['type'] == 'multipart') { // for ($i=0; $i < count($bodystructure); $i++) { // if (!is_array($bodystructure[$i])) // break; // $this->getpart($bodystructure[$i],$i+1); // } // } else { // // get part no 1 // $this->getpart($bodystructure,1); // } }
/** * Check whether the message has the specified flag * * @param mixed $messageid * @param string $flag The flag to check * @return bool */ private function message_has_flag($messageid, $flag) { // Get the current mailbox. $mailbox = $this->get_mailbox(); // Grab messagedata including flags. $query = new \Horde_Imap_Client_Fetch_Query(); $query->flags(); $query->structure(); $messagedata = $this->client->fetch($mailbox, $query, array('ids' => $messageid))->first(); $flags = $messagedata->getFlags(); return in_array($flag, $flags); }
/** * URL Parameters: * a: (string) Action ID. * allto: (boolean) View all To addresses? * buid: (string) Browser UID. * t: (string) Token. */ protected function _init() { global $injector, $notification, $page_output, $prefs, $session; $imp_mailbox = $this->indices->mailbox->list_ob; $imp_mailbox->setIndex($this->indices); $mailbox_url = IMP_Minimal_Mailbox::url(array('mailbox' => $this->indices->mailbox)); /* Make sure we have a valid index. */ if (!$imp_mailbox->isValidIndex()) { $mailbox_url->add('a', 'm')->redirect(); } $imp_ui = $injector->getInstance('IMP_Message_Ui'); /* Run through action handlers */ $msg_delete = false; switch ($this->vars->a) { // 'd' = delete message case 'd': $old_index = $imp_mailbox->getIndex(); try { $session->checkToken($this->vars->t); $msg_delete = (bool) $injector->getInstance('IMP_Message')->delete($this->indices, array('mailboxob' => $imp_mailbox)); } catch (Horde_Exception $e) { $notification->push($e); } break; // 'u' = undelete message // 'u' = undelete message case 'u': $old_index = $imp_mailbox->getIndex(); $injector->getInstance('IMP_Message')->undelete($this->indices); break; // 'rs' = report spam // 'ri' = report innocent // 'rs' = report spam // 'ri' = report innocent case 'rs': case 'ri': $old_index = $imp_mailbox->getIndex(); $msg_delete = $injector->getInstance('IMP_Factory_Spam')->create($this->vars->a == 'rs' ? IMP_Spam::SPAM : IMP_Spam::INNOCENT)->report($this->indices, array('mailboxob' => $imp_mailbox)) === 1; break; } if ($msg_delete && $imp_ui->moveAfterAction($this->indices->mailbox)) { $imp_mailbox->setIndex(1); } /* We may have done processing that has taken us past the end of the * message array, so we will return to the mailbox. */ if (!$imp_mailbox->isValidIndex() || $msg_delete && $prefs->getValue('mailbox_return')) { $mailbox_url->add('s', $old_index)->redirect(); } /* Now that we are done processing, get the index and array index of * the current message. */ $msg_index = $imp_mailbox[$imp_mailbox->getIndex()]; $mailbox = $msg_index['m']; $uid = $msg_index['u']; $buid = $imp_mailbox->getBuid($mailbox, $uid); /* Get envelope/flag/header information. */ try { $imp_imap = $mailbox->imp_imap; /* Need to fetch flags before HEADERTEXT, because SEEN flag might * be set before we can grab it. */ $query = new Horde_Imap_Client_Fetch_Query(); $query->flags(); $flags_ret = $imp_imap->fetch($mailbox, $query, array('ids' => $imp_imap->getIdsOb($uid))); $query = new Horde_Imap_Client_Fetch_Query(); $query->envelope(); $fetch_ret = $imp_imap->fetch($mailbox, $query, array('ids' => $imp_imap->getIdsOb($uid))); } catch (IMP_Imap_Exception $e) { $mailbox_url->add('a', 'm')->redirect(); } $envelope = $fetch_ret->first()->getEnvelope(); $flags = $flags_ret->first()->getFlags(); /* Parse the message. */ try { $imp_contents = $injector->getInstance('IMP_Factory_Contents')->create(new IMP_Indices($imp_mailbox)); $mime_headers = $imp_contents->getHeaderAndMarkAsSeen(); } catch (IMP_Exception $e) { $mailbox_url->add('a', 'm')->redirect(); } /* Get the starting index for the current message and the message * count. */ $msgindex = $imp_mailbox->getIndex(); $msgcount = count($imp_mailbox); /* Generate the mailbox link. */ $mailbox_link = $mailbox_url->add('s', $msgindex); $self_link = self::url(array('buid' => $buid, 'mailbox' => $this->indices->mailbox)); /* Create the Identity object. */ $user_identity = $injector->getInstance('IMP_Identity'); /* Develop the list of headers to display. */ $basic_headers = $imp_ui->basicHeaders(); $display_headers = $msgAddresses = array(); if ($subject = $mime_headers->getValue('subject')) { /* Filter the subject text, if requested. */ $subject = Horde_String::truncate(IMP::filterText($subject), 50); } else { $subject = _("[No Subject]"); } $display_headers['subject'] = $subject; $format_date = $imp_ui->getLocalTime($envelope->date); if (!empty($format_date)) { $display_headers['date'] = $format_date; } /* Build From address links. */ $display_headers['from'] = $imp_ui->buildAddressLinks($envelope->from, null, false); /* Build To/Cc/Bcc links. */ foreach (array('to', 'cc', 'bcc') as $val) { $msgAddresses[] = $mime_headers->getValue($val); $addr_val = $imp_ui->buildAddressLinks($envelope->{$val}, null, false); if (!empty($addr_val)) { $display_headers[$val] = $addr_val; } } /* Check for the presence of mailing list information. */ $list_info = $imp_ui->getListInformation($mime_headers); /* See if the priority has been set. */ switch ($priority = $injector->getInstance('IMP_Mime_Headers')->getPriority($mime_headers)) { case 'high': case 'low': $basic_headers['priority'] = _("Priority"); $display_headers['priority'] = Horde_String::ucfirst($priority); break; } /* Set the status information of the message. */ $status = ''; $match_identity = $identity = null; if (!empty($msgAddresses)) { $match_identity = $identity = $user_identity->getMatchingIdentity($msgAddresses); if (is_null($identity)) { $identity = $user_identity->getDefault(); } } $flag_parse = $injector->getInstance('IMP_Flags')->parse(array('flags' => $flags, 'personal' => $match_identity)); foreach ($flag_parse as $val) { if ($abbrev = $val->abbreviation) { $status .= $abbrev; } elseif ($val instanceof IMP_Flag_User) { $status .= ' *' . Horde_String::truncate($val->label, 8) . '*'; } } /* Create the body of the message. */ $inlineout = $imp_contents->getInlineOutput(array('display_mask' => IMP_Contents::RENDER_INLINE, 'no_inline_all' => true)); $msg_text = $inlineout['msgtext']; $this->view->msg = nl2br($injector->getInstance('Horde_Core_Factory_TextFilter')->filter($msg_text, 'space2html')); $menu = array(); if ($this->indices->mailbox->access_deletemsgs) { $menu[] = in_array(Horde_Imap_Client::FLAG_DELETED, $flags) ? array(_("Undelete"), $self_link->copy()->add('a', 'u')) : array(_("Delete"), $self_link->copy()->add(array('a' => 'd', 't' => $session->getToken()))); } /* Add compose actions (Reply, Reply List, Reply All, Forward, * Redirect, Edit as New). */ if (IMP_Compose::canCompose()) { $clink_ob = new IMP_Compose_Link(); $clink_ob->args['buid'] = $buid; $clink_ob->args['mailbox'] = $this->indices->mailbox; $clink = $clink_ob->link()->add(array('identity' => $identity)); $menu[] = array(_("Reply"), $clink->copy()->add(array('a' => 'r'))); if ($list_info['reply_list']) { $menu[] = array(_("Reply to List"), $clink->copy()->add(array('a' => 'rl'))); } $addr_ob = clone $envelope->to; $addr_ob->add($envelope->cc); $addr_ob->setIteratorFilter(0, $user_identity->getAllFromAddresses()); if (count($addr_ob)) { $menu[] = array(_("Reply All"), $clink->copy()->add(array('a' => 'ra'))); } $menu[] = array(_("Forward"), $clink->copy()->add(array('a' => 'f'))); $menu[] = array(_("Redirect"), $clink->copy()->add(array('a' => 'rc'))); $menu[] = array(_("Edit as New"), $clink->copy()->add(array('a' => 'en'))); } /* Generate previous/next links. */ if ($prev_msg = $imp_mailbox[$imp_mailbox->getIndex() - 1]) { $menu[] = array(_("Previous Message"), self::url(array('buid' => $imp_mailbox->getBuid($prev_msg['m'], $prev_msg['u']), 'mailbox' => $this->indices->mailbox))); } if ($next_msg = $imp_mailbox[$imp_mailbox->getIndex() + 1]) { $menu[] = array(_("Next Message"), self::url(array('buid' => $imp_mailbox->getBuid($next_msg['m'], $next_msg['u']), 'mailbox' => $this->indices->mailbox))); } $menu[] = array(sprintf(_("To %s"), $this->indices->mailbox->label), $mailbox_link); if ($mailbox->spam_show) { $menu[] = array(_("Report as Spam"), $self_link->copy()->add(array('a' => 'rs', 't' => $session->getToken()))); } if ($mailbox->innocent_show) { $menu[] = array(_("Report as Innocent"), $self_link->copy()->add(array('a' => 'ri', 't' => $session->getToken()))); } $this->view->menu = $this->getMenu('message', $menu); $hdrs = array(); foreach ($display_headers as $head => $val) { $tmp = array('label' => $basic_headers[$head]); if (Horde_String::lower($head) == 'to' && !isset($this->vars->allto) && ($pos = strpos($val, ',')) !== false) { $val = Horde_String::substr($val, 0, $pos); $tmp['all_to'] = $self_link->copy()->add('allto', 1); } $tmp['val'] = $val; $hdrs[] = $tmp; } $this->view->hdrs = $hdrs; $atc = array(); foreach ($inlineout['atc_parts'] as $key) { $summary = $imp_contents->getSummary($key, IMP_Contents::SUMMARY_BYTES | IMP_Contents::SUMMARY_SIZE | IMP_Contents::SUMMARY_DESCRIP | IMP_Contents::SUMMARY_DOWNLOAD); $tmp = array('descrip' => $summary['description_raw'], 'size' => $summary['size'], 'type' => $summary['type']); if (!empty($summary['download'])) { /* Preference: if set, only show download confirmation screen * if attachment over a certain size. */ $tmp['download'] = IMP_Minimal_Messagepart::url(array('buid' => $buid, 'mailbox' => $this->indices->mailbox))->add('atc', $key); } if ($imp_contents->canDisplay($key, IMP_Contents::RENDER_INLINE)) { $tmp['view'] = IMP_Minimal_Messagepart::url(array('buid' => $buid, 'mailbox' => $this->indices->mailbox))->add('id', $key); } $atc[] = $tmp; } $this->view->atc = $atc; $this->title = $display_headers['subject']; $this->view->title = ($status ? $status . ' ' : '') . sprintf(_("(Message %d of %d)"), $msgindex, $msgcount); $page_output->noDnsPrefetch(); $this->_pages[] = 'message'; $this->_pages[] = 'menu'; }
/** * Synchronizes the current mailbox cache with the server (using CONDSTORE * or QRESYNC). */ protected function _condstoreSync() { $mbox_ob = $this->_mailboxOb(); /* Check that modseqs are available in mailbox. */ if (!($highestmodseq = $mbox_ob->getStatus(Horde_Imap_Client::STATUS_HIGHESTMODSEQ)) || !($modseq = $this->_updateModSeq($highestmodseq))) { $mbox_ob->sync = true; } if ($mbox_ob->sync) { return; } $uids_ob = $this->getIdsOb($this->_cache->get($this->_selected, array(), array(), $mbox_ob->getStatus(Horde_Imap_Client::STATUS_UIDVALIDITY))); if (!count($uids_ob)) { $mbox_ob->sync = true; return; } /* Are we caching flags? */ if (array_key_exists(Horde_Imap_Client::FETCH_FLAGS, $this->_cacheFields())) { $fquery = new Horde_Imap_Client_Fetch_Query(); $fquery->flags(); /* Update flags in cache. Cache will be updated in _fetch(). */ $this->_fetch(new Horde_Imap_Client_Fetch_Results(), array(array('_query' => $fquery, 'changedsince' => $modseq, 'ids' => $uids_ob))); } /* Search for deleted messages, and remove from cache. */ $vanished = $this->vanished($this->_selected, $modseq, array('ids' => $uids_ob)); $disappear = array_diff($uids_ob->ids, $vanished->ids); if (!empty($disappear)) { $this->_deleteMsgs($this->_selected, $this->getIdsOb($disappear)); } $mbox_ob->sync = true; }
/** */ protected function _init() { global $conf, $injector, $notification, $page_output, $prefs, $registry, $session; $mailbox = $this->indices->mailbox; $imp_imap = $mailbox->imp_imap; /* We know we are going to be exclusively dealing with this mailbox, * so select it on the IMAP server (saves some STATUS calls). Open R/W * to clear the RECENT flag. */ $imp_imap->openMailbox($mailbox, Horde_Imap_Client::OPEN_READWRITE); /* Make sure we have a valid index. */ $imp_mailbox = $mailbox->list_ob; $imp_mailbox->setIndex($this->indices); if (!$imp_mailbox->isValidIndex()) { $this->_returnToMailbox(null, 'message_missing'); return; } $imp_flags = $injector->getInstance('IMP_Flags'); $imp_identity = $injector->getInstance('IMP_Identity'); $imp_message = $injector->getInstance('IMP_Message'); $imp_ui = $injector->getInstance('IMP_Message_Ui'); /* Run through action handlers. */ if ($this->vars->actionID) { try { $session->getToken($this->vars->token); } catch (Horde_Exception $e) { $notification->push($e); $this->vars->actionID = null; } } $readonly = $mailbox->readonly; $peek = false; switch ($this->vars->actionID) { case 'blacklist': case 'whitelist': if ($this->vars->actionID == 'blacklist') { $injector->getInstance('IMP_Filter')->blacklistMessage($this->indices); } else { $injector->getInstance('IMP_Filter')->whitelistMessage($this->indices); } break; case 'delete_message': $imp_message->delete($this->indices, array('mailboxob' => $imp_mailbox)); if ($prefs->getValue('mailbox_return')) { $this->_returnToMailbox($imp_mailbox->getIndex()); return; } if ($imp_ui->moveAfterAction($mailbox)) { $imp_mailbox->setIndex(1); } break; case 'undelete_message': $imp_message->undelete($this->indices); break; case 'move_message': case 'copy_message': if (isset($this->vars->targetMbox) && (!$readonly || $this->vars->actionID == 'copy_message')) { if ($this->vars->newMbox) { $targetMbox = IMP_Mailbox::prefFrom($this->vars->targetMbox); $newMbox = true; } else { $targetMbox = IMP_Mailbox::formFrom($this->vars->targetMbox); $newMbox = false; } $imp_message->copy($targetMbox, $this->vars->actionID == 'move_message' ? 'move' : 'copy', $this->indices, array('create' => $newMbox, 'mailboxob' => $imp_mailbox)); if ($prefs->getValue('mailbox_return')) { $this->_returnToMailbox($imp_mailbox->getIndex()); return; } } break; case 'innocent_report': case 'spam_report': $res = $injector->getInstance('IMP_Factory_Spam')->create($this->vars->actionID == 'spam_report' ? IMP_Spam::SPAM : IMP_Spam::INNOCENT)->report($this->indices, array('mailbox' => $imp_mailbox)); switch ($res) { case 1: if ($imp_ui->moveAfterAction($mailbox)) { $imp_mailbox->setIndex(1); } break; } if ($prefs->getValue('mailbox_return')) { $this->_returnToMailbox($imp_mailbox->getIndex()); return; } break; case 'flag_message': if (!$readonly && isset($this->vars->flag) && count($this->indices)) { $peek = true; $flag = $imp_flags->parseFormId($this->vars->flag); $imp_message->flag(array($flag['set'] ? 'add' : 'remove' => array($flag['flag'])), $this->indices); if ($prefs->getValue('mailbox_return')) { $this->_returnToMailbox($imp_mailbox->getIndex()); return; } } break; case 'add_address': try { $contact_link = $injector->getInstance('IMP_Contacts')->addAddress($this->vars->address, $this->vars->name); $notification->push(sprintf(_("Entry \"%s\" was successfully added to the address book"), $contact_link), 'horde.success', array('content.raw')); } catch (Horde_Exception $e) { $notification->push($e); } break; case 'strip_all': case 'strip_attachment': if (!$readonly) { try { $this->indices = new IMP_Indices_Mailbox($this->indices->mailbox, $imp_message->stripPart($this->indices, $this->vars->actionID == 'strip_all' ? null : $this->vars->imapid, array('mailboxob' => $imp_mailbox))); $notification->push(_("Attachment successfully stripped."), 'horde.success'); } catch (Horde_Exception $e) { $notification->push($e); } } break; } /* We may have done processing that has taken us past the end of the * message array, so we will return to the mailbox. */ if (!$imp_mailbox->isValidIndex()) { $this->_returnToMailbox(count($imp_mailbox)); return; } /* Now that we are done processing, get the index and array index of * the current message. */ $msg_index = $imp_mailbox[$imp_mailbox->getIndex()]; /* Parse the message. */ try { $imp_contents = $injector->getInstance('IMP_Factory_Contents')->create(new IMP_Indices($imp_mailbox)); } catch (IMP_Exception $e) { $imp_mailbox->removeMsgs(true); $this->_returnToMailbox(null, 'message_missing'); return; } /* Get envelope/flag/header information. */ try { /* Need to fetch flags before HEADERTEXT, because SEEN flag might * be set before we can grab it. */ $query = new Horde_Imap_Client_Fetch_Query(); $query->flags(); $flags_ret = $imp_imap->fetch($msg_index['m'], $query, array('ids' => $imp_imap->getIdsOb($msg_index['u']))); $query = new Horde_Imap_Client_Fetch_Query(); $query->envelope(); $fetch_ret = $imp_imap->fetch($msg_index['m'], $query, array('ids' => $imp_imap->getIdsOb($msg_index['u']))); } catch (IMP_Imap_Exception $e) { $this->_returnToMailbox(null, 'message_missing'); return; } $envelope = $fetch_ret->first()->getEnvelope(); $flags = $flags_ret->first()->getFlags(); $mime_headers = $peek ? $imp_contents->getHeader() : $imp_contents->getHeaderAndMarkAsSeen(); /* Get the title/mailbox label of the mailbox page. */ $page_label = $mailbox->label; /* Generate the link to ourselves. */ $buid = $imp_mailbox->getBuid($msg_index['m'], $msg_index['u']); $msgindex = $imp_mailbox->getIndex(); $message_url = Horde::url('basic.php')->add('page', 'message'); $token = $session->getToken(); $self_link = self::url(array('buid' => $buid, 'mailbox' => $mailbox))->add(array('token' => $token, 'start' => $msgindex)); /* Develop the list of headers to display. */ $basic_headers = $imp_ui->basicHeaders(); $display_headers = $msgAddresses = array(); $date_ob = new IMP_Message_Date($envelope->date); if ($format_date = $date_ob->format($date_ob::DATE_LOCAL)) { $display_headers['date'] = $format_date; } /* Build From address links. */ $display_headers['from'] = $imp_ui->buildAddressLinks($envelope->from, $self_link); /* Add country/flag image. */ if (!empty($envelope->from)) { $contacts_img = new IMP_Contacts_Image($envelope->from[0]); try { $res = $contacts_img->getImage($contacts_img::FLAG); $display_headers['from'] .= ' ' . Horde_Themes_Image::tag($res['url'], array('alt' => $res['desc'], 'fullsrc' => true)); } catch (IMP_Exception $e) { } } /* Look for Face information. */ if ($face = $mime_headers->getValue('face')) { $display_headers['from'] .= ' <img src="' . Horde_Url_Data::create('image/png', base64_decode($face)) . '">'; } /* Build To/Cc/Bcc links. */ foreach (array('to', 'cc', 'bcc') as $val) { $msgAddresses[] = $mime_headers->getValue($val); if ($val == 'to' || count($envelope->{$val})) { $display_headers[$val] = $imp_ui->buildAddressLinks($envelope->{$val}, $self_link); } } /* Process the subject now. */ if ($subject = $mime_headers->getValue('subject')) { $this->title = sprintf(_("%s: %s"), $page_label, $subject); $shortsub = Horde_String::truncate($subject, 100); } else { $shortsub = _("[No Subject]"); $this->title = sprintf(_("%s: %s"), $page_label, $shortsub); } /* See if the priority has been set. */ switch ($injector->getInstance('IMP_Mime_Headers')->getPriority($mime_headers)) { case 'high': $basic_headers['priority'] = _("Priority"); $display_headers['priority'] = '<div class="iconImg msgflags flagHighpriority" title="' . htmlspecialchars(_("High Priority")) . '"></div> ' . _("High"); break; case 'low': $basic_headers['priority'] = _("Priority"); $display_headers['priority'] = '<div class="iconImg msgflags flagLowpriority" title="' . htmlspecialchars(_("Low Priority")) . '"></div> ' . _("Low"); break; } /* Build Reply-To address link. */ if (!empty($envelope->reply_to) && $envelope->from[0]->bare_address != $envelope->reply_to[0]->bare_address && ($reply_to = $imp_ui->buildAddressLinks($envelope->reply_to, $self_link))) { $display_headers['reply-to'] = $reply_to; } /* Determine if all/list/user-requested headers needed. */ $all_headers = $this->vars->show_all_headers; $user_hdrs = $imp_ui->getUserHeaders(); /* Check for the presence of mailing list information. */ $list_info = $imp_ui->getListInformation($mime_headers); /* Display all headers or, optionally, the user-specified headers for * the current identity. */ $full_headers = array(); if ($all_headers) { $header_array = $mime_headers->toArray(); foreach ($header_array as $head => $val) { $lc_head = strtolower($head); /* Skip the header if we have already dealt with it. */ if (!isset($display_headers[$lc_head]) && (!in_array($lc_head, array('importance', 'x-priority')) || !isset($display_headers['priority']))) { $full_headers[$lc_head] = $val; } } } elseif (!empty($user_hdrs)) { foreach ($user_hdrs as $user_hdr) { $user_val = $mime_headers->getValue($user_hdr); if (!empty($user_val)) { $full_headers[$user_hdr] = $user_val; } } } ksort($full_headers); /* For the self URL link, we can't trust the index in the query string * as it may have changed if we deleted/copied/moved messages. We may * need other stuff in the query string, so we need to do an * add/remove of uid info. */ $selfURL = $mailbox->url(Horde::selfUrlParams()->remove(array('actionID')), $buid)->add('token', $token); $headersURL = $selfURL->copy()->remove(array('show_all_headers')); /* Generate previous/next links. */ $prev_msg = $imp_mailbox[$imp_mailbox->getIndex() - 1]; if ($prev_msg) { $prev_url = self::url(array('buid' => $imp_mailbox->getBuid($prev_msg['m'], $prev_msg['u']), 'mailbox' => $mailbox))->setRaw(true); $page_output->addLinkTag(array('href' => $prev_url, 'id' => 'prev', 'rel' => 'Previous', 'type' => null)); } else { $prev_url = null; } $next_msg = $imp_mailbox[$imp_mailbox->getIndex() + 1]; if ($next_msg) { $next_url = self::url(array('buid' => $imp_mailbox->getBuid($next_msg['m'], $next_msg['u']), 'mailbox' => $mailbox))->setRaw(true); $page_output->addLinkTag(array('href' => $next_url, 'id' => 'next', 'rel' => 'Next', 'type' => null)); } else { $next_url = null; } /* Generate the mailbox link. */ $mailbox_url = $mailbox->url('mailbox')->add('start', $msgindex); /* Everything below here is related to preparing the output. */ $js_vars = array('ImpMessage.text' => array('innocent_report' => _("Are you sure you wish to report this message as innocent?"), 'moveconfirm' => _("Are you sure you want to move the message(s)? (Some message information might get lost, like message headers, text formatting or attachments!)"), 'newmbox' => _("You are copying/moving to a new mailbox.") . "\n" . _("Please enter a name for the new mailbox:") . "\n", 'spam_report' => _("Are you sure you wish to report this message as spam?"), 'target_mbox' => _("You must select a target mailbox first."))); /* Set the status information of the message. */ $msgAddresses[] = $mime_headers->getValue('from'); $identity = $match_identity = $imp_identity->getMatchingIdentity($msgAddresses); if (is_null($identity)) { $identity = $imp_identity->getDefault(); } $flag_parse = $imp_flags->parse(array('flags' => $flags, 'personal' => $match_identity)); $status = ''; foreach ($flag_parse as $val) { if ($val instanceof IMP_Flag_User) { $status .= '<span class="' . $val->css . '" style="' . ($val->bgdefault ? '' : 'background:' . htmlspecialchars($val->bgcolor) . ';') . 'color:' . htmlspecialchars($val->fgcolor) . '">' . htmlspecialchars($val->label) . '</span>'; } else { $status .= $val->span; } } /* If this is a search mailbox, display a link to the parent mailbox * of the message in the header. */ $h_page_label = htmlspecialchars($page_label); $header_label = $h_page_label; if ($mailbox->search) { $header_label .= ' [' . $msg_index['m']->url('mailbox')->link() . $msg_index['m']->display_html . '</a>]'; } /* Prepare the navbar top template. */ $view = new Horde_View(array('templatePath' => IMP_TEMPLATES . '/basic/message')); $view->addHelper('FormTag'); $view->addHelper('Tag'); $t_view = clone $view; $t_view->buid = $buid; $t_view->message_url = $message_url; $t_view->mailbox = $mailbox->form_to; $t_view->start = $msgindex; $t_view->token = $token; /* Prepare the navbar navigate template. */ $n_view = clone $view; $n_view->readonly = $readonly; $n_view->id = 1; if ($mailbox->access_flags) { $n_view->mailbox = $mailbox->form_to; $args = array('imap' => true, 'mailbox' => $mailbox); $form_set = $form_unset = array(); foreach ($imp_flags->getList($args) as $val) { if ($val->canset) { $form_set[] = array('f' => $val->form_set, 'l' => $val->label); $form_unset[] = array('f' => $val->form_unset, 'l' => $val->label); } } $n_view->flaglist_set = $form_set; $n_view->flaglist_unset = $form_unset; } if ($imp_imap->access(IMP_Imap::ACCESS_FOLDERS)) { $n_view->move = Horde::widget(array('url' => '#', 'class' => 'moveAction', 'title' => _("Move"), 'nocheck' => true)); $n_view->copy = Horde::widget(array('url' => '#', 'class' => 'copyAction', 'title' => _("Copy"), 'nocheck' => true)); $iterator = new IMP_Ftree_IteratorFilter($injector->getInstance('IMP_Ftree')); $iterator->add($iterator::NONIMAP); $n_view->options = new IMP_Ftree_Select(array('heading' => _("This message to"), 'inc_tasklists' => true, 'inc_notepads' => true, 'iterator' => $iterator, 'new_mbox' => true)); } $n_view->back_to = Horde::widget(array('url' => $mailbox_url, 'title' => sprintf(_("Bac_k to %s"), $h_page_label), 'nocheck' => true)); if ($prev_url) { $n_view->prev = Horde::link($prev_url, _("Previous Message")); $n_view->prev_img = 'navleftImg'; } else { $n_view->prev_img = 'navleftgreyImg'; } if ($next_url) { $n_view->next = Horde::link($next_url, _("Next Message")); $n_view->next_img = 'navrightImg'; } else { $n_view->next_img = 'navrightgreyImg'; } /* Prepare the navbar actions template. */ $a_view = clone $view; $compose_params = array('buid' => $buid, 'identity' => $identity, 'mailbox' => IMP_Mailbox::formTo($mailbox)); if (!$prefs->getValue('compose_popup')) { $compose_params['start'] = $msgindex; } if ($msg_index['m']->access_deletemsgs) { if (in_array(Horde_Imap_Client::FLAG_DELETED, $flags)) { $a_view->delete = Horde::widget(array('url' => $self_link->copy()->add('actionID', 'undelete_message'), 'title' => _("Undelete"), 'nocheck' => true)); } else { $a_view->delete = Horde::widget(array('url' => $self_link->copy()->add('actionID', 'delete_message'), 'title' => _("_Delete"), 'nocheck' => true)); if (!$msg_index['m']->is_imap) { $js_vars['ImpMessage.pop3delete'] = _("Are you sure you want to PERMANENTLY delete these messages?"); } } } $disable_compose = !IMP_Compose::canCompose(); if (!$disable_compose) { $clink_ob = new IMP_Compose_Link(); $clink = $clink_ob->link()->add($compose_params); $a_view->reply = Horde::widget(array('url' => $clink->add(array('actionID' => 'reply_auto')), 'class' => 'horde-hasmenu', 'title' => _("_Reply"), 'nocheck' => true)); $a_view->reply_sender = Horde::widget(array('url' => $clink->add(array('actionID' => 'reply')), 'title' => _("To Sender"), 'nocheck' => true)); if ($list_info['reply_list']) { $a_view->reply_list = Horde::widget(array('url' => $clink->add(array('actionID' => 'reply_list')), 'title' => _("To _List"), 'nocheck' => true)); } $addr_ob = clone $envelope->to; $addr_ob->add($envelope->cc); $addr_ob->setIteratorFilter(0, $imp_identity->getAllFromAddresses()); if (count($addr_ob)) { $a_view->show_reply_all = Horde::widget(array('url' => $clink->add(array('actionID' => 'reply_all')), 'title' => _("To _All"), 'nocheck' => true)); } $fwd_locked = $prefs->isLocked('forward_default'); $a_view->forward = Horde::widget(array('url' => $clink->add(array('actionID' => 'forward_auto')), 'class' => $fwd_locked ? '' : ' horde-hasmenu', 'title' => _("Fo_rward"), 'nocheck' => true)); if (!$fwd_locked) { $a_view->forward_attach = Horde::widget(array('url' => $clink->add(array('actionID' => 'forward_attach')), 'title' => _("As Attachment"), 'nocheck' => true)); $a_view->forward_body = Horde::widget(array('url' => $clink->add(array('actionID' => 'forward_body')), 'title' => _("In Body Text"), 'nocheck' => true)); $a_view->forward_both = Horde::widget(array('url' => $clink->add(array('actionID' => 'forward_both')), 'title' => _("Attachment and Body Text"), 'nocheck' => true)); } $a_view->redirect = Horde::widget(array('url' => $clink->add(array('actionID' => 'redirect_compose')), 'title' => _("Redirec_t"), 'nocheck' => true)); $a_view->editasnew = Horde::widget(array('url' => $clink->add(array('actionID' => 'editasnew')), 'title' => _("Edit as New"), 'nocheck' => true)); } if ($mailbox->access_sortthread) { $a_view->show_thread = Horde::widget(array('url' => $mailbox->url(IMP_Basic_Thread::url(), $buid)->add(array('start' => $msgindex)), 'title' => _("_View Thread"), 'nocheck' => true)); } if (!$readonly && $registry->hasMethod('mail/blacklistFrom')) { $a_view->blacklist = Horde::widget(array('url' => $self_link->copy()->add('actionID', 'blacklist'), 'title' => _("_Blacklist"), 'nocheck' => true)); } if (!$readonly && $registry->hasMethod('mail/whitelistFrom')) { $a_view->whitelist = Horde::widget(array('url' => $self_link->copy()->add('actionID', 'whitelist'), 'title' => _("_Whitelist"), 'nocheck' => true)); } if (!empty($conf['user']['allow_view_source'])) { $a_view->view_source = $imp_contents->linkViewJS($imp_contents->getMIMEMessage(), 'view_source', _("_Message Source"), array('css' => '', 'jstext' => _("Message Source"), 'widget' => true)); } if (!$disable_compose && (in_array(Horde_Imap_Client::FLAG_DRAFT, $flags) || $msg_index['m']->drafts)) { $a_view->resume = Horde::widget(array('url' => $clink->add(array('actionID' => 'draft')), 'title' => _("Resume"), 'nocheck' => true)); } $imp_params = $mailbox->urlParams($buid); $a_view->save_as = Horde::widget(array('url' => IMP_Contents_View::downloadUrl($subject, array_merge(array('actionID' => 'save_message'), $imp_params)), 'title' => _("Sa_ve as"), 'nocheck' => true)); if ($msg_index['m']->spam_show) { $a_view->spam = Horde::widget(array('url' => '#', 'class' => 'spamAction', 'title' => _("Report as Spam"), 'nocheck' => true)); } if ($msg_index['m']->innocent_show) { $a_view->innocent = Horde::widget(array('url' => '#', 'class' => 'innocentAction', 'title' => _("Report as Innocent"), 'nocheck' => true)); } if (!$disable_compose) { $a_view->redirect = Horde::widget(array('url' => $clink->add(array('actionID' => 'redirect_compose')), 'title' => _("Redirec_t"), 'nocheck' => true)); } $a_view->headers = Horde::widget(array('url' => '#', 'class' => 'horde-hasmenu', 'title' => _("Headers"), 'nocheck' => true)); if ($all_headers) { $a_view->common_headers = Horde::widget(array('url' => $headersURL, 'title' => _("Show Common Headers"), 'nocheck' => true)); } if (!$all_headers) { $a_view->all_headers = Horde::widget(array('url' => $headersURL->copy()->add('show_all_headers', 1), 'title' => _("Show All Headers"), 'nocheck' => true)); } if ($list_info['exists']) { $a_view->list_headers = Horde::widget(array('onclick' => Horde::popupJs(IMP_Basic_Listinfo::url(array('buid' => $buid, 'mailbox' => $mailbox)), array('urlencode' => true)), 'title' => _("Show Mailing List Information"), 'nocheck' => true)); } $hdrs = array(); /* Prepare the main message template. */ if (!$all_headers) { foreach ($display_headers as $head => $val) { $hdrs[] = array('name' => $basic_headers[$head], 'val' => $val); } } foreach ($full_headers as $head => $val) { if (is_array($val)) { $hdrs[] = array('name' => $head, 'val' => '<ul style="margin:0;padding-left:15px"><li>' . implode("</li>\n<li>", array_map('htmlspecialchars', $val)) . '</li></ul>'); } else { $hdrs[] = array('name' => $head, 'val' => htmlspecialchars($val)); } } /* Determine the fields that will appear in the MIME info entries. */ $part_info = $part_info_display = array('icon', 'description', 'size'); $part_info_action = array('download', 'download_zip', 'img_save', 'strip'); $part_info_bodyonly = array('print'); $show_parts = isset($this->vars->show_parts) ? $this->vars->show_parts : $prefs->getValue('parts_display'); $part_info_display = array_merge($part_info_display, $part_info_action, $part_info_bodyonly); $contents_mask = IMP_Contents::SUMMARY_BYTES | IMP_Contents::SUMMARY_SIZE | IMP_Contents::SUMMARY_ICON | IMP_Contents::SUMMARY_DESCRIP_LINK | IMP_Contents::SUMMARY_DOWNLOAD | IMP_Contents::SUMMARY_DOWNLOAD_ZIP | IMP_Contents::SUMMARY_IMAGE_SAVE | IMP_Contents::SUMMARY_PRINT; /* Do MDN processing now. */ $mdntext = $imp_ui->MDNCheck(new IMP_Indices($msg_index['m'], $buid), $mime_headers, $this->vars->mdn_confirm) ? strval(new IMP_Mime_Status(array(_("The sender of this message is requesting a notification from you when you have read this message."), sprintf(_("Click %s to send the notification message."), Horde::link($selfURL->copy()->add('mdn_confirm', 1)) . _("HERE") . '</a>')))) : ''; /* Build body text. This needs to be done before we build the * attachment list that lives in the header. */ $inlineout = $imp_contents->getInlineOutput(array('mask' => $contents_mask, 'part_info_display' => $part_info_display, 'show_parts' => $show_parts)); /* Build the Attachments menu. */ $show_atc = false; switch ($show_parts) { case 'atc': $a_view->show_parts_all = Horde::widget(array('url' => $headersURL->copy()->add(array('show_parts' => 'all')), 'title' => _("Show All Parts"), 'nocheck' => true)); $show_atc = true; break; case 'all': if ($prefs->getValue('strip_attachments')) { $js_vars['ImpMessage.text']['stripwarn'] = _("Are you sure you wish to PERMANENTLY delete this attachment?"); } break; } if (count($inlineout['atc_parts']) > 2) { $a_view->download_all = Horde::widget(array('url' => $imp_contents->urlView($imp_contents->getMIMEMessage(), 'download_all'), 'title' => _("Download All Attachments (in .zip file)"), 'nocheck' => true)); if ($prefs->getValue('strip_attachments')) { $a_view->strip_all = Horde::widget(array('url' => Horde::selfUrlParams()->add(array('actionID' => 'strip_all', 'token' => $token)), 'class' => 'stripAllAtc', 'title' => _("Strip All Attachments"), 'nocheck' => true)); $js_vars['ImpMessage.text']['stripallwarn'] = _("Are you sure you want to PERMANENTLY delete all attachments?"); } $show_atc = true; } if ($show_atc) { $a_view->atc = Horde::widget(array('url' => '#', 'class' => 'horde-hasmenu', 'title' => _("Attachments"), 'nocheck' => true)); } /* Show attachment information in headers? 'atc_parts' will be empty if * 'parts_display' pref is 'none'. */ if (!empty($inlineout['atc_parts'])) { if ($show_parts == 'all') { $val = $imp_contents->getTree()->getTree(true); } else { $tmp = array(); foreach ($inlineout['atc_parts'] as $id) { $summary = $imp_contents->getSummary($id, $contents_mask); $tmp[] = '<tr>'; foreach ($part_info as $val) { $tmp[] = '<td>' . $summary[$val] . '</td>'; } $tmp[] = '<td>'; foreach ($part_info_action as $val) { $tmp[] = $summary[$val]; } $tmp[] = '</td></tr>'; } $val = '<table>' . implode('', $tmp) . '</table>'; } $hdrs[] = array('class' => 'msgheaderParts', 'name' => $show_parts == 'all' ? _("Parts") : _("Attachments"), 'val' => $val); } $m_view = clone $view; $m_view->label = $shortsub; $m_view->headers = $hdrs; $m_view->msgtext = $mdntext . $inlineout['msgtext']; $subinfo = new IMP_View_Subinfo(array('mailbox' => $mailbox)); $subinfo->label = $header_label; $subinfo->value = sprintf(_("(%d of %d)"), $msgindex, count($imp_mailbox)) . $status; $injector->getInstance('Horde_View_Topbar')->subinfo = $subinfo->render(); /* Output message page now. */ $page_output->addInlineJsVars($js_vars, array('top' => true)); $page_output->addScriptFile('scriptaculous/effects.js', 'horde'); $page_output->addScriptFile('hordecore.js', 'horde'); $page_output->addScriptFile('message.js'); $page_output->addScriptFile('stripe.js', 'horde'); $page_output->addScriptPackage('IMP_Script_Package_Imp'); if (!empty($conf['tasklist']['use_notepad']) || !empty($conf['tasklist']['use_tasklist'])) { $page_output->addScriptPackage('Horde_Core_Script_Package_Dialog'); } $page_output->noDnsPrefetch(); Horde::startBuffer(); foreach ($injector->getInstance('IMP_Maillog')->getLog(new IMP_Maillog_Message($this->indices, array('mdn'))) as $val) { $notification->push($val->message, 'imp.' . $val->action); } $this->output = Horde::endBuffer(); $this->output .= $t_view->render('navbar_top') . $n_view->render('navbar_navigate') . $a_view->render('navbar_actions') . $m_view->render('message') . $a_view->render('navbar_actions'); $n_view->id = 2; $n_view->isbottom = true; $this->output .= $n_view->render('navbar_navigate'); }
private function loadMessageBodies() { $headers = array(); $fetch_query = new \Horde_Imap_Client_Fetch_Query(); $fetch_query->envelope(); $fetch_query->structure(); $fetch_query->flags(); $fetch_query->seq(); $fetch_query->size(); $fetch_query->uid(); $fetch_query->imapDate(); $headers = array_merge($headers, array('importance', 'list-post', 'x-priority')); $headers[] = 'content-type'; $fetch_query->headers('imp', $headers, array('cache' => true, 'peek' => true)); // $list is an array of Horde_Imap_Client_Data_Fetch objects. $ids = new \Horde_Imap_Client_Ids($this->message_id); $headers = $this->conn->fetch($this->folder_id, $fetch_query, array('ids' => $ids)); $fetch = $headers[$this->message_id]; // set $this->fetch to get to, from ... $this->fetch = $fetch; // analyse the body part $structure = $fetch->getStructure(); // debugging below $structure_type = $structure->getPrimaryType(); if ($structure_type == 'multipart') { $i = 1; foreach ($structure->getParts() as $p) { $this->getpart($p, $i++); } } else { if ($structure->findBody() != null) { // get the body from the server $partId = $structure->findBody(); $this->queryBodyPart($partId); } } }
/** * Synchronizes the current mailbox cache with the server. */ protected function _syncMailbox() { $status = $this->status($this->_selected, Horde_Imap_Client::STATUS_UIDVALIDITY | Horde_Imap_Client::STATUS_HIGHESTMODSEQ); /* Check that modseqs are available in mailbox. */ if (empty($status['highestmodseq'])) { return; } /* Grab all flags updated since the cached modseq. */ $md = $this->_cache->getMetaData($this->_selected, $status['uidvalidity'], array(self::CACHE_MODSEQ)); if (!isset($md[self::CACHE_MODSEQ]) || $md[self::CACHE_MODSEQ] == $status['highestmodseq']) { return; } $uids = $this->_cache->get($this->_selected, array(), array(), $status['uidvalidity']); if (!empty($uids)) { $uids_ob = $this->getIdsOb($uids); /* Are we caching flags? */ if (array_key_exists(Horde_Imap_Client::FETCH_FLAGS, $this->_cacheFields())) { $fquery = new Horde_Imap_Client_Fetch_Query(); $fquery->flags(); /* Update flags in cache. Cache will be updated in _fetch(). */ $this->_fetch(new Horde_Imap_Client_Fetch_Results(), $fquery, array('changedsince' => $md[self::CACHE_MODSEQ], 'ids' => $uids_ob)); } /* Search for deleted messages, and remove from cache. */ $squery = new Horde_Imap_Client_Search_Query(); $squery->ids($this->getIdsOb($uids_ob->range_string)); $search = $this->search($this->_selected, $squery, array('nocache' => true)); $deleted = array_diff($uids_ob->ids, $search['match']->ids); if (!empty($deleted)) { $this->_deleteMsgs($this->_selected, $deleted); } } $this->_updateMetaData($this->_selected, array(self::CACHE_MODSEQ => $status['highestmodseq']), $status['uidvalidity']); }
/** * Strips one or all MIME parts out of a message. * * @param string $partid The MIME ID of the part to strip. All parts are * stripped if null. * * @return IMP_Indices Returns the new indices object. * @throws IMP_Exception */ public function stripPart($partid = null) { global $injector; list($mbox, $uid) = $this->getSingle(); if (!$uid) { return; } if ($mbox->readonly) { throw new IMP_Exception(_("Cannot strip the part as the mailbox is read-only.")); } $uidvalidity = $mbox->uidvalid; $contents = $injector->getInstance('IMP_Factory_Contents')->create($this); $message = $contents->getMIMEMessage(); $boundary = trim($message->getContentTypeParameter('boundary'), '"'); $url = new Horde_Imap_Client_Url(); $url->mailbox = $mbox; $url->uid = $uid; $url->uidvalidity = $uidvalidity; $imp_imap = $mbox->imp_imap; /* Always add the header to output. */ $url->section = 'HEADER'; $parts = array(array('t' => 'url', 'v' => strval($url))); for ($id = 1;; ++$id) { if (!($part = $message[$id])) { break; } $parts[] = array('t' => 'text', 'v' => "\r\n--" . $boundary . "\r\n"); if ($id != 1 && is_null($partid) || $id == $partid) { $newPart = new Horde_Mime_Part(); $newPart->setType('text/plain'); /* Need to make sure all text is in the correct charset. */ $newPart->setCharset('UTF-8'); $newPart->setContents(sprintf(_("[Part stripped: Original part type: %s, name: %s]"), $part->getType(), $contents->getPartName($part))); $newPart->setDisposition('attachment'); $parts[] = array('t' => 'text', 'v' => $newPart->toString(array('canonical' => true, 'headers' => true, 'stream' => true))); } else { $url->section = $id . '.MIME'; $parts[] = array('t' => 'url', 'v' => strval($url)); $url->section = $id; $parts[] = array('t' => 'url', 'v' => strval($url)); } } $parts[] = array('t' => 'text', 'v' => "\r\n--" . $boundary . "--\r\n"); /* Get the headers for the message. */ $query = new Horde_Imap_Client_Fetch_Query(); $query->imapDate(); $query->flags(); try { $res = $imp_imap->fetch($mbox, $query, array('ids' => $imp_imap->getIdsOb($uid)))->first(); if (is_null($res)) { throw new IMP_Imap_Exception(); } $flags = $res->getFlags(); /* If in Virtual Inbox, we need to reset flag to unseen so that it * appears again in the mailbox list. */ if ($mbox->vinbox) { $flags = array_values(array_diff($flags, array(Horde_Imap_Client::FLAG_SEEN))); } $new_uid = $imp_imap->append($mbox, array(array('data' => $parts, 'flags' => $flags, 'internaldate' => $res->getImapDate())))->ids; $new_uid = reset($new_uid); } catch (IMP_Imap_Exception $e) { throw new IMP_Exception(_("An error occured while attempting to strip the part.")); } $this->delete(array('keeplog' => true, 'nuke' => true)); $indices_ob = $mbox->getIndicesOb($new_uid); /* We need to replace the old UID(s) in the URL params. */ $vars = $injector->getInstance('Horde_Variables'); if (isset($vars->buid)) { list(, $vars->buid) = $mbox->toBuids($indices_ob)->getSingle(); } if (isset($vars->uid)) { $vars->uid = $new_uid; } return $indices_ob; }
/** * Build the array of message information. * * @param array $msgnum An array of index numbers. * @param array $options Additional options: * - headers: (boolean) Return info on the non-envelope headers * 'Importance', 'List-Post', and 'X-Priority'. * DEFAULT: false (only envelope headers returned) * - preview: (mixed) Include preview information? If empty, add no * preview information. If 1, uses value from prefs. * If 2, forces addition of preview info. * DEFAULT: No preview information. * - type: (boolean) Return info on the MIME Content-Type of the base * message part ('Content-Type' header). * DEFAULT: false * * @return array An array with the following keys: * - overview: (array) The overview information. Contains the following: * - envelope: (Horde_Imap_Client_Data_Envelope) Envelope information * returned from the IMAP server. * - flags: (array) The list of IMAP flags returned from the server. * - headers: (array) Horde_Mime_Headers objects containing header data * if either $options['headers'] or $options['type'] are * true. * - idx: (integer) Array index of this message. * - mailbox: (string) The mailbox containing the message. * - preview: (string) If requested in $options['preview'], the preview * text. * - previewcut: (boolean) Has the preview text been cut? * - size: (integer) The size of the message in bytes. * - uid: (string) The unique ID of the message. * - uids: (IMP_Indices) An indices object. */ public function getMailboxArray($msgnum, $options = array()) { $this->_buildMailbox(); $headers = $overview = $to_process = $uids = array(); /* Build the list of mailboxes and messages. */ foreach ($msgnum as $i) { /* Make sure that the index is actually in the slice of messages we're looking at. If we're hiding deleted messages, for example, there may be gaps here. */ if (isset($this->_sorted[$i - 1])) { $to_process[strval($this->_getMbox($i - 1))][$i] = $this->_sorted[$i - 1]; } } $fetch_query = new Horde_Imap_Client_Fetch_Query(); $fetch_query->envelope(); $fetch_query->flags(); $fetch_query->size(); $fetch_query->uid(); if (!empty($options['headers'])) { $headers = array_merge($headers, array('importance', 'list-post', 'x-priority')); } if (!empty($options['type'])) { $headers[] = 'content-type'; } if (!empty($headers)) { $fetch_query->headers('imp', $headers, array('cache' => true, 'peek' => true)); } if (empty($options['preview'])) { $cache = null; $options['preview'] = 0; } else { $cache = $this->_mailbox->imp_imap->getCache(); } /* Retrieve information from each mailbox. */ foreach ($to_process as $mbox => $ids) { try { $imp_imap = IMP_Mailbox::get($mbox)->imp_imap; $fetch_res = $imp_imap->fetch($mbox, $fetch_query, array('ids' => $imp_imap->getIdsOb($ids))); if ($options['preview']) { $preview_info = $tostore = array(); if ($cache) { try { $preview_info = $cache->get($mbox, $ids, array('IMPpreview', 'IMPpreviewc')); } catch (IMP_Imap_Exception $e) { } } } $mbox_ids = array(); foreach ($ids as $k => $v) { if (!isset($fetch_res[$v])) { continue; } $f = $fetch_res[$v]; $uid = $f->getUid(); $v = array('envelope' => $f->getEnvelope(), 'flags' => $f->getFlags(), 'headers' => $f->getHeaders('imp', Horde_Imap_Client_Data_Fetch::HEADER_PARSE), 'idx' => $k, 'mailbox' => $mbox, 'size' => $f->getSize(), 'uid' => $uid); if ($options['preview'] === 2 || $options['preview'] === 1 && (!$GLOBALS['prefs']->getValue('preview_show_unread') || !in_array(Horde_Imap_Client::FLAG_SEEN, $v['flags']))) { if (empty($preview_info[$uid])) { try { $imp_contents = $GLOBALS['injector']->getInstance('IMP_Factory_Contents')->create(new IMP_Indices($mbox, $uid)); $prev = $imp_contents->generatePreview(); $preview_info[$uid] = array('IMPpreview' => $prev['text'], 'IMPpreviewc' => $prev['cut']); if (!is_null($cache)) { $tostore[$uid] = $preview_info[$uid]; } } catch (Exception $e) { $preview_info[$uid] = array('IMPpreview' => '', 'IMPpreviewc' => false); } } $v['preview'] = $preview_info[$uid]['IMPpreview']; $v['previewcut'] = $preview_info[$uid]['IMPpreviewc']; } $overview[] = $v; $mbox_ids[] = $uid; } $uids[$mbox] = $mbox_ids; if (!is_null($cache) && !empty($tostore)) { $status = $imp_imap->status($mbox, Horde_Imap_Client::STATUS_UIDVALIDITY); $cache->set($mbox, $tostore, $status['uidvalidity']); } } catch (IMP_Imap_Exception $e) { } } return array('overview' => $overview, 'uids' => new IMP_Indices($uids)); }
/** * Return a folder object containing all IMAP server change information. * * @param array $options An array of options. * @see Horde_ActiveSync_Imap_Adapter::getMessageChanges * * @return Horde_ActiveSync_Folder_Base The populated folder object. */ public function getChanges(array $options) { $this->_logger->info(sprintf('[%s] CONDSTORE and CHANGES', $this->_procid)); $flags = array(); $current_modseq = $this->_status[Horde_ActiveSync_Folder_Imap::HIGHESTMODSEQ]; $query = new Horde_Imap_Client_Search_Query(); // Increment since $imap->search uses >= operator. if ($this->_modseq_valid) { $query->modseq($this->_folder->modseq() + 1); } if (!empty($options['sincedate'])) { $query->dateSearch(new Horde_Date($options['sincedate']), Horde_Imap_Client_Search_Query::DATE_SINCE); } $search_ret = $this->_imap_ob->search($this->_mbox, $query, array('results' => array(Horde_Imap_Client::SEARCH_RESULTS_MATCH))); $search_uids = $search_ret['count'] ? $search_ret['match']->ids : array(); // Catch changes to FILTERTYPE. if (!empty($options['refreshfilter'])) { $this->_logger->info(sprintf('[%s] Checking for additional messages within the new FilterType parameters.', $this->_procid)); $search_ret = $this->_searchQuery($options, false); if ($search_ret['count']) { $this->_logger->info(sprintf('[%s] Found %d messages that are now outside FilterType.', $this->_procid, $search_ret['count'])); $search_uids = array_merge($search_uids, $search_ret['match']->ids); } } // Protect against very large change sets. $cnt = count($search_uids) / Horde_ActiveSync_Imap_Adapter::MAX_FETCH + 1; $query = new Horde_Imap_Client_Fetch_Query(); if ($this->_modseq_valid) { $query->modseq(); } $query->flags(); $changes = array(); $categories = array(); for ($i = 0; $i <= $cnt; $i++) { $ids = new Horde_Imap_Client_Ids(array_slice($search_uids, $i * Horde_ActiveSync_Imap_Adapter::MAX_FETCH, Horde_ActiveSync_Imap_Adapter::MAX_FETCH)); try { $fetch_ret = $this->_imap_ob->fetch($this->_mbox, $query, array('ids' => $ids)); } catch (Horde_Imap_Client_Exception $e) { $this->_logger->err($e->getMessage()); throw new Horde_ActiveSync_Exception($e); } $this->_buildModSeqChanges($changes, $flags, $categories, $fetch_ret, $options, $current_modseq); } // Set the changes in the folder object. $this->_folder->setChanges($changes, $flags, $categories, !empty($options['softdelete']) || !empty($options['refreshfilter'])); // Check for deleted messages. try { $deleted = $this->_imap_ob->vanished($this->_mbox, $this->_folder->modseq(), array('ids' => new Horde_Imap_Client_Ids($this->_folder->messages()))); } catch (Horde_Imap_Client_Excetion $e) { $this->_logger->err($e->getMessage()); throw new Horde_ActiveSync_Exception($e); } $this->_folder->setRemoved($deleted->ids); $this->_logger->info(sprintf('[%s] Found %d deleted messages.', $this->_procid, $deleted->count())); // Check for SOFTDELETE messages. if (!empty($options['sincedate']) && (!empty($options['softdelete']) || !empty($options['refreshfilter']))) { $this->_logger->info(sprintf('[%s] Polling for SOFTDELETE in %s before %d', $this->_procid, $this->_folder->serverid(), $options['sincedate'])); $search_ret = $this->_searchQuery($options, true); if ($search_ret['count']) { $this->_logger->info(sprintf('[%s] Found %d messages to SOFTDELETE.', $this->_procid, count($search_ret['match']->ids))); $this->_folder->setSoftDeleted($search_ret['match']->ids); } $this->_folder->setSoftDeleteTimes($options['sincedate'], time()); } return $this->_folder; }
/** * Build the array of message information. * * @param array $msgnum An array of index numbers. * * @return array An array with the following keys: * <pre> * - overview: (array) The overview information. Contains the following: * - envelope: (Horde_Imap_Client_Data_Envelope) Envelope information * returned from the IMAP server. * - flags: (array) The list of IMAP flags returned from the server. * - headers: (array) Horde_Mime_Headers objects containing header * data for non-envelope headers. * - idx: (integer) Array index of this message. * - mailbox: (string) The mailbox containing the message. * - size: (integer) The size of the message in bytes. * - uid: (string) The unique ID of the message. * - uids: (IMP_Indices) An indices object. * </pre> */ public function getMailboxArray($msgnum) { $this->_buildMailbox(); $overview = $to_process = $uids = array(); /* Build the list of mailboxes and messages. */ foreach ($msgnum as $i) { /* Make sure that the index is actually in the slice of messages we're looking at. If we're hiding deleted messages, for example, there may be gaps here. */ if (isset($this->_sorted[$i - 1])) { $to_process[strval($this->_getMbox($i - 1))][$i] = $this->_sorted[$i - 1]; } } $fetch_query = new Horde_Imap_Client_Fetch_Query(); $fetch_query->envelope(); $fetch_query->flags(); $fetch_query->size(); $fetch_query->uid(); $fetch_query->headers('imp', array_merge(self::$headersUsed, IMP_Contents_Message::$headersUsed), array('cache' => true, 'peek' => true)); /* Retrieve information from each mailbox. */ foreach ($to_process as $mbox => $ids) { try { $imp_imap = IMP_Mailbox::get($mbox)->imp_imap; if ($imp_imap->config->atc_structure) { $query = clone $fetch_query; $query->structure(); } else { $query = $fetch_query; } $fetch_res = $imp_imap->fetch($mbox, $query, array('ids' => $imp_imap->getIdsOb($ids))); $mbox_ids = array(); foreach ($ids as $k => $v) { if (!isset($fetch_res[$v])) { continue; } $f = $fetch_res[$v]; $uid = $f->getUid(); $v = array('envelope' => $f->getEnvelope(), 'flags' => $f->getFlags(), 'headers' => $f->getHeaders('imp', Horde_Imap_Client_Data_Fetch::HEADER_PARSE), 'idx' => $k, 'mailbox' => $mbox, 'size' => $f->getSize(), 'structure' => $f->getStructure(), 'uid' => $uid); $overview[] = $v; $mbox_ids[] = $uid; } $uids[$mbox] = $mbox_ids; } catch (IMP_Imap_Exception $e) { } } return array('overview' => $overview, 'uids' => new IMP_Indices($uids)); }
function Execute($aparams) { require_once JPATH_SITE . DS . "Horde" . DS . "Autoloader.php"; require_once JPATH_SITE . DS . "Horde" . DS . "Autoloader" . DS . "ClassPathMapper.php"; require_once JPATH_SITE . DS . "Horde" . DS . "Autoloader" . DS . "ClassPathMapper" . DS . "Default.php"; require_once JPATH_SITE . DS . "Horde" . DS . "Autoloader" . DS . "Default.php"; $this->Log("Checking email account - {$aparams['name']}"); /*if (JRequest::getVar('email') != 1) return;*/ if (!$aparams['server']) { return $this->Log("No server specified"); } if (!$aparams['port']) { return $this->Log("No port specified"); } if (!$aparams['username']) { return $this->Log("No username specified"); } if (!$aparams['password']) { return $this->Log("No password specified"); } $this->params = $aparams; $this->connect(); if (!$this->conn) { return $this->Log("Unable to connect to server"); } // check if we have any messages at all $messages = $this->conn->search("INBOX"); $ids = $messages['match']; $ids->reverse(); $msgcount = $ids->count(); if ($msgcount == 0) { $this->Log("No messages"); $this->disconnect(); return; } else { $this->Log("{$msgcount} messaeges"); } // only get the first 20 messages to make sure web page response is quicker $maxmsgcount = 50; if ($msgcount < $maxmsgcount) { $maxmsgcount = $msgcount; } $query = new Horde_Imap_Client_Fetch_Query(); $query->flags(); $query->structure(); $query->headerText(array('peek' => 1)); $uid = new Horde_Imap_Client_Ids(); for ($i = 0; $i < $maxmsgcount; $i++) { $uid->add($ids->ids[$i]); } $messages = $this->conn->fetch('INBOX', $query, array('ids' => $uid)); // for the most recent xx messages for ($i = 0; $i < $maxmsgcount; $i++) { $mapped = $ids->ids[$i]; $message = $messages->get($mapped); $this->Log("---------------------"); $this->Log("Processing message {$i} / {$mapped}"); // get headres of message if (!$this->GetHeaders($message)) { $this->Log("Error getting headers"); continue; } $subject = $this->headers->getValue("subject"); $this->Log("Subject : " . $subject); $this->from = $this->parse_addys($this->headers->getValue("from")); $this->to = $this->parse_addys($this->headers->getValue("to")); $this->Log("From : {$this->from[0]->mailbox}@{$this->from[0]->host} ({$this->from[0]->personal})"); if ($this->from[0]->mailbox == "no-reply") { // no-reply from form builder, attempt to find address in name $text = $this->from[0]->personal; //$text = str_replace("\"","",$text); $matches = array(); $pattern = "/(?:[a-z0-9!#\$%&'*+=?^_`{|}~-]+(?:\\.[a-z0-9!#\$%&'*+=?^_`{|}~-]+)*|\"(?:[-\v\f-!#-[]-]|\\[-\t\v\f-])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[-\v\f-!-ZS-]|\\[-\t\v\f-])+)\\])/"; preg_match_all($pattern, $text, $matches); //print_p($matches); if (count($matches[0]) > 0) { // new email found $newemail = $matches[0][0]; list($name, $host) = explode("@", $newemail); $this->Log("No Reply message, New From address : {$name}@{$host}"); $this->from[0]->mailbox = $name; $this->from[0]->host = $host; $this->from[0]->personal = trim(str_replace("{$name}@{$host}", "", $this->from[0]->personal)); } } // skip if already read if ($aparams['type'] == "imap" && $this->IsMessageRead($message)) { $this->Log("Skipping read message"); continue; } // validate to address is required if (!$this->ValidateToAddress()) { $this->Log("Skipping invalid to address"); continue; } if (!$this->ValidateFromAddress()) { $this->Log("Skipping due to from address"); continue; } //check subject and to email to see if we have found a user and or ticket $subject = $this->headers->getValue("subject"); list($ticketid, $userid, $subject) = $this->ParseSubject($subject, $this->from[0]->mailbox . '@' . $this->from[0]->host); $this->subject = $subject; //echo "Ticket : $ticketid, $userid, $subject<br>"; // ok, need to get the message as we have decided its ok to use this ticket if ($ticketid < 1 && $userid < 1 && $this->params['newticketsfrom'] == "registered") { $this->Log("Skipping as registered only and not a registered email"); continue; } if ($this->params['allowrepliesonly'] && $ticketid < 1) { $this->Log("Skipping as not a reply"); continue; } // validate that the ticket is being replied to by user or handler if ($ticketid > 0) { $ticket = $this->getTicket($ticketid); if ($this->params['allowunknown'] < 1) { if ($ticket['user_id'] == 0 && $ticket['email'] != "{$this->from[0]->mailbox}@{$this->from[0]->host}") { $this->Log("Unknown email replying to the message, ignore the email ({$this->from[0]->mailbox}@{$this->from[0]->host})"); continue; } if ($userid != $ticket['handler_id'] && $userid != $ticket['user_id']) { $this->Log("Unknown user replying to the message, ignore the email ({$this->from[0]->mailbox}@{$this->from[0]->host})"); continue; } } } $this->GetMessage($message); $this->TrimMessage(); $messageid = 0; $filesok = true; // add to existing ticket if ($ticketid > 0) { // unreg ticket, just check email if ($ticket['user_id'] == 0) { //echo "Adding message to ticket - {$ticket['email']}<br>"; $this->DoTicketReply($ticketid, $userid, 0, $messageid); } else { if ($userid == $ticket['handler_id']) { //echo "Adding admin message to ticket - {$ticket['user_id']} -> {$userid}<br>"; $this->DoTicketReply($ticketid, $userid, 1, $messageid); } else { if ($userid == $ticket['user_id']) { //echo "Adding message to ticket - {$ticket['user_id']} -> {$userid}<br>"; $this->DoTicketReply($ticketid, $userid, 0, $messageid); if (!FSS_Settings::get('support_user_attach')) { $filesok = false; } } else { if ($this->params['allowunknown']) { // unreg ticket, add users reply $this->DoTicketReply($ticketid, 0, 0, $messageid); } } } } } else { if ($userid > 0) { //echo "Opening new ticket<br>"; $ticketid = $this->OpenNewTicket($userid, $messageid); } else { // open ticket for unregistered user //echo "Opening new ticket for unreg user<br>"; $ticketid = $this->OpenNewTicketUnreg($messageid); } } $ticket = $this->getTicket($ticketid); if ($userid > 0) { $user = JFactory::getUser($userid); $this->Log("Ticket ID : {$ticketid} - {$ticket['reference']}, UserID : {$userid} - {$user->name} ({$user->username})"); } else { $this->Log("Ticket ID : {$ticketid} - {$ticket['reference']}, Unregistered User"); } /* if ($filesok) $this->AttachFiles($ticketid, $userid, $messageid);*/ } //imap_expunge($this->conn); $this->disconnect(); //echo "</div>"; }
private function loadMessageBodies() { $headers = []; $fetch_query = new \Horde_Imap_Client_Fetch_Query(); $fetch_query->envelope(); $fetch_query->structure(); $fetch_query->flags(); $fetch_query->size(); $fetch_query->imapDate(); $headers = array_merge($headers, ['importance', 'list-post', 'x-priority']); $headers[] = 'content-type'; $fetch_query->headers('imp', $headers, ['cache' => true, 'peek' => true]); // $list is an array of Horde_Imap_Client_Data_Fetch objects. $ids = new \Horde_Imap_Client_Ids($this->messageId); $headers = $this->conn->fetch($this->mailBox, $fetch_query, ['ids' => $ids]); /** @var $fetch \Horde_Imap_Client_Data_Fetch */ $fetch = $headers[$this->messageId]; if (is_null($fetch)) { throw new DoesNotExistException("This email ({$this->messageId}) can't be found. Probably it was deleted from the server recently. Please reload."); } // set $this->fetch to get to, from ... $this->fetch = $fetch; // analyse the body part $structure = $fetch->getStructure(); // debugging below $structure_type = $structure->getPrimaryType(); if ($structure_type == 'multipart') { $i = 1; foreach ($structure->getParts() as $p) { $this->getPart($p, $i++); } } else { if ($structure->findBody() != null) { // get the body from the server $partId = $structure->findBody(); $this->getPart($structure->getPart($partId), $partId); } } }
/** * @depends testOptimizedSearches */ public function testComplexFetch() { // Fetching message information from complex MIME message. $complex_fetch = new Horde_Imap_Client_Fetch_Query(); $complex_fetch->fullText(array('length' => 100, 'peek' => true)); // Header of entire message $complex_fetch->headerText(array('length' => 100, 'peek' => true)); // Header of message/rfc822 part $complex_fetch->headerText(array('id' => 2, 'length' => 100, 'peek' => true)); // Body text of entire message $complex_fetch->bodyText(array('length' => 100, 'peek' => true)); // Body text of message/rfc822 part $complex_fetch->bodyText(array('id' => 2, 'length' => 100, 'peek' => true)); // MIME Header of multipart/alternative part $complex_fetch->mimeHeader('1', array('length' => 100, 'peek' => true)); // MIME Header of text/plain part embedded in message/rfc822 part $complex_fetch->mimeHeader('2.1', array('length' => 100, 'peek' => true)); // Body text of multipart/alternative part $complex_fetch->bodyPart('1', array('length' => 100, 'peek' => true)); // Body text of image/png part embedded in message/rfc822 part // Try to do server-side decoding, if available $complex_fetch->mimeHeader('2.2', array('decode' => true, 'length' => 100, 'peek' => true)); // If supported, return decoded body part size $complex_fetch->bodyPartSize('2.2'); // Select message-id header from base message header $complex_fetch->headers('headersearch1', array('message-id'), array('length' => 100, 'peek' => true)); // Select everything but message-id header from message/rfc822 header $complex_fetch->headers('headersearch2', array('message-id'), array('id' => '2', 'length' => 100, 'notsearch' => true, 'peek' => true)); $complex_fetch->structure(); $complex_fetch->flags(); $complex_fetch->imapDate(); $complex_fetch->size(); $complex_fetch->uid(); if (self::$live->capability->query('CONDSTORE')) { $complex_fetch->modseq(); } try { $res = self::$live->fetch(self::$test_mbox, $complex_fetch, array('ids' => new Horde_Imap_Client_Ids(3, true))); } catch (Horde_Imap_Client_Exception $e) { if ($e->getCode() === $e::MBOXNOMODSEQ) { $this->markTestSkipped('Mailbox does not support MODSEQ.'); } throw $e; } $this->assertInstanceOf('Horde_Imap_Client_Fetch_Results', $res); $this->assertEquals(1, count($res)); $this->assertEquals('Message-ID: <*****@*****.**>', trim($res[3]->getHeaders('headersearch1'))); /* Return stream instead. */ $this->assertInternalType('resource', $res[3]->getHeaders('headersearch1', Horde_Imap_Client_Data_Fetch::HEADER_STREAM)); /* Parse headers instead. */ $this->assertInstanceOf('Horde_Mime_Headers', $res[3]->getHeaders('headersearch1', Horde_Imap_Client_Data_Fetch::HEADER_PARSE)); }
/** * * @param Horde_Imap_Client_Mailbox $mbox The mailbox * @param array $uids An array of message uids * @param array $options An options array * - headers: (boolean) Fetch header text if true. * DEFAULT: false (Do not fetch header text). * - structure: (boolean) Fetch message structure. * DEFAULT: true (Fetch message structure). * - flags: (boolean) Fetch messagge flags. * DEFAULT: true (Fetch message flags). * - envelope: (boolen) Fetch the envelope data. * DEFAULT: false (Do not fetch envelope). @since 2.4.0 * * @return Horde_Imap_Fetch_Results The results. * @throws Horde_ActiveSync_Exception */ protected function _getMailMessages(Horde_Imap_Client_Mailbox $mbox, array $uids, array $options = array()) { $options = array_merge(array('headers' => false, 'structure' => true, 'flags' => true, 'envelope' => false), $options); $query = new Horde_Imap_Client_Fetch_Query(); if ($options['structure']) { $query->structure(); } if ($options['flags']) { $query->flags(); } if ($options['envelope']) { $query->envelope(); } if (!empty($options['headers'])) { $query->headerText(array('peek' => true)); } try { return $this->_getImapOb()->fetch($mbox, $query, array('ids' => new Horde_Imap_Client_Ids($uids), 'exists' => true)); } catch (Horde_Imap_Client_Exception $e) { $this->_logger->err(sprintf('[%s] Unable to fetch message: %s', $this->_procid, $e->getMessage())); throw new Horde_ActiveSync_Exception($e); } }
/** * @static * @param $user_id * @param $account_id * @param $folder_id * @param int $from * @param int $count * @return array */ public static function getMessages($user_id, $account_id, $folder_id, $from = 0, $count = 20) { // get the account $account = App::getAccount($user_id, $account_id); if (!$account) { #TODO: i18n return array('error' => 'unknown account'); } try { // connect to the imap server $conn = App::getImapConnection($account); $messages = array(); // $mb = new \Horde_Imap_Client_Mailbox($folder_id); $status = $conn->status($folder_id, \Horde_Imap_Client::STATUS_MESSAGES); $total = $status['messages']; if ($from + $count > $total) { $count = $total - $from; } $headers = array(); $fetch_query = new \Horde_Imap_Client_Fetch_Query(); $fetch_query->envelope(); $fetch_query->flags(); $fetch_query->seq(); $fetch_query->size(); $fetch_query->uid(); $fetch_query->imapDate(); $headers = array_merge($headers, array('importance', 'list-post', 'x-priority')); $headers[] = 'content-type'; $fetch_query->headers('imp', $headers, array('cache' => true, 'peek' => true)); $opt = array('ids' => $from + 1 . ':' . ($from + 1 + $count)); // $list is an array of Horde_Imap_Client_Data_Fetch objects. $headers = $conn->fetch($folder_id, $fetch_query); foreach ($headers as $header) { $flags = array('SEEN' => True, 'ANSWERED' => False, 'FORWARDED' => False, 'DRAFT' => False, 'HAS_ATTACHMENTS' => True); // \Horde_Imap_Client_Data_Fetch::HEADER_PARSE $f = $header->getFlags(); $date = $header->getImapDate()->format('U'); $id = $header->getUid(); $e = $header->getEnvelope(); $flags = array(); $to = $e->to_decoded[0]; $to = $to['personal']; //."<".$to['mailbox']."@".$to['host'].">"; $from = $e->from_decoded[0]; $from = $from['personal']; //."<".$from['mailbox']."@".$from['host'].">"; $messages[] = array('id' => $id, 'from' => $from, 'to' => $to, 'subject' => $e->subject_decoded, 'date' => $date, 'size' => $header->getSize(), 'flags' => $flags); } return array('account_id' => $account_id, 'folder_id' => $folder_id, 'messages' => $messages); } catch (\Horde_Imap_Client_Exception $e) { return array('error' => $e->getMessage()); } }