public function getCustomerByEmail(Mirasvit_Helpdesk_Model_Email $email)
 {
     $customers = Mage::getModel('customer/customer')->getCollection();
     $customers->addAttributeToSelect('*')->addFieldToFilter('email', $email->getFromEmail())->addFieldToFilter('store_id', $email->getGateway()->getStoreId());
     if ($customers->count()) {
         return $customers->getFirstItem();
     }
     // customer may be registered in store A, but sends email to gateway of store B
     $customers = Mage::getModel('customer/customer')->getCollection();
     $customers->addAttributeToSelect('*')->addFieldToFilter('email', $email->getFromEmail());
     if ($customers->count()) {
         return $customers->getFirstItem();
     }
     /** @var Mage_Customer_Model_Customer $address */
     $address = $customers->getLastItem();
     if ($address->getId()) {
         $customer = new Varien_Object();
         $customer->setName($address->getName());
         $customer->setEmail($address->getEmail());
         $customer->setQuoteAddressId($address->getId());
         return $customer;
     }
     $customer = new Varien_Object();
     if ($email->getSenderName() == '') {
         $customer->setName($email->getFromEmail());
     } else {
         $customer->setName($email->getSenderName());
     }
     $customer->setEmail($email->getFromEmail());
     return $customer;
 }
 /**
  * @param Mirasvit_Helpdesk_Model_Email $email
  *
  * @return bool|Mirasvit_Helpdesk_Model_Ticket
  */
 public function processEmail($email)
 {
     // $code = false;
     // if (Mage::getSingleton('helpdesk/config')->getNotificationIsShowCode()) {
     //get object by code from subject
     $code = Mage::helper('helpdesk/string')->getTicketCodeFromSubject($email->getSubject());
     // }
     if (!$code) {
         $code = Mage::helper('helpdesk/string')->getTicketCodeFromBody($email->getBody());
     }
     if (strpos($code, 'RMA') === 0 && $this->getConfig()->isActiveRma()) {
         return Mage::helper('rma/process')->processEmail($email, $code);
     } else {
         return Mage::helper('helpdesk/process')->processEmail($email, $code);
     }
 }
 /**
  * @param Mirasvit_Helpdesk_Model_Email $email
  *
  * @return bool
  */
 public function checkEmail($email)
 {
     $subject = '';
     switch ($this->getScope()) {
         case 'headers':
             $subject = $email->getHeaders();
             break;
         case 'subject':
             $subject = $email->getSubject();
             break;
         case 'body':
             $subject = $email->getBody();
             break;
     }
     $matches = array();
     preg_match($this->getPattern(), $subject, $matches);
     if (count($matches) > 0) {
         return true;
     } else {
         return false;
     }
 }
 /**
  * @param Mirasvit_Helpdesk_Model_Email $email
  * @param string                        $code
  *
  * @return bool|Mirasvit_Helpdesk_Model_Ticket
  *
  * @throws Exception
  */
 public function processEmail($email, $code)
 {
     $ticket = false;
     $customer = false;
     $user = false;
     $triggeredBy = Mirasvit_Helpdesk_Model_Config::CUSTOMER;
     $messageType = Mirasvit_Helpdesk_Model_Config::MESSAGE_PUBLIC;
     if ($code) {
         //try to find customer for this email
         $tickets = Mage::getModel('helpdesk/ticket')->getCollection();
         $tickets->addFieldToFilter('code', $code)->addFieldToFilter('customer_email', $email->getFromEmail());
         if ($tickets->count()) {
             $ticket = $tickets->getFirstItem();
         } else {
             //try to find staff user for this email
             $users = Mage::getModel('admin/user')->getCollection()->addFieldToFilter('email', $email->getFromEmail());
             if ($users->count()) {
                 $user = $users->getFirstItem();
                 $tickets = Mage::getModel('helpdesk/ticket')->getCollection()->addFieldToFilter('code', $code);
                 if ($tickets->count()) {
                     $ticket = $tickets->getFirstItem();
                     $ticket->setUserId($user->getId());
                     $ticket->save();
                     $triggeredBy = Mirasvit_Helpdesk_Model_Config::USER;
                 } else {
                     $user = false;
                     //@temp dva for testing
                 }
             } else {
                 //third party
                 $tickets = Mage::getModel('helpdesk/ticket')->getCollection()->addFieldToFilter('code', $code);
                 if ($tickets->count()) {
                     $ticket = $tickets->getFirstItem();
                     $triggeredBy = Mirasvit_Helpdesk_Model_Config::THIRD;
                     if ($ticket->isThirdPartyPublic()) {
                         $messageType = Mirasvit_Helpdesk_Model_Config::MESSAGE_PUBLIC_THIRD;
                     } else {
                         $messageType = Mirasvit_Helpdesk_Model_Config::MESSAGE_INTERNAL_THIRD;
                     }
                 }
             }
         }
     }
     if (!$user) {
         $customer = Mage::helper('helpdesk/customer')->getCustomerByEmail($email);
     }
     // create a new ticket
     if (!$ticket) {
         $ticket = Mage::getModel('helpdesk/ticket');
         if (!$code) {
             $ticket->setCode(Mage::helper('helpdesk/string')->generateTicketCode());
         } else {
             $ticket->setCode($code);
             //temporary for testing to fix @dva
         }
         $gateway = Mage::getModel('helpdesk/gateway')->load($email->getGatewayId());
         if ($gateway->getId()) {
             if ($gateway->getDepartmentId()) {
                 $ticket->setDepartmentId($gateway->getDepartmentId());
             } else {
                 //if department was removed
                 $departments = Mage::getModel('helpdesk/department')->getCollection()->addFieldToFilter('is_active', true);
                 if ($departments->count()) {
                     $department = $departments->getFirstItem();
                     $ticket->setDepartmentId($department->getId());
                 } else {
                     // throw new Exception("Helpdesk MX - Can't find any active department. Helpdesk can't fetch tickets correctly!");
                     Mage::log('Helpdesk MX - Can\'t find any active department. Helpdesk can\'t fetch tickets correctly!');
                 }
             }
             $ticket->setStoreId($gateway->getStoreId());
         }
         $ticket->setName($email->getSubject())->setCustomerName($customer->getName())->setCustomerId($customer->getId())->setQuoteAddressId($customer->getQuoteAddressId())->setCustomerEmail($email->getFromEmail())->setChannel(Mirasvit_Helpdesk_Model_Config::CHANNEL_EMAIL)->setCc($email->getCc());
         $ticket->setEmailId($email->getId());
         $ticket->save();
         if ($pattern = $this->checkForSpamPattern($email)) {
             $ticket->markAsSpam($pattern);
             if ($email) {
                 $email->setPatternId($pattern->getId())->save();
             }
         }
     }
     if ($customer) {
         //parse order ID from email subject
         preg_match_all('[[0-9]{9}]', $email->getSubject(), $numbers);
         foreach ($numbers[0] as $number) {
             $orders = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('increment_id', $number)->addFieldToFilter('customer_id', $customer->getId());
             if (count($orders)) {
                 // Case 1: this is registered customer and has an order
                 $order = Mage::getModel('sales/order')->loadByAttribute('increment_id', $number);
                 $ticket->setCustomerId($order->getCustomerId());
                 $ticket->setOrderId($order->getId());
                 $ticket->save();
                 break;
             } else {
                 $order = Mage::getModel('sales/order')->loadByAttribute('increment_id', $number);
                 $ticket->setOrderId($order->getId());
                 // Case 2: this is known guest customer or known another email of registered customer
                 $prevTickets = Mage::getModel('helpdesk/ticket')->getCollection()->addFieldToFilter('customer_email', $email->getFromEmail())->addFieldToFilter('order_id', $order->getId());
                 if (count($prevTickets)) {
                     $ticket->setCustomerId($order->getCustomerId());
                     $ticket->save();
                     break;
                 }
                 // Case 3: this is generic guest customer with existing order
                 $quotes = Mage::getModel('sales/order_address')->getCollection();
                 $quotes->addFieldToFilter('email', $email->getFromEmail());
                 $quotes->getSelect()->group('email');
                 if ($quotes->count()) {
                     $ticket->setQuoteAddressId($quotes->getFirstItem()->getId());
                     $ticket->save();
                     break;
                 }
             }
         }
     }
     //add message to ticket
     $text = $email->getBody();
     $encodingHelper = Mage::helper('helpdesk/encoding');
     $text = $encodingHelper->toUTF8($text);
     $body = Mage::helper('helpdesk/string')->parseBody($text, $email->getFormat());
     $ticket->addMessage($body, $customer, $user, $triggeredBy, $messageType, $email);
     Mage::dispatchEvent('helpdesk_process_email', array('body' => $body, 'customer' => $customer, 'user' => $user, 'ticket' => $ticket));
     Mage::helper('helpdesk/history')->changeTicket($ticket, $triggeredBy, array('user' => $user, 'customer' => $customer));
     return $ticket;
 }
 /**
  * @param string                                           $text
  * @param Mage_Customer_Model_Customer|Varien_Object|false $customer
  * @param Mage_Admin_Model_User|false                      $user
  * @param string                                           $triggeredBy
  * @param string                                           $messageType
  * @param bool|Mirasvit_Helpdesk_Model_Email               $email
  * @param bool|string                                      $bodyFormat
  *
  * @return Mirasvit_Helpdesk_Model_Message
  *
  * @throws Exception
  */
 public function addMessage($text, $customer, $user, $triggeredBy, $messageType = Mirasvit_Helpdesk_Model_Config::MESSAGE_PUBLIC, $email = false, $bodyFormat = false)
 {
     $message = Mage::getModel('helpdesk/message')->setTicketId($this->getId())->setType($messageType)->setBody($text)->setBodyFormat($bodyFormat)->setTriggeredBy($triggeredBy);
     if ($triggeredBy == Mirasvit_Helpdesk_Model_Config::CUSTOMER) {
         $message->setCustomerId($customer->getId());
         $message->setCustomerName($customer->getName());
         $message->setCustomerEmail($customer->getEmail());
         $message->setIsRead(true);
         $this->setLastReplyName($customer->getName());
     } elseif ($triggeredBy == Mirasvit_Helpdesk_Model_Config::USER) {
         $message->setUserId($user->getId());
         if ($this->getOrigData('user_id') == $this->getData('user_id')) {
             if ($messageType != Mirasvit_Helpdesk_Model_Config::MESSAGE_INTERNAL) {
                 $this->setUserId($user->getId());
                 // In case of different departments of ticket and owner, correct department id
                 $departments = Mage::getModel('helpdesk/department')->getCollection();
                 $departments->addUserFilter($user->getId())->addFieldToFilter('is_active', true);
                 if ($departments->count()) {
                     $this->_department = null;
                     $this->setDepartmentId($departments->getFirstItem()->getId());
                 }
             }
         }
         $this->setLastReplyName($user->getName());
         if ($message->isThirdParty()) {
             $message->setThirdPartyEmail($this->getThirdPartyEmail());
         }
     } elseif ($triggeredBy == Mirasvit_Helpdesk_Model_Config::THIRD) {
         $message->setThirdPartyEmail($this->getThirdPartyEmail());
         if ($email) {
             $this->setLastReplyName($email->getSenderNameOrEmail());
             $message->setThirdPartyName($email->getSenderName());
         }
     }
     if ($email) {
         $message->setEmailId($email->getId());
     }
     //если тикет был закрыт, затем поступило сообщение от пользователя - мы его открываем
     if ($triggeredBy != Mirasvit_Helpdesk_Model_Config::USER) {
         if ($this->isClosed()) {
             $status = Mage::getModel('helpdesk/status')->loadByCode(Mirasvit_Helpdesk_Model_Config::STATUS_OPEN);
             $this->setStatusId($status->getId());
         }
         $this->setIsArchived(false);
     }
     $message->save();
     if ($email) {
         $email->setIsProcessed(true)->setAttachmentMessageId($message->getId())->save();
     } else {
         Mage::helper('helpdesk')->saveAttachments($message);
     }
     if (!$this->getIsSpam()) {
         if ($this->getReplyCnt() == 0) {
             Mage::helper('helpdesk/notification')->newTicket($this, $customer, $user, $triggeredBy, $messageType);
         } else {
             Mage::helper('helpdesk/notification')->newMessage($this, $customer, $user, $triggeredBy, $messageType);
         }
     }
     $this->setReplyCnt($this->getReplyCnt() + 1);
     if (!$this->getFirstReplyAt() && $user) {
         $this->setFirstReplyAt(Mage::getSingleton('core/date')->gmtDate());
     }
     $this->setLastReplyAt(Mage::getSingleton('core/date')->gmtDate());
     $this->save();
     Mage::helper('helpdesk/history')->addMessage($this, $text, $triggeredBy, array('customer' => $customer, 'user' => $user, 'email' => $email), $messageType);
     return $message;
 }