public function indexAction()
 {
     $bootstrap = $this->getInvokeArg('bootstrap');
     $options = $bootstrap->getOptions();
     $smtp_config = $options['smtp'];
     $pop3_config = $options['pop3'];
     $mail = new Zend_Mail_Storage_Pop3($pop3_config['config']);
     echo $mail->countMessages() . " messages found\n";
     foreach ($mail as $i => $message) {
         $message = $this->parseMessage($mail, $message, $i);
         $mail->removeMessage($i);
         if (!stristr($message['message']['subject'], 'ticket #')) {
             // Add email as a ticket
             $ticketModel = new Default_Model_Ticket($message['message']);
             $ticketModel->save();
             $ticketId = $ticketModel->getMapper()->getDbTable()->getAdapter()->lastInsertId();
             $replyId = 0;
             $transport = new Zend_Mail_Transport_Smtp($smtp_config['host'], $smtp_config['config']);
             // Send a plain text email
             $sendmail = new Zend_Mail();
             $sendmail->setBodyText('Thank you for your submission. We will process you ticket shortly.');
             $sendmail->setFrom($smtp_config['email']['address'], $smtp_config['email']['name']);
             $sendmail->addTo($message['message']['fromEmail']);
             $sendmail->setSubject('Ticket #' . $ticketId);
             $sendmail->send($transport);
         } else {
             // Get ticket it from subject
             $ticketId = explode('ticket #', strtolower($message['message']['subject']));
             $ticketId = explode(' ', $ticketId[1]);
             $ticketId = array_shift($ticketId);
             $message['message']['ticketId'] = $ticketId;
             // Add email as a reply
             $replyModel = new Default_Model_TicketReply($message['message']);
             $replyModel->save();
             $replyId = $replyModel->getMapper()->getDbTable()->getAdapter()->lastInsertId();
         }
         foreach ($message['attachments'] as &$attachment) {
             if (empty($attachment['filename'])) {
                 // This is probably a text or html alternative.
                 $attachment['filename'] = stristr($attachment['contentType'], 'html') ? 'html-version.html' : 'text-version.txt';
             }
             $attachment['ticketId'] = $ticketId;
             // TODO: reply not being set?
             $attachment['replyId'] = $replyId;
             $ticketAttachmentModel = new Default_Model_TicketAttachment($attachment);
             $ticketAttachmentModel->save();
             unset($attachment);
         }
     }
 }
Example #2
0
 /**
  * CLI Bot action
  * 
  */
 public function botAction()
 {
     // Retrieve configuration
     $config = Zend_Registry::get('config');
     // URI to be called
     $uri = $config->snsServerUrlScheme . '://' . $config->snsServerUrlHost . $config->snsServerUrlPath . 'default/wikiarticle/create';
     try {
         // Connect to POP3 mail storage
         $mail = new Zend_Mail_Storage_Pop3(array('host' => $config->wikiarticle->pop3->host, 'port' => $config->wikiarticle->pop3->port, 'user' => $config->wikiarticle->pop3->user, 'password' => $config->wikiarticle->pop3->pass));
     } catch (Exception $ex) {
         //SWAT_Log::get()->MailPuller()->err($ex->getMessage());
         Zend_Registry::get('log')->err($ex->getMessage());
     }
     // Generate mail puller instance
     $puller = new SWAT_Mail_Puller();
     $puller->setFileDir(sys_get_temp_dir());
     $puller->setFileTypes(array_map('trim', explode(',', $config->wikiarticleAllowedMimeTypes)));
     //echo 'We have ' . $mail->countMessages() . ' messages to process.<br />';
     //echo 'Attachments will be stored in directory: ' . sys_get_temp_dir() . '<br />';
     // Foreach mail found
     foreach ($mail as $number => $message) {
         //echo 'Found message with title: ' . $message->subject . '<br />';
         // Check if it's a wiki article to be created
         if (strtoupper(substr($message->subject, 0, 5)) === 'WIKI:') {
             try {
                 // Retrieve message information
                 $info = $puller->getMessageInfo($message);
                 // Post found information to wiki article creator
                 $client = new Zend_Http_Client($uri);
                 $client->setRawData(Zend_Json::encode($info));
                 $response = $client->request(Zend_Http_Client::POST);
                 //echo 'Response: <pre>' . var_export($response->getBody(), true) . '</pre>';
                 // Switch to each response status
                 switch ($response->getStatus()) {
                     case 400:
                         throw new Exception('Invalid request.');
                         break;
                     case 500:
                         throw new Exception('Internal server error.');
                         break;
                     default:
                         // Decode response
                         $body = SWAT_Encoder::decode($response->getRawBody());
                         // If error code is not 201, we need to report the issue
                         if ($body['code'] != 201) {
                             throw new Exception($body['message']);
                         }
                         // Generate log entry
                         //SWAT_Log::get()->MailPuller()->debug($body['message']);
                         Zend_Registry::get('log')->debug($body['message']);
                         break;
                 }
             } catch (Exception $ex) {
                 //SWAT_Log::get()->MailPuller()->err($ex->getMessage());
                 Zend_Registry::get('log')->err($ex->getMessage());
             }
         }
         $mail->noop();
     }
 }
Example #3
0
 public function execute()
 {
     // get a logger
     $logger = Zend_Registry::get("logger");
     echo "Memory usage on startup: " . memory_get_usage() . "\r\n";
     // Access the email
     $mail = new Zend_Mail_Storage_Pop3(array('host' => 'xxxxxx', 'user' => 'xxxxxx', 'password' => 'xxxxxx', 'ssl' => 'SSL'));
     // If no new email, goodbye
     if ($mail->countMessages() == 0) {
         $log = "No new emails to process.";
         echo "{$log}\r\n";
         $logger->log($log, Zend_Log::INFO);
         exit;
     }
     $email_count = 0;
     foreach ($mail as $messageNum => $message) {
         // A bit of feedback
         $log = "Message to {$message->to}.. (mem: " . memory_get_usage() . ")...";
         echo "{$log}";
         $logger->log($log, Zend_Log::INFO);
         // Get the user, if not we continue
         if (!($user = $this->getUser($message->to))) {
             $log = "skipped.";
             echo "{$log}\r\n";
             $logger->log($log, Zend_Log::INFO);
             $mail->removeMessage($messageNum);
             continue;
         }
         // Assign the shard value
         Zend_Registry::set("shard", $user['id']);
         $this->_user = $user;
         $this->_properties = new Properties(array(Stuffpress_Db_Properties::KEY => $user['id']));
         // Get the subject
         try {
             $subject = $this->mimeWordDecode(trim($message->subject));
         } catch (Exception $e) {
             $subject = "";
         }
         // Get the content
         $foundPart = null;
         $plain_text = "";
         $html_text = "";
         $latitude = false;
         $longitude = false;
         $image = false;
         $audio = false;
         $files = new Files();
         $timestamp = time();
         foreach (new RecursiveIteratorIterator($message) as $part) {
             try {
                 $part_type = strtok($part->contentType, ';');
                 if ($part_type == 'text/plain') {
                     $charset = $this->getCharset($part->contentType);
                     $plain_text = $this->recode(trim($part->getContent()), $charset);
                 } else {
                     if ($part_type == 'text/html') {
                         $charset = $this->getCharset($part->contentType);
                         $html_text = $this->recode(trim($part->getContent()), $charset);
                     } else {
                         if (substr_compare($part_type, 'image', 0, 5) == 0) {
                             if ($details = $this->getFileDetails($part->contentType)) {
                                 if ($content = base64_decode($part->getContent())) {
                                     $file_id = $files->saveFile($content, $details['name'], $details['mime'], "Email upload");
                                     $file = $files->getFile($file_id);
                                     $key = $file->key;
                                     $files->fitWidth($file_id, 240, 'small');
                                     $files->fitWidth($file_id, 500, 'medium');
                                     $files->fitWidth($file_id, 1024, 'large');
                                     $files->fitSquare($file_id, 75, 'thumbnails');
                                     $exif = $files->readExif($file_id);
                                     // Retrieve the picture date/time
                                     if (isset($exif['DateTimeOriginal'])) {
                                         $timestamp = Stuffpress_Date::strToTimezone($exif['DateTimeOriginal'], $this->_properties->getProperty('timezone'));
                                     }
                                     // Get longitude if provided
                                     if (!empty($exif['GPSLongitude']) && count($exif['GPSLongitude']) == 3 && !empty($exif['GPSLongitudeRef'])) {
                                         $longitude = ($exif['GPSLongitudeRef'] == 'W' ? '-' : '') . Stuffpress_Exif::exif_gpsconvert($exif['GPSLongitude']);
                                     }
                                     // Get latitude
                                     if (!empty($exif['GPSLatitude']) && count($exif['GPSLatitude']) == 3 && !empty($exif['GPSLatitudeRef'])) {
                                         $latitude = ($exif['GPSLatitudeRef'] == 'S' ? '-' : '') . Stuffpress_Exif::exif_gpsconvert($exif['GPSLatitude']);
                                     }
                                     $image = $key;
                                 }
                             }
                         } else {
                             if (substr_compare($part_type, 'audio', 0, 5) == 0) {
                                 if ($details = $this->getFileDetails($part->contentType)) {
                                     if ($content = base64_decode($part->getContent())) {
                                         $file_id = $files->saveFile($content, $details['name'], $details['mime'], "Email upload");
                                         $file = $files->getFile($file_id);
                                         $audio = $file->key;
                                     }
                                 }
                             }
                         }
                     }
                 }
             } catch (Zend_Mail_Exception $e) {
                 // ignore
             }
         }
         $body = strlen($html_text) > 0 ? $html_text : $plain_text;
         // Post the content
         // 1 - a status message
         if (!$image && !$audio && strlen($subject) == 0) {
             $item_id = $this->postStatus($user['id'], $timestamp, $body);
         } else {
             if (!$image && !$audio) {
                 $item_id = $this->postBlog($user['id'], $timestamp, $subject, $body);
             } else {
                 if ($image) {
                     $item_id = $this->postImage($user['id'], $timestamp, $subject, $body, $image);
                 } else {
                     if ($audio) {
                         $item_id = $this->postAudio($user['id'], $timestamp, $subject, $body, $audio);
                     } else {
                         echo "Unsupported fotmat\r\n";
                     }
                 }
             }
         }
         // Set the location of the item if provided
         if ($latitude && $longitude) {
             $source = StuffpressModel::forUser($this->_user->id);
             $source_id = $source->getID();
             $data = new Data();
             $data->setLocation($source_id, $item_id, $latitude, $longitude, 0);
         }
         $email_count++;
         // Delete the email
         $mail->removeMessage($messageNum);
         echo "processed.\r\n";
         $logger->log("Message delivered to {$user['username']}.", Zend_Log::INFO);
         // Clean up before the loop
         unset($content);
     }
     $logger->log("Processed {$email_count} emails. (max mem: " . memory_get_peak_usage() . ").", Zend_Log::INFO);
 }
Example #4
0
 public function testDotMessage()
 {
     $mail = new Zend_Mail_Storage_Pop3($this->_params);
     $content = '';
     $content .= "Before the dot\r\n";
     $content .= ".\r\n";
     $content .= "is after the dot\r\n";
     $this->assertEquals($mail->getMessage(7)->getContent(), $content);
 }
Example #5
0
	public function getPendingMessages() {
		$messages = array();
		// connect to the server to grab all messages 
		Loader::library('3rdparty/Zend/Mail/Storage/Pop3');

		$args = array('host' => $this->miServer, 'user' => $this->miUsername, 'password' => $this->miPassword);
		if ($this->miEncryption != '') {
			$args['ssl'] = $this->miEncryption;
		}
		if ($this->miPort > 0) {
			$args['port'] = $this->miPort;
		}
		
		$mail = new Zend_Mail_Storage_Pop3($args);
		for ($i = 1; $i <= $mail->countMessages(); $i++) {
			$mim = new MailImportedMessage($mail, $mail->getMessage($i), $i);
			$messages[] = $mim;
		}
		return $messages;
	}
Example #6
0
 public function testRequestAfterClose()
 {
     $mail = new Zend_Mail_Storage_Pop3($this->_params);
     $mail->close();
     try {
         $mail->getMessage(1);
     } catch (Exception $e) {
         return;
         // test ok
     }
     $this->fail('no exception raised while requesting after closing connection');
 }
Example #7
0
<?php

// include('config.php');
// include('includes.php');
SqlBeginTransaction();
Zoop::loadLib('zend');
$mailConfig = Config::get('app.importer');
$mail = new Zend_Mail_Storage_Pop3(array('host' => $mailConfig['host'], 'user' => $mailConfig['username'], 'password' => $mailConfig['password'], 'ssl' => $mailConfig['ssl'] ? 'SSL' : ''));
// $mail = new Zend_Mail_Storage_Imap(array('host'     => $mailConfig['host'],
//                                          'user'     => $mailConfig['username'],
//                                          'password' => $mailConfig['password'],
//                                          'ssl'      => $mailConfig['ssl'] ? 'SSL' : ''));
// var_dump($mail);
var_dump($count = $mail->countMessages());
foreach ($mail as $message) {
    //	spit out a little info about the message being processed
    echo "{$message->from}: {$message->to}: {$message->subject}\n";
    //	see if the from field is like "John Doe <*****@*****.**>"
    //	and if it is parse out the individual fields
    preg_match('/([\\w ]*)<(\\w.+)@([\\w.]+)>/', $message->from, $matches);
    if (count($matches) == 4) {
        $name = trim($matches[1]);
        $parts = explode(' ', $name);
        $firstname = array_shift($parts);
        $lastname = array_pop($parts);
        $user = trim($matches[2]);
        $domain = trim($matches[3]);
        $username = $email = "{$user}@{$domain}";
    } else {
        die("unhandled address format in the 'From' field\n\n");
    }
Example #8
0
 public function testRemove()
 {
     $mail = new Zend_Mail_Storage_Pop3($this->_params);
     $count = $mail->countMessages();
     $mail->removeMessage(1);
     $this->assertEquals($mail->countMessages(), --$count);
     unset($mail[2]);
     $this->assertEquals($mail->countMessages(), --$count);
 }
Example #9
0
 public function testWrongUniqueId()
 {
     $mail = new Zend_Mail_Storage_Pop3($this->_params);
     try {
         $mail->getNumberByUniqueId('this_is_an_invalid_id');
     } catch (Exception $e) {
         return;
         // test ok
     }
     $this->fail('no exception while getting number for invalid id');
 }