Author: Michael Slusarz (slusarz@horde.org)
Inheritance: implements ArrayAccess, implements Countable, implements Iterator
Ejemplo n.º 1
0
 /**
  * Constructor.
  *
  * @param IMP_Indices $indices  The index of the message.
  * @param boolean $peek         Don't set seen flag?
  */
 public function __construct(IMP_Indices $indices, $peek = false)
 {
     global $injector;
     /* Get envelope/header information. We don't use flags in this
      * view. */
     try {
         list($mbox, $uid) = $indices->getSingle();
         if (!$uid) {
             throw new Exception();
         }
         $query = new Horde_Imap_Client_Fetch_Query();
         $query->envelope();
         $query->headers('imp', self::$headersUsed, array('cache' => true, 'peek' => true));
         $imp_imap = $mbox->imp_imap;
         $imp_imap->openMailbox($mbox, Horde_Imap_Client::OPEN_READWRITE);
         $ret = $imp_imap->fetch($mbox, $query, array('ids' => $imp_imap->getIdsOb($uid)));
         if (!($ob = $ret->first())) {
             throw new Exception();
         }
         $this->contents = $injector->getInstance('IMP_Factory_Contents')->create($indices);
         if (!$peek) {
             $this->_loadHeaders();
         }
     } catch (Exception $e) {
         throw new IMP_Exception(_("Requested message not found."));
     }
     $this->_envelope = $ob->getEnvelope();
     $this->_headers = $ob->getHeaders('imp', Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
     $this->_indices = $indices;
     $this->_peek = $peek;
 }
Ejemplo n.º 2
0
 /**
  * Renames the old sent-mail mailboxes.
  *
  * Mailbox name: sent-mail-month-year
  *   month = English:         3 letter abbreviation
  *           Other Languages: Month value (01-12)
  *   year  = 4 digit year
  *
  * The mailbox name needs to be in this specific format (as opposed to a
  * user-defined one) to ensure that 'delete_sentmail_monthly' processing
  * can accurately find all the old sent-mail mailboxes.
  *
  * @return boolean  Whether all sent-mail mailboxes were renamed.
  */
 public function execute()
 {
     global $notification;
     $date_format = substr($GLOBALS['language'], 0, 2) == 'en' ? 'M-Y' : 'm-Y';
     $datetime = new DateTime();
     $now = $datetime->format($date_format);
     foreach ($this->_getSentmail() as $sent) {
         /* Display a message to the user and rename the mailbox.
          * Only do this if sent-mail mailbox currently exists. */
         if ($sent->exists) {
             $notification->push(sprintf(_("\"%s\" mailbox being renamed at the start of the month."), $sent->display), 'horde.message');
             $query = new Horde_Imap_Client_Fetch_Query();
             $query->imapDate();
             $query->uid();
             $imp_imap = $sent->imp_imap;
             $res = $imp_imap->fetch($sent, $query);
             $msgs = array();
             foreach ($res as $val) {
                 $date_string = $val->getImapDate()->format($date_format);
                 if (!isset($msgs[$date_string])) {
                     $msgs[$date_string] = $imp_imap->getIdsOb();
                 }
                 $msgs[$date_string]->add($val->getUid());
             }
             unset($msgs[$now]);
             foreach ($msgs as $key => $val) {
                 $new_mbox = IMP_Mailbox::get(strval($sent) . '-' . Horde_String::lower($key));
                 $imp_imap->copy($sent, $new_mbox, array('create' => true, 'ids' => $val, 'move' => true));
             }
         }
     }
     return true;
 }
Ejemplo n.º 3
0
 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;
 }
Ejemplo n.º 4
0
 /**
  */
 public function fetchEnvelope($indices)
 {
     if ($GLOBALS['registry']->hasMethod('mail/imapOb')) {
         $query = new Horde_Imap_Client_Fetch_Query();
         $query->envelope();
         $query->uid();
         try {
             return $GLOBALS['registry']->call('mail/imapOb')->fetch($this->_getMboxOb(), $query, array('ids' => new Horde_Imap_Client_Ids($indices)));
         } catch (Horde_Imap_Client_Exception $e) {
         }
     }
     return false;
 }
Ejemplo n.º 5
0
 /**
  */
 public function getMessageIds()
 {
     if (isset($this->_msgids)) {
         return $this->_msgids;
     }
     $this->_msgids = array();
     $query = new Horde_Imap_Client_Fetch_Query();
     $query->envelope();
     $ret = $this->_mbox->imp_imap->fetch($this->_mbox, $query, array('ids' => $this->_ids));
     foreach ($ret as $ob) {
         $this->_msgids[] = $ob->getEnvelope()->message_id;
     }
     return $this->_msgids;
 }
Ejemplo n.º 6
0
 private function load()
 {
     $headers = [];
     $fetch_query = new \Horde_Imap_Client_Fetch_Query();
     $fetch_query->bodyPart($this->attachmentId);
     $fetch_query->mimeHeader($this->attachmentId);
     $headers = array_merge($headers, ['importance', 'list-post', 'x-priority']);
     $headers[] = 'content-type';
     $fetch_query->headers('imp', $headers, ['cache' => 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 */
     if (!isset($headers[$this->messageId])) {
         throw new DoesNotExistException('Unable to load the attachment.');
     }
     $fetch = $headers[$this->messageId];
     $mimeHeaders = $fetch->getMimeHeader($this->attachmentId, Horde_Imap_Client_Data_Fetch::HEADER_PARSE);
     $this->mimePart = new \Horde_Mime_Part();
     // To prevent potential problems with the SOP we serve all files with the
     // MIME type "application/octet-stream"
     $this->mimePart->setType('application/octet-stream');
     // Serve all files with a content-disposition of "attachment" to prevent Cross-Site Scripting
     $this->mimePart->setDisposition('attachment');
     // Extract headers from part
     $contentDisposition = $mimeHeaders->getValue('content-disposition', \Horde_Mime_Headers::VALUE_PARAMS);
     if (!is_null($contentDisposition)) {
         $vars = ['filename'];
         foreach ($contentDisposition as $key => $val) {
             if (in_array($key, $vars)) {
                 $this->mimePart->setDispositionParameter($key, $val);
             }
         }
     } else {
         $contentDisposition = $mimeHeaders->getValue('content-type', \Horde_Mime_Headers::VALUE_PARAMS);
         $vars = ['name'];
         foreach ($contentDisposition as $key => $val) {
             if (in_array($key, $vars)) {
                 $this->mimePart->setContentTypeParameter($key, $val);
             }
         }
     }
     /* Content transfer encoding. */
     if ($tmp = $mimeHeaders->getValue('content-transfer-encoding')) {
         $this->mimePart->setTransferEncoding($tmp);
     }
     $body = $fetch->getBodyPart($this->attachmentId);
     $this->mimePart->setContents($body);
 }
Ejemplo n.º 7
0
 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 IMAPMessage($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;
 }
Ejemplo n.º 8
0
 /**
  * Obtain the mailbox size
  *
  * @param IMP_Mailbox $mbox   The mailbox to obtain the size of.
  * @param boolean $formatted  Whether to return a human readable value.
  *
  * @return mixed  Either the size of the mailbox (in bytes) or a formatted
  *                string with this information.
  */
 public function getSize(IMP_Mailbox $mbox, $formatted = true)
 {
     $query = new Horde_Imap_Client_Fetch_Query();
     $query->size();
     try {
         $imp_imap = $mbox->imp_imap;
         $res = $imp_imap->fetch($mbox, $query, array('ids' => $imp_imap->getIdsOb(Horde_Imap_Client_Ids::ALL, true)));
         $size = 0;
         foreach ($res as $v) {
             $size += $v->getSize();
         }
         return $formatted ? sprintf(_("%.2fMB"), $size / (1024 * 1024)) : $size;
     } catch (IMP_Imap_Exception $e) {
         return 0;
     }
 }
Ejemplo n.º 9
0
 /**
  */
 public function __get($name)
 {
     switch ($name) {
         case 'indices':
             return $this->_indices;
         case 'msgid':
             if (!$this->_msgid) {
                 list($mbox, $uid) = $this->indices->getSingle();
                 $query = new Horde_Imap_Client_Fetch_Query();
                 $query->envelope();
                 $imp_imap = $mbox->imp_imap;
                 $ret = $imp_imap->fetch($mbox, $query, array('ids' => $imp_imap->getIdsOb($uid)));
                 $this->_msgid = ($ob = $ret->first()) ? $ob->getEnvelope()->message_id : '';
             }
             return $this->_msgid;
     }
 }
Ejemplo n.º 10
0
 /**
  */
 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();
 }
Ejemplo n.º 11
0
 /**
  */
 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();
 }
Ejemplo n.º 12
0
 /**
  * Sort search results client side if the server does not support the SORT
  * IMAP extension (RFC 5256).
  *
  * @param Horde_Imap_Client_Ids $res  The search results.
  * @param array $opts                 The options to _search().
  *
  * @return array  The sort results.
  *
  * @throws Horde_Imap_Client_Exception
  */
 public function clientSort($res, $opts)
 {
     if (!count($res)) {
         return $res;
     }
     /* Generate the FETCH command needed. */
     $query = new Horde_Imap_Client_Fetch_Query();
     foreach ($opts['sort'] as $val) {
         switch ($val) {
             case Horde_Imap_Client::SORT_ARRIVAL:
                 $query->imapDate();
                 break;
             case Horde_Imap_Client::SORT_DATE:
                 $query->imapDate();
                 $query->envelope();
                 break;
             case Horde_Imap_Client::SORT_CC:
             case Horde_Imap_Client::SORT_DISPLAYFROM:
             case Horde_Imap_Client::SORT_DISPLAYTO:
             case Horde_Imap_Client::SORT_FROM:
             case Horde_Imap_Client::SORT_SUBJECT:
             case Horde_Imap_Client::SORT_TO:
                 $query->envelope();
                 break;
             case Horde_Imap_Client::SORT_SEQUENCE:
                 $query->seq();
                 break;
             case Horde_Imap_Client::SORT_SIZE:
                 $query->size();
                 break;
         }
     }
     if (!count($query)) {
         return $res;
     }
     $mbox = $this->_socket->currentMailbox();
     $fetch_res = $this->_socket->fetch($mbox['mailbox'], $query, array('ids' => $res));
     return $this->_clientSortProcess($res->ids, $fetch_res, $opts['sort']);
 }
Ejemplo n.º 13
0
 /**
  */
 protected function _content()
 {
     $inbox = IMP_Mailbox::get('INBOX');
     /* Filter on INBOX display, if requested. */
     $inbox->filterOnDisplay();
     $query = new Horde_Imap_Client_Search_Query();
     $query->flag(Horde_Imap_Client::FLAG_SEEN, false);
     $ids = $inbox->runSearchQuery($query, Horde_Imap_Client::SORT_SEQUENCE, 1);
     $indices = $ids['INBOX'];
     $html = '<table cellspacing="0" width="100%">';
     $text = _("Go to your Inbox...");
     if (empty($indices)) {
         $html .= '<tr><td><em>' . _("No unread messages") . '</em></td></tr>';
     } else {
         $imp_ui = new IMP_Mailbox_Ui($inbox);
         $shown = empty($this->_params['msgs_shown']) ? 3 : $this->_params['msgs_shown'];
         $query = new Horde_Imap_Client_Fetch_Query();
         $query->envelope();
         try {
             $imp_imap = $GLOBALS['injector']->getInstance('IMP_Factory_Imap')->create($inbox);
             $fetch_ret = $imp_imap->fetch($inbox, $query, array('ids' => $imp_imap->getIdsOb(array_slice($indices, 0, $shown))));
         } catch (IMP_Imap_Exception $e) {
             $fetch_ret = new Horde_Imap_Client_Fetch_Results();
         }
         foreach ($fetch_ret as $uid => $ob) {
             $envelope = $ob->getEnvelope();
             $date = $imp_ui->getDate(isset($envelope->date) ? $envelope->date : null);
             $from = $imp_ui->getFrom($envelope);
             $subject = $imp_ui->getSubject($envelope->subject, true);
             $html .= '<tr style="cursor:pointer" class="text"><td>' . $inbox->url('message', $uid)->link() . '<strong>' . htmlspecialchars($from['from'], ENT_QUOTES, 'UTF-8') . '</strong><br />' . $subject . '</a></td>' . '<td>' . htmlspecialchars($date, ENT_QUOTES, 'UTF-8') . '</td></tr>';
         }
         $more_msgs = count($indices) - $shown;
         if ($more_msgs > 0) {
             $text = sprintf(ngettext("%d more unseen message...", "%d more unseen messages...", $more_msgs), $more_msgs);
         }
     }
     return $html . '<tr><td colspan="2" style="cursor:pointer" align="right">' . $inbox->url('mailbox')->link() . $text . '</a></td></tr>' . '</table>';
 }
Ejemplo n.º 14
0
 /**
  * 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;
 }
Ejemplo n.º 15
0
 /**
  */
 public function searchCallback(IMP_Mailbox $mbox, array $ids)
 {
     $fetch_query = new Horde_Imap_Client_Fetch_Query();
     $fetch_query->structure();
     $fetch_res = $mbox->imp_imap->fetch($mbox, $fetch_query, array('ids' => $mbox->imp_imap->getIdsOb($ids)));
     $out = array();
     foreach ($ids as $v) {
         if (isset($fetch_res[$v])) {
             $atc = false;
             foreach ($fetch_res[$v]->getStructure()->partIterator() as $val) {
                 if ($val->isAttachment()) {
                     $atc = true;
                     break;
                 }
             }
             if ($this->_data && $atc || !$this->_data && !$atc) {
                 continue;
             }
         }
         $out[] = $v;
     }
     return $out;
 }
Ejemplo n.º 16
0
 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);
     //		}
 }
Ejemplo n.º 17
0
 /**
  * Generates a string that can be saved out to an mbox format mailbox file
  * for a mailbox (or set of mailboxes), optionally including all
  * subfolders of the selected mailbox(es) as well. All mailboxes will be
  * output in the same string.
  *
  * @param mixed $mboxes  A mailbox name (UTF-8), or list of mailbox names,
  *                       to generate a mbox file for.
  *
  * @return resource  A stream resource containing the text of a mbox
  *                   format mailbox file.
  */
 public function generate($mboxes)
 {
     $body = fopen('php://temp', 'r+');
     if (!is_array($mboxes)) {
         if (!strlen($mboxes)) {
             return $body;
         }
         $mboxes = array($mboxes);
     }
     if (empty($mboxes)) {
         return $body;
     }
     $query = new Horde_Imap_Client_Fetch_Query();
     $query->envelope();
     $query->imapDate();
     $query->headerText(array('peek' => true));
     $query->bodyText(array('peek' => true));
     foreach (IMP_Mailbox::get($mboxes) as $val) {
         $imp_imap = $val->imp_imap;
         $slices = $imp_imap->getSlices($val, $imp_imap->getIdsOb(Horde_Imap_Client_Ids::ALL, true));
         foreach ($slices as $slice) {
             try {
                 $res = $imp_imap->fetch($val, $query, array('ids' => $slice, 'nocache' => true));
             } catch (IMP_Imap_Exception $e) {
                 continue;
             }
             foreach ($res as $ptr) {
                 $from_env = $ptr->getEnvelope()->from;
                 $from = count($from_env) ? $from_env[0]->bare_address : '<>';
                 /* We need this long command since some MUAs (e.g. pine)
                  * require a space in front of single digit days. */
                 $imap_date = $ptr->getImapDate();
                 $date = sprintf('%s %2s %s', $imap_date->format('D M'), $imap_date->format('j'), $imap_date->format('H:i:s Y'));
                 fwrite($body, 'From ' . $from . ' ' . $date . "\r\n");
                 /* Remove spurious 'From ' line in headers. */
                 $stream = $ptr->getHeaderText(0, Horde_Imap_Client_Data_Fetch::HEADER_STREAM);
                 while (!feof($stream)) {
                     $line = fgets($stream);
                     if (substr($line, 0, 5) != 'From ') {
                         fwrite($body, $line);
                     }
                 }
                 fwrite($body, "\r\n");
                 /* Add Body text. */
                 $stream = $ptr->getBodyText(0, true);
                 while (!feof($stream)) {
                     fwrite($body, fread($stream, 8192));
                 }
                 fwrite($body, "\r\n");
             }
         }
     }
     return $body;
 }
Ejemplo n.º 18
0
 /**
  * Fetch data from the IMAP client.
  *
  * @param  array $params  Parameter array.
  *     - html_id (string)  The MIME id of the HTML part, if any.
  *     - text_id (string)  The MIME id of the plain part, if any.
  *
  * @return Horde_Imap_Client_Data_Fetch  The results.
  */
 protected function _fetchData(array $params)
 {
     $query = new Horde_Imap_Client_Fetch_Query();
     $query_opts = array('decode' => true, 'peek' => true);
     // Get body information
     if ($this->_version >= Horde_ActiveSync::VERSION_TWELVE) {
         if (!empty($params['html_id'])) {
             $query->bodyPartSize($params['html_id']);
             $query->bodyPart($params['html_id'], $query_opts);
         }
         if (!empty($params['text_id'])) {
             $query->bodyPart($params['text_id'], $query_opts);
             $query->bodyPartSize($params['text_id']);
         }
     } else {
         // EAS 2.5 Plaintext body
         $query->bodyPart($params['text_id'], $query_opts);
         $query->bodyPartSize($params['text_id']);
     }
     try {
         $fetch_ret = $this->_imap->fetch($this->_mbox, $query, array('ids' => new Horde_Imap_Client_Ids(array($this->_uid))));
     } catch (Horde_Imap_Client_Exception $e) {
         throw new Horde_ActiveSync_Exception($e);
     }
     if (!($data = $fetch_ret->first())) {
         throw new Horde_Exception_NotFound(sprintf('Could not load message %s from server.', $this->_uid));
     }
     return $data;
 }
Ejemplo n.º 19
0
 /**
  * Retrieves a bodypart for the given message ID and mime part ID.
  *
  * @param string $folder The folder to fetch the messages from.
  * @param array  $uid                 The message UID.
  * @param array  $id                  The mime part ID.
  *
  * @return resource  The body part, as a stream resource.
  */
 public function fetchBodypart($folder, $uid, $id)
 {
     $query = new Horde_Imap_Client_Fetch_Query();
     $query->structure();
     $query->bodyPart($id, array('decode' => true));
     try {
         $ret = $this->getBackend()->fetch($folder, $query, array('ids' => new Horde_Imap_Client_Ids($uid)));
         $part = $ret[$uid]->getStructure()->getPart($id);
         $part->setContents($ret[$uid]->getBodyPart($id, true), array('encoding' => $ret[$uid]->getBodyPartDecode($id), 'usestream' => true));
         return $part->getContents(array('stream' => true));
     } catch (Horde_Imap_Client_Exception_ServerResponse $e) {
         throw new Horde_Kolab_Storage_Exception($e->details);
     } catch (Horde_Imap_Client_Exception $e) {
         throw new Horde_Kolab_Storage_Exception($e);
     }
 }
Ejemplo n.º 20
0
 /**
  * Attempt to determine whether this message is a bulk message (e.g. automated reply).
  *
  * @param \Horde_Imap_Client_Data_Fetch $message The message to process
  * @param string|\Horde_Imap_Client_Ids $messageid The Hore message Uid
  * @return boolean
  */
 private function is_bulk_message(\Horde_Imap_Client_Data_Fetch $message, $messageid)
 {
     $query = new \Horde_Imap_Client_Fetch_Query();
     $query->headerText(array('peek' => true));
     $messagedata = $this->client->fetch($this->get_mailbox(), $query, array('ids' => $messageid))->first();
     // Assume that this message is not bulk to begin with.
     $isbulk = false;
     // An auto-reply may itself include the Bulk Precedence.
     $precedence = $messagedata->getHeaderText(0, \Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->getValue('Precedence');
     $isbulk = $isbulk || strtolower($precedence) == 'bulk';
     // If the X-Autoreply header is set, and not 'no', then this is an automatic reply.
     $autoreply = $messagedata->getHeaderText(0, \Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->getValue('X-Autoreply');
     $isbulk = $isbulk || $autoreply && $autoreply != 'no';
     // If the X-Autorespond header is set, and not 'no', then this is an automatic response.
     $autorespond = $messagedata->getHeaderText(0, \Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->getValue('X-Autorespond');
     $isbulk = $isbulk || $autorespond && $autorespond != 'no';
     // If the Auto-Submitted header is set, and not 'no', then this is a non-human response.
     $autosubmitted = $messagedata->getHeaderText(0, \Horde_Imap_Client_Data_Fetch::HEADER_PARSE)->getValue('Auto-Submitted');
     $isbulk = $isbulk || $autosubmitted && $autosubmitted != 'no';
     return $isbulk;
 }
Ejemplo n.º 21
0
 /**
  * Gets the raw text for one section of the message.
  *
  * @param integer $id     The ID of the MIME part.
  * @param array $options  Additional options:
  *   - decode: (boolean) Attempt to decode the bodypart on the remote
  *             server. If successful, sets self::$_lastBodyPartDecode to
  *             the content-type of the decoded data.
  *             DEFAULT: No
  *   - length: (integer) If set, only download this many bytes of the
  *             bodypart from the server.
  *             DEFAULT: All data is retrieved.
  *   - mimeheaders: (boolean) Include the MIME headers also?
  *                  DEFAULT: No
  *   - stream: (boolean) If true, return a stream.
  *             DEFAULT: No
  *
  * @return mixed  The text of the part or a stream resource if 'stream'
  *                is true.
  * @todo Simplify by removing 'mimeheaders' parameter (not used).
  */
 public function getBodyPart($id, $options)
 {
     $options = array_merge(array('decode' => false, 'mimeheaders' => false, 'stream' => false), $options);
     $this->_lastBodyPartDecode = null;
     $query = new Horde_Imap_Client_Fetch_Query();
     if (!isset($options['length']) || !empty($options['length'])) {
         $bodypart_params = array('decode' => true, 'peek' => true);
         if (isset($options['length'])) {
             $bodypart_params['start'] = 0;
             $bodypart_params['length'] = $options['length'];
         }
         $query->bodyPart($id, $bodypart_params);
     }
     if (!empty($options['mimeheaders'])) {
         $query->mimeHeader($id, array('peek' => true));
     }
     $fetch_res = $this->_imap->fetch($this->_mbox, $query, array('ids' => new Horde_Imap_Client_Ids(array($this->uid))));
     if (empty($options['mimeheaders'])) {
         $this->_lastBodyPartDecode = $fetch_res[$this->uid]->getBodyPartDecode($id);
         return $fetch_res[$this->uid]->getBodyPart($id, $options['stream']);
     } elseif (empty($options['stream'])) {
         return $fetch_res[$this->uid]->getMimeHeader($id) . $fetch_res[$this->uid]->getBodyPart($id);
     } else {
         $swrapper = new Horde_Support_CombineStream(array($fetch_res[$this->uid]->getMimeHeader($id, Horde_Imap_Client_Data_Fetch::HEADER_STREAM), $fetch_res[$this->uid]->getBodyPart($id, true)));
         return $swrapper->fopen();
     }
 }
Ejemplo n.º 22
0
 /**
  */
 protected function _init()
 {
     global $injector, $notification, $page_output, $registry, $session;
     $imp_mailbox = $this->indices->mailbox->list_ob;
     switch ($mode = $this->vars->get('mode', 'thread')) {
         case 'thread':
             /* THREAD MODE: Make sure we have a valid index. */
             list($m, $u) = $this->indices->getSingle();
             $imp_indices = $imp_mailbox->getFullThread($u, $m);
             break;
         default:
             /* MSGVIEW MODE: Make sure we have a valid list of messages. */
             $imp_indices = $this->indices;
             break;
     }
     if (!count($imp_indices)) {
         $notification->push(_("Could not load message."), 'horde.error');
         $this->indices->mailbox->url('mailbox')->redirect();
     }
     /* Run through action handlers. */
     switch ($this->vars->actionID) {
         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;
     }
     $msgs = $tree = array();
     $subject = '';
     $page_label = $this->indices->mailbox->label;
     $imp_ui = $injector->getInstance('IMP_Message_Ui');
     $query = new Horde_Imap_Client_Fetch_Query();
     $query->envelope();
     /* Force images to show in HTML data. */
     $injector->getInstance('IMP_Images')->alwaysShow = true;
     $multiple = count($imp_indices) > 1;
     foreach ($imp_indices as $ob) {
         $imp_imap = $ob->mbox->imp_imap;
         $fetch_res = $imp_imap->fetch($ob->mbox, $query, array('ids' => $imp_imap->getIdsOb($ob->uids)));
         foreach ($ob->uids as $idx) {
             $envelope = $fetch_res[$idx]->getEnvelope();
             /* Get the body of the message. */
             $curr_msg = $curr_tree = array();
             $contents = $injector->getInstance('IMP_Factory_Contents')->create($ob->mbox->getIndicesOb($idx));
             $mime_id = $contents->findBody();
             if ($contents->canDisplay($mime_id, IMP_Contents::RENDER_INLINE)) {
                 $ret = $contents->renderMIMEPart($mime_id, IMP_Contents::RENDER_INLINE);
                 $ret = reset($ret);
                 $curr_msg['body'] = $ret['data'];
                 if (!empty($ret['js'])) {
                     $page_output->addInlineScript($ret['js'], true);
                 }
             } else {
                 $curr_msg['body'] = '<em>' . _("There is no text that can be displayed inline.") . '</em>';
             }
             $curr_msg['idx'] = $idx;
             /* Get headers for the message. */
             $date_ob = new IMP_Message_Date($envelope->date);
             $curr_msg['date'] = $date_ob->format($date_ob::DATE_LOCAL);
             if ($this->indices->mailbox->special_outgoing) {
                 $curr_msg['addr_to'] = true;
                 $curr_msg['addr'] = _("To:") . ' ' . $imp_ui->buildAddressLinks($envelope->to, Horde::selfUrlParams());
                 $addr = _("To:") . ' ' . htmlspecialchars($envelope->to[0]->label, ENT_COMPAT, 'UTF-8');
             } else {
                 $from = $envelope->from;
                 $curr_msg['addr_to'] = false;
                 $curr_msg['addr'] = $imp_ui->buildAddressLinks($from, Horde::selfUrlParams());
                 $addr = htmlspecialchars($from[0]->label, ENT_COMPAT, 'UTF-8');
             }
             $subject_header = htmlspecialchars($envelope->subject, ENT_COMPAT, 'UTF-8');
             switch ($mode) {
                 case 'thread':
                     if (empty($subject)) {
                         $subject = preg_replace('/^re:\\s*/i', '', $subject_header);
                     }
                     $curr_msg['link'] = $multiple ? Horde::widget(array('url' => '#display', 'title' => _("Thread List"), 'nocheck' => true)) : '';
                     $curr_tree['subject'] = $imp_mailbox->getThreadOb($imp_mailbox->getArrayIndex($fetch_res[$idx]->getUid(), $ob->mbox) + 1)->img;
                     break;
                 default:
                     $curr_msg['link'] = Horde::widget(array('url' => '#display', 'title' => _("Back to Multiple Message View Index"), 'nocheck' => true));
                     $curr_tree['subject'] = '';
                     break;
             }
             switch ($registry->getView()) {
                 case $registry::VIEW_BASIC:
                     $curr_msg['link'] .= ' | ' . Horde::widget(array('url' => $this->indices->mailbox->url('message', $idx), 'title' => _("Go to Message"), 'nocheck' => true)) . ' | ' . Horde::widget(array('url' => $this->indices->mailbox->url('mailbox')->add(array('start' => $imp_mailbox->getArrayIndex($idx))), 'title' => sprintf(_("Bac_k to %s"), $page_label)));
                     break;
             }
             $curr_tree['subject'] .= Horde::link('#i' . $idx) . Horde_String::truncate($subject_header, 60) . '</a> (' . $addr . ')';
             $msgs[] = $curr_msg;
             $tree[] = $curr_tree;
         }
     }
     /* Flag messages as seen. */
     $injector->getInstance('IMP_Message')->flag(array('add' => array(Horde_Imap_Client::FLAG_SEEN)), $imp_indices);
     $view = new Horde_View(array('templatePath' => IMP_TEMPLATES . '/thread'));
     if ($mode == 'thread') {
         $view->subject = $subject;
         $view->thread = true;
         switch ($registry->getView()) {
             case $registry::VIEW_BASIC:
                 $uid_list = $imp_indices[strval($this->indices->mailbox)];
                 $delete_link = $this->indices->mailbox->url('mailbox')->add(array('actionID' => 'delete_messages', 'indices' => strval($imp_indices), 'token' => $session->getToken(), 'start' => $imp_mailbox->getArrayIndex(end($uid_list))));
                 $view->delete = Horde::link($delete_link, _("Delete Thread"), null, null, null, null, null, array('id' => 'threaddelete'));
                 $page_output->addInlineScript(array('$("threaddelete").observe("click", function(e) { if (!window.confirm(' . json_encode(_("Are you sure you want to delete all messages in this thread?")) . ')) { e.stop(); } })'), true);
                 break;
         }
     } else {
         $view->subject = sprintf(_("%d Messages"), count($msgs));
     }
     $view->messages = $msgs;
     $view->tree = $tree;
     $page_output->addScriptFile('stripe.js', 'horde');
     $page_output->addScriptFile('toggle_quotes.js', 'horde');
     $page_output->noDnsPrefetch();
     $this->output = $view->render('thread');
     switch ($registry->getView()) {
         case $registry::VIEW_DYNAMIC:
             $page_output->topbar = $page_output->sidebar = false;
             $this->header_params = array('html_id' => 'htmlAllowScroll');
             break;
     }
     $this->title = $mode == 'thread' ? _("Thread View") : _("Multiple Message View");
 }
Ejemplo n.º 23
0
 /**
  * @throws Horde_Imap_Client_Exception_NoSupportExtension
  */
 protected function _thread($options)
 {
     $thread_criteria = array(Horde_Imap_Client::THREAD_ORDEREDSUBJECT => 'ORDEREDSUBJECT', Horde_Imap_Client::THREAD_REFERENCES => 'REFERENCES', Horde_Imap_Client::THREAD_REFS => 'REFS');
     $tsort = isset($options['criteria']) ? is_string($options['criteria']) ? strtoupper($options['criteria']) : $thread_criteria[$options['criteria']] : 'ORDEREDSUBJECT';
     $cap = $this->queryCapability('THREAD');
     if (!$cap || !in_array($tsort, $cap)) {
         switch ($tsort) {
             case 'ORDEREDSUBJECT':
                 if (empty($options['search'])) {
                     $ids = $this->getIdsOb(Horde_Imap_Client_Ids::ALL, !empty($options['sequence']));
                 } else {
                     $search_res = $this->search($this->_selected, $options['search'], array('sequence' => !empty($options['sequence'])));
                     $ids = $search_res['match'];
                 }
                 /* Do client-side ORDEREDSUBJECT threading. */
                 $query = new Horde_Imap_Client_Fetch_Query();
                 $query->envelope();
                 $query->imapDate();
                 $fetch_res = $this->fetch($this->_selected, $query, array('ids' => $ids));
                 if (!isset($this->_temp['clientsort'])) {
                     $this->_temp['clientsort'] = new Horde_Imap_Client_Socket_ClientSort($this);
                 }
                 return $this->_temp['clientsort']->threadOrderedSubject($fetch_res, empty($options['sequence']));
             case 'REFERENCES':
             case 'REFS':
                 throw new Horde_Imap_Client_Exception_NoSupportExtension('THREAD', sprintf('Server does not support "%s" thread sort.', $tsort));
         }
     }
     $cmd = $this->_clientCommand(array(empty($options['sequence']) ? 'UID' : null, 'THREAD', $tsort));
     if (empty($options['search'])) {
         $cmd->add(array('US-ASCII', 'ALL'));
     } else {
         $search_query = $options['search']->build();
         $cmd->add(is_null($search_query['charset']) ? 'US-ASCII' : $search_query['charset']);
         $cmd->add($search_query['query'], true);
     }
     $this->_sendLine($cmd);
     return new Horde_Imap_Client_Data_Thread($this->_temp['threadparse'], empty($options['sequence']) ? 'uid' : 'sequence');
 }
Ejemplo n.º 24
0
 /**
  * Check whether the message has the specified flag
  *
  * @param $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);
 }
Ejemplo n.º 25
0
 /**
  * Parse a FETCH response (RFC 3501 [7.4.2]). A FETCH response may occur
  * due to a FETCH command, or due to a change in a message's state (i.e.
  * the flags change).
  *
  * @param Horde_Imap_Client_Interaction_Pipeline $pipeline  Pipeline
  *                                                          object.
  * @param integer $id                       The message sequence number.
  * @param Horde_Imap_Client_Tokenize $data  The server response.
  */
 protected function _parseFetch(Horde_Imap_Client_Interaction_Pipeline $pipeline, $id, Horde_Imap_Client_Tokenize $data)
 {
     if ($data->next() !== true) {
         return;
     }
     $ob = $pipeline->fetch->get($id);
     $ob->setSeq($id);
     $flags = $modseq = $uid = false;
     while (($tag = $data->next()) !== false) {
         $tag = strtoupper($tag);
         switch ($tag) {
             case 'BODYSTRUCTURE':
                 $data->next();
                 $structure = $this->_parseBodystructure($data);
                 $structure->buildMimeIds();
                 $ob->setStructure($structure);
                 break;
             case 'ENVELOPE':
                 $data->next();
                 $ob->setEnvelope($this->_parseEnvelope($data));
                 break;
             case 'FLAGS':
                 $data->next();
                 $ob->setFlags($data->flushIterator());
                 $flags = true;
                 break;
             case 'INTERNALDATE':
                 $ob->setImapDate($data->next());
                 break;
             case 'RFC822.SIZE':
                 $ob->setSize($data->next());
                 break;
             case 'UID':
                 $ob->setUid($data->next());
                 $uid = true;
                 break;
             case 'MODSEQ':
                 $data->next();
                 $modseq = $data->next();
                 $data->next();
                 /* MODSEQ must be greater than 0, so do sanity checking. */
                 if ($modseq > 0) {
                     $ob->setModSeq($modseq);
                     /* Store MODSEQ value. It may be used as the highestmodseq
                      * once a tagged response is received (RFC 7162 [6]). */
                     $pipeline->data['modseqs'][] = $modseq;
                 }
                 break;
             default:
                 // Catch BODY[*]<#> responses
                 if (strpos($tag, 'BODY[') === 0) {
                     // Remove the beginning 'BODY['
                     $tag = substr($tag, 5);
                     // BODY[HEADER.FIELDS] request
                     if (!empty($pipeline->data['fetch_lookup']) && strpos($tag, 'HEADER.FIELDS') !== false) {
                         $data->next();
                         $sig = $tag . ' (' . implode(' ', array_map('strtoupper', $data->flushIterator())) . ')';
                         // Ignore the trailing bracket
                         $data->next();
                         $ob->setHeaders($pipeline->data['fetch_lookup'][$sig], $data->next());
                     } else {
                         // Remove trailing bracket and octet start info
                         $tag = substr($tag, 0, strrpos($tag, ']'));
                         if (!strlen($tag)) {
                             // BODY[] request
                             if (!is_null($tmp = $data->next())) {
                                 $ob->setFullMsg($tmp);
                             }
                         } elseif (is_numeric(substr($tag, -1))) {
                             // BODY[MIMEID] request
                             if (!is_null($tmp = $data->next())) {
                                 $ob->setBodyPart($tag, $tmp);
                             }
                         } else {
                             // BODY[HEADER|TEXT|MIME] request
                             if (($last_dot = strrpos($tag, '.')) === false) {
                                 $mime_id = 0;
                             } else {
                                 $mime_id = substr($tag, 0, $last_dot);
                                 $tag = substr($tag, $last_dot + 1);
                             }
                             if (!is_null($tmp = $data->next())) {
                                 switch ($tag) {
                                     case 'HEADER':
                                         $ob->setHeaderText($mime_id, $tmp);
                                         break;
                                     case 'TEXT':
                                         $ob->setBodyText($mime_id, $tmp);
                                         break;
                                     case 'MIME':
                                         $ob->setMimeHeader($mime_id, $tmp);
                                         break;
                                 }
                             }
                         }
                     }
                 } elseif (strpos($tag, 'BINARY[') === 0) {
                     // Catch BINARY[*]<#> responses
                     // Remove the beginning 'BINARY[' and the trailing bracket
                     // and octet start info
                     $tag = substr($tag, 7, strrpos($tag, ']') - 7);
                     $body = $data->next();
                     if (is_null($body)) {
                         /* Dovecot bug (as of 2.2.12): binary fetch of body
                          * part may fail with NIL return if decoding failed on
                          * server. Try again with non-decoded body. */
                         $bq = $pipeline->data['binaryquery'][$tag];
                         unset($bq['decode']);
                         $query = new Horde_Imap_Client_Fetch_Query();
                         $query->bodyPart($tag, $bq);
                         $qids = ($quid = $ob->getUid()) ? new Horde_Imap_Client_Ids($quid) : new Horde_Imap_Client_Ids($id, true);
                         $pipeline->data['fetch_followup'][] = array('_query' => $query, 'ids' => $qids);
                     } else {
                         $ob->setBodyPart($tag, $body, empty($this->_temp['literal8']) ? '8bit' : 'binary');
                     }
                 } elseif (strpos($tag, 'BINARY.SIZE[') === 0) {
                     // Catch BINARY.SIZE[*] responses
                     // Remove the beginning 'BINARY.SIZE[' and the trailing
                     // bracket and octet start info
                     $tag = substr($tag, 12, strrpos($tag, ']') - 12);
                     $ob->setBodyPartSize($tag, $data->next());
                 }
                 break;
         }
     }
     /* MODSEQ issue: Oh joy. Per RFC 5162 (see Errata #1807), FETCH FLAGS
      * responses are NOT required to provide UID information, even if
      * QRESYNC is explicitly enabled. Caveat: the FLAGS information
      * returned during a SELECT/EXAMINE MUST contain UIDs so we are OK
      * there.
      * The good news: all decent IMAP servers (Cyrus, Dovecot) will always
      * provide UID information, so this is not normally an issue.
      * The bad news: spec-wise, this behavior cannot be 100% guaranteed.
      * Compromise: We will watch for a FLAGS response with a MODSEQ and
      * check if a UID exists also. If not, put the sequence number in a
      * queue - it is possible the UID information may appear later in an
      * untagged response. When the command is over, double check to make
      * sure there are none of these MODSEQ/FLAGS that are still UID-less.
      * In the (rare) event that there is, don't cache anything and
      * immediately close the mailbox: flags will be correctly sync'd next
      * mailbox open so we only lose a bit of caching efficiency.
      * Otherwise, we could end up with an inconsistent cached state.
      * This Errata has been fixed in 7162 [3.2.4]. */
     if ($flags && $modseq && !$uid) {
         $pipeline->data['modseqs_nouid'][] = $id;
     }
 }
Ejemplo n.º 26
0
 /**
  * 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;
 }
Ejemplo n.º 27
0
 /**
  *
  * @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);
     }
 }
Ejemplo n.º 28
0
 /**
  * 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));
 }
Ejemplo n.º 29
0
 /**
  * Returns base header information.
  *
  * @param integer $type  See getHeader().
  * @param boolean $seen  Mark message as seen?
  *
  * @return mixed  See getHeader().
  */
 protected function _getHeader($type, $seen)
 {
     if (!isset($this->_header)) {
         if (!$this->_indices) {
             $this->_header = $this->_message->addMimeHeaders();
         } else {
             $query = new Horde_Imap_Client_Fetch_Query();
             $query->headerText(array('peek' => !$seen));
             $this->_header = ($res = $this->_fetchData($query)) ? $res : new Horde_Imap_Client_Data_Fetch();
         }
     }
     switch ($type) {
         case self::HEADER_OB:
             return $this->_indices ? $this->_header->getHeaderText(0, Horde_Imap_Client_Data_Fetch::HEADER_PARSE) : $this->_header;
         case self::HEADER_TEXT:
             return $this->_indices ? $this->_header->getHeaderText() : $this->_header->toString();
         case self::HEADER_STREAM:
             if ($this->_indices) {
                 return $this->_header->getHeaderText(0, Horde_Imap_Client_Data_Fetch::HEADER_STREAM);
             }
             $stream = new Horde_Support_StringStream($this->_header->toString());
             $stream->fopen();
             return $stream;
     }
 }
Ejemplo n.º 30
0
 /**
  * Given an IMAP URL, fetches the corresponding part.
  *
  * @param Horde_Imap_Client_Url_Imap $url  An IMAP URL.
  *
  * @return resource  The section contents in a stream. Returns null if
  *                   the part could not be found.
  *
  * @throws Horde_Imap_Client_Exception
  */
 public function fetchFromUrl(Horde_Imap_Client_Url_Imap $url)
 {
     $ids_ob = $this->_socket->getIdsOb($url->uid);
     // BODY[]
     if (is_null($url->section)) {
         $query = new Horde_Imap_Client_Fetch_Query();
         $query->fullText(array('peek' => true));
         $fetch = $this->_socket->fetch($url->mailbox, $query, array('ids' => $ids_ob));
         return $fetch[$url->uid]->getFullMsg(true);
     }
     $section = trim($url->section);
     // BODY[<#.>HEADER.FIELDS<.NOT>()]
     if (($pos = stripos($section, 'HEADER.FIELDS')) !== false) {
         $hdr_pos = strpos($section, '(');
         $cmd = substr($section, 0, $hdr_pos);
         $query = new Horde_Imap_Client_Fetch_Query();
         $query->headers('section', explode(' ', substr($section, $hdr_pos + 1, strrpos($section, ')') - $hdr_pos)), array('id' => $pos ? substr($section, 0, $pos - 1) : 0, 'notsearch' => stripos($cmd, '.NOT') !== false, 'peek' => true));
         $fetch = $this->_socket->fetch($url->mailbox, $query, array('ids' => $ids_ob));
         return $fetch[$url->uid]->getHeaders('section', Horde_Imap_Client_Data_Fetch::HEADER_STREAM);
     }
     // BODY[#]
     if (is_numeric(substr($section, -1))) {
         $query = new Horde_Imap_Client_Fetch_Query();
         $query->bodyPart($section, array('peek' => true));
         $fetch = $this->_socket->fetch($url->mailbox, $query, array('ids' => $ids_ob));
         return $fetch[$url->uid]->getBodyPart($section, true);
     }
     // BODY[<#.>HEADER]
     if (($pos = stripos($section, 'HEADER')) !== false) {
         $id = $pos ? substr($section, 0, $pos - 1) : 0;
         $query = new Horde_Imap_Client_Fetch_Query();
         $query->headerText(array('id' => $id, 'peek' => true));
         $fetch = $this->_socket->fetch($url->mailbox, $query, array('ids' => $ids_ob));
         return $fetch[$url->uid]->getHeaderText($id, Horde_Imap_Client_Data_Fetch::HEADER_STREAM);
     }
     // BODY[<#.>TEXT]
     if (($pos = stripos($section, 'TEXT')) !== false) {
         $id = $pos ? substr($section, 0, $pos - 1) : 0;
         $query = new Horde_Imap_Client_Fetch_Query();
         $query->bodyText(array('id' => $id, 'peek' => true));
         $fetch = $this->_socket->fetch($url->mailbox, $query, array('ids' => $ids_ob));
         return $fetch[$url->uid]->getBodyText($id, true);
     }
     // BODY[<#.>MIMEHEADER]
     if (($pos = stripos($section, 'MIME')) !== false) {
         $id = $pos ? substr($section, 0, $pos - 1) : 0;
         $query = new Horde_Imap_Client_Fetch_Query();
         $query->mimeHeader($id, array('peek' => true));
         $fetch = $this->_socket->fetch($url->mailbox, $query, array('ids' => $ids_ob));
         return $fetch[$url->uid]->getMimeHeader($id, Horde_Imap_Client_Data_Fetch::HEADER_STREAM);
     }
     return null;
 }