DataObjects/Core_notify_server.php
[Pman.Core] / NotifySend.php
index 8bcb973..07c1e9f 100644 (file)
@@ -26,6 +26,8 @@ require_once 'Pman.php';
  * Mail[helo] << helo host name
  * Mail[socket_options] << any socket option.
  */
+class Pman_Core_NotifySend_Exception_Success extends Exception {}
+class Pman_Core_NotifySend_Exception_Fail extends Exception {}
 
 
 class Pman_Core_NotifySend extends Pman
@@ -81,9 +83,9 @@ class Pman_Core_NotifySend extends Pman
         
     }
    
-    function get($id,$opts)
+    function get($id,$opts=array())
     {
-        
+
         //print_r($opts);
         if (!empty($opts['DB_DataObject-debug'])) {
             DB_DataObject::debugLevel($opts['DB_DataObject-debug']);
@@ -95,14 +97,14 @@ class Pman_Core_NotifySend extends Pman
         $force = empty($opts['force']) ? 0 : 1;
         
         $w = DB_DataObject::factory($this->table);
-        
+
         if (!$w->get($id)) {
             $this->errorHandler("invalid id\n");
         }
-        if (!$force && strtotime($w->act_when) < strtotime($w->sent)) {
-            
-            
-            $this->errorHandler("send repeat to early\n");
+
+        if (!$force && !empty($w->sent) && strtotime($w->act_when) < strtotime($w->sent)) {
+             
+            $this->errorHandler("already sent - repeat to early\n");
         }
         if (!empty($opts['debug'])) {
             print_r($w);
@@ -118,7 +120,7 @@ class Pman_Core_NotifySend extends Pman
         if (!$force && (!empty($w->msgid) || $sent)) {
             $ww = clone($w);
             if (!$sent) { 
-                $w->sent = $w->sqlValue("NOW()");
+                $w->sent = $w->sent == '0000-00-00 00:00:00' ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
                 $w->update($ww);
             }    
             $this->errorHandler("message has been sent already.\n");
@@ -131,7 +133,7 @@ class Pman_Core_NotifySend extends Pman
             $ev = $this->addEvent('NOTIFY', $w,
                             "Notification event cleared (underlying object does not exist)" );;
             $ww = clone($w);
-            $w->sent = date('Y-m-d H:i:s');
+            $w->sent = $w->sent == '0000-00-00 00:00:00' ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
             $w->msgid = '';
             $w->event_id = $ev->id;
             $w->update($ww);
@@ -148,7 +150,7 @@ class Pman_Core_NotifySend extends Pman
             $ev = $this->addEvent('NOTIFY', $w,
                             "Notification event cleared (not user not active any more)" );;
             $ww = clone($w);
-            $w->sent = date('Y-m-d H:i:s');
+            $w->sent = $w->sent == '0000-00-00 00:00:00' ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
             $w->msgid = '';
             $w->event_id = $ev->id;
             $w->update($ww);
@@ -157,7 +159,21 @@ class Pman_Core_NotifySend extends Pman
                     ."\n");
             $this->errorHandler("message has been sent already.\n");
         }
+        // has it failed mutliple times..
         
+        if (!empty($w->field) && isset($p->{$w->field .'_fails'}) && $p->{$w->field .'_fails'} > 9) {
+            $ev = $this->addEvent('NOTIFY', $w,
+                            "Notification event cleared (user has to many failures)" );;
+            $ww = clone($w);
+            $w->sent = $w->sqlValue('NOW()'); // do not update if sent.....
+            $w->msgid = '';
+            $w->event_id = $ev->id;
+            $w->update($ww);
+            $this->errorHandler(date('Y-m-d h:i:s ') . 
+                     "Notification event cleared (user has to many failures)" 
+                    ."\n");
+            $this->errorHandler("user has to many failures.\n");
+        }
         
         // let's work out the last notification sent to this user..
         $l = DB_DataObject::factory($this->table);
@@ -167,9 +183,11 @@ class Pman_Core_NotifySend extends Pman
                 'onid' => $w->onid,
         );
         // only newer version of the database us this..
-        $personid_col = strtolower($w->person_table).'_id';
-        if (isset($w->{$personid_col})) {
-            $lar[$personid_col] = $w->{$personid_col};
+        if (isset($w->person_table)) {
+            $personid_col = strtolower($w->person_table).'_id';
+            if (isset($w->{$personid_col})) {
+                $lar[$personid_col] = $w->{$personid_col};
+            }
         }
         
         
@@ -202,7 +220,7 @@ class Pman_Core_NotifySend extends Pman
             $ev = $this->addEvent('NOTIFY', $w,
                             "Notification event cleared (not required any more)" );;
             $ww = clone($w);
-            $w->sent = date('Y-m-d H:i:s');
+            $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
             $w->msgid = '';
             $w->event_id = $ev->id;
             $w->update($ww);
@@ -210,24 +228,28 @@ class Pman_Core_NotifySend extends Pman
                      "Notification event cleared (not required any more)" 
                     ."\n");
         }
+        if (is_a($email, 'PEAR_Error')) {
+            $email =array(
+                'error' => $email->toString()
+            );
+        }
         
-        if (empty($p) && !empty($email['rcpts'])) {
+        if (empty($p) && !empty($email['recipients'])) {
             // make a fake person..
             $p = (object) array(
-                'email' => $email['rcpts']
+                'email' => $email['recipients']
             );
         }
-        print_R($email);exit;
-        
-        
+         
         if ($email === false || isset($email['error']) || empty($p)) {
             // object returned 'false' - it does not know how to send it..
-            $ev = $this->addEvent('NOTIFY', $w, isset($email['error'])  ?
+            $ev = $this->addEvent('NOTIFYFAIL', $w, isset($email['error'])  ?
                             $email['error'] : "INTERNAL ERROR  - We can not handle " . $w->ontable); 
             $ww = clone($w);
-            $w->sent = date('Y-m-d H:i:s');
+            $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
             $w->msgid = '';
             $w->event_id = $ev->id;
+            $w->to_email = $p->email; 
             $w->update($ww);
             $this->errorHandler(date('Y-m-d h:i:s ') . 
                     (isset($email['error'])  ?
@@ -239,6 +261,7 @@ class Pman_Core_NotifySend extends Pman
         if (isset($email['later'])) {
             $old = clone($w);
             $w->act_when = $email['later'];
+            $this->updateServer($w);
             $w->update($old);
             $this->errorHandler(date('Y-m-d h:i:s ') . " Delivery postponed by email creator to {$email['later']}");
         }
@@ -271,11 +294,12 @@ class Pman_Core_NotifySend extends Pman
         
         require_once 'Validate.php';
         if (!Validate::email($p->email, true)) {
-            $ev = $this->addEvent('NOTIFY', $w, "INVALID ADDRESS: " . $p->email);
+            $ev = $this->addEvent('NOTIFYFAIL', $w, "INVALID ADDRESS: " . $p->email);
             $ww = clone($w);
-            $w->sent = date('Y-m-d H:i:s');
+            $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
             $w->msgid = '';
             $w->event_id = $ev->id;
+            $w->to_email = $p->email; 
             $w->update($ww);
             $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
             
@@ -284,8 +308,8 @@ class Pman_Core_NotifySend extends Pman
         
         $ff = HTML_FlexyFramework::get();
         
-        
-        $dom = array_pop(explode('@', $p->email));
+        $explode_email = explode('@', $p->email);
+        $dom = array_pop($explode_email);
         
         $mxs = $this->mxs($dom);
         $ww = clone($w);
@@ -294,37 +318,39 @@ class Pman_Core_NotifySend extends Pman
         // need to handle temporary failure..
        
         
-          // we try for 3 days..
-        $retry = 5;
+          // we try for 2 days..
+        $retry = 15;
         if (strtotime($w->act_start) <  strtotime('NOW - 1 HOUR')) {
             // older that 1 hour.
-            $retry = 15;
+            $retry = 60;
         }
         
         if (strtotime($w->act_start) <  strtotime('NOW - 1 DAY')) {
             // older that 1 day.
-            $retry = 60;
+            $retry = 120;
         }
         if (strtotime($w->act_start) <  strtotime('NOW - 2 DAY')) {
             // older that 1 day.
-            $retry = 120;
+            $retry = 240;
         }
         
-        if ($mxs === false) {
-            // only retry for 2 day son the MX issue..
-            if ($retry < 120) {
+        if (empty($mxs)) {
+            // only retry for 1 day if the MX issue..
+            if ($retry < 240) {
                 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
                 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
+                $this->updateServer($w);
                 $w->update($ww);
-                $this->errorHandler(date('Y-m-d h:i:s') . " - MX LOOKUP FAILED\n");
+                $this->errorHandler(date('Y-m-d h:i:s') . " - MX LOOKUP FAILED {$dom}\n");
             }
             
-            $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
-            $w->sent = date('Y-m-d H:i:s');
+            $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
+            $w->sent =   $w->sqlValue('NOW()'); // why not updated - used to leave as is?
             $w->msgid = '';
             $w->event_id = $ev->id;
+            $w->to_email = $p->email; 
             $w->update($ww);
-            $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED -  BAD EMAIL - {$p->email} \n");
+            $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED -  BAD DOMAIN - {$p->email} \n");
             
             
         }
@@ -332,11 +358,12 @@ class Pman_Core_NotifySend extends Pman
         
         
         
-        if (!$force && strtotime($w->act_start) <  strtotime('NOW - 14 DAY')) {
-            $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
-            $w->sent = date('Y-m-d H:i:s');
+        if (!$force && strtotime($w->act_start) <  strtotime('NOW - 3 DAY')) {
+            $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
+            $w->sent =  $w->sqlValue('NOW()'); 
             $w->msgid = '';
             $w->event_id = $ev->id;
+            $w->to_email = $p->email; 
             $w->update($ww);
             $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED -  GAVE UP TO OLD - {$p->email} \n");
         }
@@ -345,7 +372,10 @@ class Pman_Core_NotifySend extends Pman
         
         $w->to_email = $p->email; 
         //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
-        $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
+        // we can only update act_when if it has not been sent already (only happens when running in force mode..)
+        // set act when if it's empty...
+        $w->act_when =  (!$w->act_when || $w->act_when == '0000-00-00 00:00:00') ? date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES')) : $w->act_when;
+        
         $w->update($ww);
         
         $ww = clone($w);   
@@ -353,46 +383,121 @@ class Pman_Core_NotifySend extends Pman
         $fail = false;
         require_once 'Mail.php';
         
-        foreach($mxs as $dom) {
-            
-            
+        $core_domain = DB_DataObject::factory('core_domain');
+        if(!$core_domain->get('domain', $dom)){
+            $core_domain = DB_DataObject::factory('core_domain');
+            $core_domain->setFrom(array(
+                'domain' => $dom
+            ));
+            $core_domain->insert();
+        }
+         
+        
+        $this->initHelo();
+        
+        if (!isset($ff->Mail['helo'])) {
+            $this->errorHandler("config Mail[helo] is not set");
+        }
+        
+        
+                        
+        foreach($mxs as $mx) {
             
-            if (!isset($ff->Mail['helo'])) {
-                $this->errorHandler("config Mail[helo] is not set");
-            }
+           
             $this->debug_str = '';
-            $this->debug("Trying SMTP: $dom / HELO {$ff->Mail['helo']}");
+            $this->debug("Trying SMTP: $mx / HELO {$ff->Mail['helo']}");
             $mailer = Mail::factory('smtp', array(
-                    'host'    => $dom ,
+                    'host'    => $mx ,
                     'localhost' => $ff->Mail['helo'],
                     'timeout' => 15,
                     'socket_options' =>  isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
                     //'debug' => isset($opts['debug']) ?  1 : 0,
                     'debug' => 1,
                     'debug_handler' => array($this, 'debugHandler')
-                ));
+            ));
             
             // if the host is the mail host + it's authenticated add auth details
             // this normally will happen if you sent  Pman_Core_NotifySend['host']
-            if (isset($ff->Mail['host']) && $ff->Mail['host'] == $dom && !empty($ff->Mail['auth'] )) {
+             
+            
+            if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
+                
                 $mailer->auth = true;
-                $mailer->username = $ff->Mail['username'] ;
-                $mailer->password = $ff->Mail['password'] ;        
+                $mailer->username = $ff->Mail['username'];
+                $mailer->password = $ff->Mail['password'];        
             }
             
+            if(!empty($ff->Core_Notify) && !empty($ff->Core_Notify['routes'])){
+                
+                // we might want to regex 'office365 as a mx host 
+                foreach ($ff->Core_Notify['routes'] as $server => $settings){
+                    if(!in_array($dom, $settings['domains'])){
+                        continue;
+                    }
+                    
+                    // what's the minimum timespan.. - if we have 60/hour.. that's 1 every minute.
+                    // if it's newer that '1' minute...
+                    // then shunt it..
+                    
+                    $settings['rate'] = isset( $settings['rate']) ?  $settings['rate']  : 360;
+                    
+                    $seconds = floor((60 * 60) / $settings['rate']);
+                    
+                    $core_notify = DB_DataObject::factory($this->table);
+                    $core_notify->domain_id = $core_domain->id;
+                    $core_notify->whereAdd("
+                        sent >= NOW() - INTERVAL $seconds SECOND
+                    ");
+                    
+                    if($core_notify->count()){
+                        $old = clone($w);
+                        $w->act_when = date("Y-m-d H:i:s", time() + $seconds);
+                        $this->updateServer($w);
+                        $w->update($old);
+                        $this->errorHandler(date('Y-m-d h:i:s ') . " Too many emails sent by {$dom}");
+                    }
+                     
+                    
+                    
+                    $mailer->host = $server;
+                    $mailer->auth = isset($settings['auth']) ? $settings['auth'] : true;
+                    $mailer->username = $settings['username'];
+                    $mailer->password = $settings['password'];
+                    if (isset($settings['port'])) {
+                        $mailer->port = $settings['port'];
+                    }
+                    if (isset($settings['socket_options'])) {
+                        $mailer->socket_options = $settings['socket_options'];
+                        
+                    }
+                    
+                    
+                    break;
+                }
+                
+            }
+        
+            
             $res = $mailer->send($p->email, $email['headers'], $email['body']);
              
             
             if ($res === true) {
                 // success....
                 
-                $ev = $this->addEvent('NOTIFYSENT', $w, "{$w->to_email} - {$email['headers']['Subject']}");
+                $successEventName = (empty($email['successEventName'])) ? 'NOTIFYSENT' : $email['successEventName'];
+                
+                $ev = $this->addEvent($successEventName, $w, "{$w->to_email} - {$email['headers']['Subject']}");
                 
                 $ev->writeEventLog($this->debug_str);
                 
-                $w->sent = date('Y-m-d H:i:s');
+                if(strtotime($w->act_when) > strtotime("NOW")){
+                    $w->act_when = date('Y-m-d H:i:s');
+                }
+                
+                $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
                 $w->msgid = $email['headers']['Message-Id'];
                 $w->event_id = $ev->id; // sent ok.. - no need to record it..
+                $w->domain_id = $core_domain->id;
                 $w->update($ww);
                 
                 // enable cc in notify..
@@ -417,7 +522,7 @@ class Pman_Core_NotifySend extends Pman
                 }
                 
                 
-                $this->errorHandler(date('Y-m-d h:i:s') . " - SENT {$w->id} - {$w->to_email} \n");
+                $this->errorHandler(date('Y-m-d h:i:s') . " - SENT {$w->id} - {$w->to_email} \n", true);
             }
             // what type of error..
             $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
@@ -442,6 +547,8 @@ class Pman_Core_NotifySend extends Pman
                 //print_r($res);
                 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
                 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
+                $this->updateServer($w);
+                $w->domain_id = $core_domain->id;
                 $w->update($ww);
                 
                 
@@ -457,28 +564,34 @@ class Pman_Core_NotifySend extends Pman
                 $errmsg=  $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
             }
             
-            $ev = $this->addEvent('NOTIFY', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
+            $ev = $this->addEvent('NOTIFYFAIL', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
                        $errmsg);
-            $w->sent = date('Y-m-d H:i:s');
+            $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
             $w->msgid = '';
             $w->event_id = $ev->id;
+            $w->domain_id = $core_domain->id;
             $w->update($ww);
             $this->errorHandler(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
         }
         
         // handle no host availalbe forever...
         if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
-            $ev = $this->addEvent('NOTIFY', $w, "RETRY TIME EXCEEDED - ". $p->email);
-            $w->sent = date('Y-m-d H:i:s');
+            $ev = $this->addEvent('NOTIFYFAIL', $w, "RETRY TIME EXCEEDED - ". $p->email);
+            $w->sent = (!$w->sent || $w->sent == '0000-00-00 00:00:00') ? $w->sqlValue('NOW()') : $w->sent; // do not update if sent.....
             $w->msgid = '';
             $w->event_id = $ev->id;
+            $w->domain_id = $core_domain->id;
             $w->update($ww);
             $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
         }
         
         
         $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
-        $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
+        $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
+        
+        $this->updateServer($w);
+        
+        $w->domain_id = $core_domain->id;
         $w->update($ww);
         $this->errorHandler(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
 
@@ -504,9 +617,11 @@ class Pman_Core_NotifySend extends Pman
         asort($mx_weight,SORT_NUMERIC);
         
         foreach($mx_weight as $k => $weight) {
-            $mxs[] = $mx_records[$k];
+            if (!empty($mx_records[$k])) {
+                $mxs[] = $mx_records[$k];
+            }
         }
-        return $mxs;
+        return empty($mxs) ? false : $mxs;
     }
     
     /**
@@ -540,7 +655,11 @@ class Pman_Core_NotifySend extends Pman
             return $object->$m($rcpt, $last_sent_date, $notify, $force);
         }
                 
-        if (!method_exists($object, 'toEmail')) {
+        if (method_exists($object, 'toMailerData')) {
+            return $object->toMailerData(array(
+                'rcpts'=>$rcpt,
+                'person'=>$rcpt, // added as mediaoutreach used this?
+            )); //this is core_email - i think it's only used for testing...
             //var_Dump($object);
             //exit;
         }
@@ -566,16 +685,59 @@ class Pman_Core_NotifySend extends Pman
     {
         $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
         $this->debug_str .= $message;
+        //echo $message ."\n";
     }
     
-    function errorHandler($msg)
+    function errorHandler($msg, $success = false)
     {
         if($this->error_handler == 'exception'){
-            throw new Exception($msg);
+            if($success){
+                throw new Pman_Core_NotifySend_Exception_Success($msg);
+            }
+            
+            throw new Pman_Core_NotifySend_Exception_Fail($msg);
         }
         
         die($msg);
         
         
     }
+    
+    function updateServer($w)
+    {
+        $ff = HTML_FlexyFramework::get();
+         
+        if (empty($ff->Core_Notify['servers'])) {
+            return;
+        }
+        // some classes dont support server routing
+        if (!property_exists($w, 'server_id')) {
+            return;
+        }
+        // next server..
+        $w->server_id = ($w->server_id + 1) % count(array_keys($ff->Core_Notify['servers']));
+         
+    }
+    
+     function initHelo()
+    {
+        $ff = HTML_FlexyFramework::get();
+        
+        if (isset($ff->Core_Notify['servers-non-pool'])  &&
+            isset($ff->Core_Notify['servers-non-pool'][gethostname()]) &&
+            isset($ff->Core_Notify['servers-non-pool'][gethostname()]['helo']) ) {
+            $ff->Mail['helo'] = $ff->Core_Notify['servers-non-pool'][gethostname()]['helo'];
+            return;
+        }
+        
+        if (empty($ff->Core_Notify['servers'])) {
+            return;
+        }
+        if (!isset($ff->Core_Notify['servers'][gethostname()]) || !isset($ff->Core_Notify['servers'][gethostname()]['helo']) ) {
+            $this->jerr("Core_Notify['servers']['" . gethostname() . "']['helo'] not set");
+        }
+        $ff->Mail['helo'] = $ff->Core_Notify['servers'][gethostname()]['helo'];
+        
+    }
+    
 }
\ No newline at end of file