NotifySend.php
[Pman.Core] / NotifySend.php
1 <?php
2 require_once 'Pman.php';
3
4 /**
5  * notification script sender - designed to be run by the Notify script - with many children running
6  * in parallel.
7  *
8  * called with an id of a core_notify element
9  *
10  * uses core_notify - to find an event to object and person.
11  *
12  * uses Events table to log failures
13  * 
14  * 
15  * calls $object->toEmail($person,$last_send, $notify) to generate an email struct with
16  *  array (
17  *      headers =>
18  *      recipients =>
19  *      body =>
20  *  )
21  * 
22  * 
23  */
24
25
26 class Pman_Core_NotifySend extends Pman
27 {
28     static $cli_desc = "Send out single notification email (usually called from  Core/Notify)";
29     
30     static $cli_opts = array(
31         'debug' => array(
32             'desc' => 'Turn on debugging (see DataObjects debugLevel )',
33             'default' => 0,
34             'short' => 'v',
35             'min' => 0,
36             'max' => 0,
37             
38         ),
39         'DB_DataObject-debug' => array(
40             'desc' => 'Turn on debugging (see DataObjects debugLevel )',
41             'default' => 0,
42             'short' => 'd',
43             'min' => 1,
44             'max' => 1,
45             
46         ),
47         'force' => array(
48             'desc' => 'Force redelivery, even if it has been sent before or not queued...',
49             'default' => 0,
50             'short' => 'f',
51             'min' => 0,
52             'max' => 0,
53         ),
54         'send-to' => array(
55             'desc' => 'Send the message to this address, rather than the one listed.',
56             'default' => '',
57             'short' => 't',
58             'min' => 0,
59             'max' => 1,
60         )
61         
62         
63         
64     );
65     var $table = 'core_notify';
66     function getAuth()
67     {
68         $ff = HTML_FlexyFramework::get();
69         if (!$ff->cli) {
70             die("access denied");
71         }
72         //HTML_FlexyFramework::ensureSingle(__FILE__, $this);
73         return true;
74         
75     }
76    
77     function get($id,$opts)
78     {
79         if ($opts['DB_DataObject-debug']) {
80             DB_DataObject::debugLevel($opts['DB_DataObject-debug']);
81         }
82         //DB_DataObject::debugLevel(1);
83         //date_default_timezone_set('UTC');
84         // phpinfo();exit;
85         $force = empty($opts['force']) ? 0 : 1;
86         
87         $w = DB_DataObject::factory($this->table);
88         
89         if (!$w->get($id)) {
90             die("invalid id\n");
91         }
92         if (!$force && strtotime($w->act_when) < strtotime($w->sent)) {
93             
94             
95             die("send repeat to early\n");
96         }
97         if (!empty($opts['debug'])) {
98             print_r($w);
99         }
100         
101         $sent = (empty($w->sent) || preg_match('/^0000/', $w->sent)) ? false : true;
102         
103         if (!$force && (!empty($w->msgid) || $sent)) {
104             $ww = clone($w);
105             if (!$sent) { 
106                 $w->sent = $w->sqlValue("NOW()");
107                 $w->update($ww);
108             }    
109             die("message has been sent already.\n");
110         }
111         
112         $o = $w->object();
113         
114         if ($o === false)  {
115             
116             $ev = $this->addEvent('NOTIFY', $w,
117                             "Notification event cleared (underlying object does not exist)" );;
118             $ww = clone($w);
119             $w->sent = date('Y-m-d H:i:s');
120             $w->msgid = '';
121             $w->event_id = $ev->id;
122             $w->update($ww);
123             die(date('Y-m-d h:i:s ') . 
124                      "Notification event cleared (underlying object does not exist)" 
125                     ."\n");
126         }
127      
128         
129         
130         $p = $w->person();
131         
132         if (isset($p->active) && empty($p->active)) {
133             $ev = $this->addEvent('NOTIFY', $w,
134                             "Notification event cleared (not user not active any more)" );;
135             $ww = clone($w);
136             $w->sent = date('Y-m-d H:i:s');
137             $w->msgid = '';
138             $w->event_id = $ev->id;
139             $w->update($ww);
140             die(date('Y-m-d h:i:s ') . 
141                      "Notification event cleared (not user not active any more)" 
142                     ."\n");
143             die("message has been sent already.\n");
144         }
145         
146         
147         // let's work out the last notification sent to this user..
148         $l = DB_DataObject::factory($this->table);
149         $l->setFrom( array(
150                 'ontable' => $w->ontable,
151                 'onid' => $w->onid,
152                 'person_id' => $w->person_id,
153         ));        
154         $l->whereAdd('id != '. $w->id);
155         $l->orderBy('sent DESC');
156         $l->limit(1);
157         $ar = $l->fetchAll('sent');
158         $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
159         
160         // find last event..
161         $ev = DB_DataObject::factory('Events');
162         $ev->on_id = $w->id;                           // int(11)
163         $ev->on_table = $this->table;
164         $ev->limit(1);
165         $ev->orderBy('event_when DESC');
166         $ar = $ev->fetchAll('event_when');
167         $last_event = empty($ar) ? 0 : $ar[0];
168         $next_try_min = 5;
169         if ($last_event) {
170             $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
171         }
172         $next_try = $next_try_min . ' MINUTES';
173          
174         // this may modify $p->email. (it will not update it though)
175         $email =  $this->makeEmail($o, $p, $last, $w, $force);
176         exit;
177         
178         if ($email === true)  {
179             
180             $ev = $this->addEvent('NOTIFY', $w,
181                             "Notification event cleared (not required any more)" );;
182             $ww = clone($w);
183             $w->sent = date('Y-m-d H:i:s');
184             $w->msgid = '';
185             $w->event_id = $ev->id;
186             $w->update($ww);
187             die(date('Y-m-d h:i:s ') . 
188                      "Notification event cleared (not required any more)" 
189                     ."\n");
190         }
191      
192        
193         
194         if ($email === false || isset($email['error'])) {
195             // object returned 'false' - it does not know how to send it..
196             $ev = $this->addEvent('NOTIFY', $w, isset($email['error'])  ?
197                             $email['error'] : "INTERNAL ERROR  - We can not handle " . $w->ontable); 
198             $ww = clone($w);
199             $w->sent = date('Y-m-d H:i:s');
200             $w->msgid = '';
201             $w->event_id = $ev->id;
202             $w->update($ww);
203             die(date('Y-m-d h:i:s ') . 
204                     (isset($email['error'])  ?
205                             $email['error'] : "INTERNAL ERROR  - We can not handle " . $w->ontable)
206                     ."\n");
207         }
208         
209         
210         if (isset($email['later'])) {
211             $old = clone($w);
212             $w->act_when = $email['later'];
213             $w->update($old);
214             die(date('Y-m-d h:i:s ') . " Delivery postponed by email creator");
215         }
216         
217          
218         if (empty($email['headers']['Message-Id'])) {
219             $HOST = gethostname();
220             $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
221             
222         }
223         //$p->email = 'alan@akbkhome.com'; //for testing..
224         //print_r($email);exit;
225         // should we fetch the watch that caused it.. - which should contain the method to call..
226         // --send-to=test@xxx.com
227        
228         if (!empty($email['send-to'])) {
229             $p->email = $email['send-to'];
230         }
231          if (!empty($opts['send-to'])) {
232             $p->email = $opts['send-to'];
233         }
234         // since some of them have spaces?!?!
235         $p->email = trim($p->email);
236         
237         
238         require_once 'Validate.php';
239         if (!Validate::email($p->email, true)) {
240             $ev = $this->addEvent('NOTIFY', $w, "INVALID ADDRESS: " . $p->email);
241             $ww = clone($w);
242             $w->sent = date('Y-m-d H:i:s');
243             $w->msgid = '';
244             $w->event_id = $ev->id;
245             $w->update($ww);
246             die(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
247             
248         }
249         
250         
251         $ff = HTML_FlexyFramework::get();
252         
253         
254         $dom = array_pop(explode('@', $p->email));
255         
256         $mxs = $this->mxs($dom);
257         $ww = clone($w);
258
259         // we might fail doing this...
260         // need to handle temporary failure..
261        
262         
263           // we try for 3 days..
264         $retry = 5;
265         if (strtotime($w->act_start) <  strtotime('NOW - 1 HOUR')) {
266             // older that 1 hour.
267             $retry = 15;
268         }
269         
270         if (strtotime($w->act_start) <  strtotime('NOW - 1 DAY')) {
271             // older that 1 day.
272             $retry = 60;
273         }
274         if (strtotime($w->act_start) <  strtotime('NOW - 2 DAY')) {
275             // older that 1 day.
276             $retry = 120;
277         }
278         
279         if ($mxs === false) {
280             // only retry for 2 day son the MX issue..
281             if ($retry < 120) {
282                 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom . ' ' . $res->toString());
283                 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
284                 $w->update($ww);
285                 die(date('Y-m-d h:i:s') . " - GREYLISTED\n");
286             }
287             
288             $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
289             $w->sent = date('Y-m-d H:i:s');
290             $w->msgid = '';
291             $w->event_id = $ev->id;
292             $w->update($ww);
293             die(date('Y-m-d h:i:s') . " - FAILED -  BAD EMAIL - {$p->email} \n");
294             
295             
296         }
297         
298         
299         
300         
301         if (!$force && strtotime($w->act_start) <  strtotime('NOW - 14 DAY')) {
302             $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
303             $w->sent = date('Y-m-d H:i:s');
304             $w->msgid = '';
305             $w->event_id = $ev->id;
306             $w->update($ww);
307             die(date('Y-m-d h:i:s') . " - FAILED -  GAVE UP TO OLD - {$p->email} \n");
308         }
309         
310         
311         
312         $w->to_email = $p->email; 
313         //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
314         $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
315         $w->update($ww);
316         
317         $ww = clone($w);   
318         
319         $fail = false;
320         require_once 'Mail.php';
321         
322         foreach($mxs as $dom) {
323             
324             
325             
326             if (!isset($ff->Mail['helo'])) {
327                 die("config Mail[helo] is not set");
328             }
329             
330             $this->debug("Trying SMTP: $dom / HELO {$ff->Mail['helo']}");
331             $mailer = Mail::factory('smtp', array(
332                     'host'    => $dom ,
333                     'localhost' => $ff->Mail['helo'],
334                     'timeout' => 15,
335                     'socket_options' =>  isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null
336                   //  'debug' => true
337                 ));
338             $res = $mailer->send($p->email, $email['headers'], $email['body']);
339              
340             
341             if ($res === true) {
342                 // success....
343                 
344                 $ev = $this->addEvent('NOTIFYSENT', $w, "{$w->to_email} - {$email['headers']['Subject']}");
345                
346                 
347                 
348                 $w->sent = date('Y-m-d H:i:s');
349                 $w->msgid = $email['headers']['Message-Id'];
350                 $w->event_id = $ev->id; // sent ok.. - no need to record it..
351                 $w->update($ww);
352                 
353                 // enable cc in notify..
354                 if (!empty($email['headers']['Cc'])) {
355                     $mailer = Mail::factory('smtp', array(
356                        //'host'    => $dom ,
357                       //  'debug' => true
358                     ));
359                     $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
360                     $mailer->send($email['headers']['Cc'],
361                                   $email['headers'], $email['body']);
362                     
363                 }
364                 
365                 if (!empty($email['bcc'])) {
366                     $mailer = Mail::factory('smtp', array(
367                        //'host'    => $dom ,
368                       //  'debug' => true
369                     ));
370                     $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
371                     $mailer->send($email['bcc'],
372                                   $email['headers'], $email['body']);
373                     
374                 }
375                 
376                 
377                 die(date('Y-m-d h:i:s') . " - SENT\n");
378             }
379             // what type of error..
380             $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
381             if (!empty($res->code) && $res->code == 10001) {
382                 // fake greylist if timed out.
383                 $code = 421;
384             }
385             
386             if ($code < 0) {
387                 $this->debug($res->message);
388                 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
389             }
390             // give up after 2 days..
391             if (in_array($code, array( 421, 450, 451, 452))   && $next_try_min < (2*24*60)) {
392                 // try again later..
393                 // check last event for this item..
394                 $errmsg=  $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) :  " - UNKNOWN ERROR";
395                 if (isset($res->userinfo['smtptext'])) {
396                     $errmsg=  $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
397                 }
398                 //print_r($res);
399                 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
400                 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
401                 $w->update($ww);
402                 die(date('Y-m-d h:i:s') . " - GREYLISTED\n");
403             }
404             $fail = true;
405             break;
406         }
407         if ($fail || $next_try_min > (2*24*60)) {
408         // fail.. = log and give up..
409             $errmsg=  $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) :  " - UNKNOWN ERROR";
410             if (isset($res->userinfo['smtptext'])) {
411                 $errmsg=  $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
412             }
413             
414             $ev = $this->addEvent('NOTIFY', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
415                        $errmsg);
416             $w->sent = date('Y-m-d H:i:s');
417             $w->msgid = '';
418             $w->event_id = $ev->id;
419             $w->update($ww);
420             die(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
421         }
422         
423         // handle no host availalbe forever...
424         if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
425             $ev = $this->addEvent('NOTIFY', $w, "RETRY TIME EXCEEDED - ". $p->email);
426             $w->sent = date('Y-m-d H:i:s');
427             $w->msgid = '';
428             $w->event_id = $ev->id;
429             $w->update($ww);
430             die(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
431             
432             
433         }
434         
435         
436         $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
437         $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
438         $w->update($ww);
439         die(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
440
441         
442     }
443     function mxs($fqdn)
444     {
445         $mx_records = array();
446         $mx_weight = array();
447         $mxs = array();
448         if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
449             if (!checkdnsrr($fqdn)) {
450                 return false;
451             }
452             return array($fqdn);
453         }
454         
455         asort($mx_weight,SORT_NUMERIC);
456         
457         foreach($mx_weight as $k => $weight) {
458             $mxs[] = $mx_records[$k];
459         }
460         return $mxs;
461     }
462     
463     /**
464      * wrapper to call object->toEmail()
465      *
466      * return
467      *   {
468         headers : {AssocArray},
469         body: {String}
470         
471         // optional..
472         error :  {String} // error message in log.
473         send-to: {String} // use to override rcpt
474          
475      }
476      **/
477     function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
478     {
479         $m = 'notify'. $notify->evtype;
480         //var_dump(get_class($object) . '::' .$m);
481         
482         if (!empty($notify->evtype) && method_exists($object,$m)) {
483             echo "calling :" . get_class($object) . '::' .$m . "\n";
484             return $object->$m($rcpt, $last_sent_date, $notify, $force);
485         }
486         
487         if(!empty($notify->evtype) && $notify->evtype == 'campaign_detail::drawWinner'){
488             echo "calling :" . $notify->evtype . "\n";
489             return $object->drawWinner($rcpt, $last_sent_date, $notify, $force);
490         }
491                 
492         if (!method_exists($object, 'toEmail')) {
493             //var_Dump($object);
494             //exit;
495         }
496         
497         return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
498     }
499     
500     function debug($str)
501     {
502         if (empty($this->cli_args['debug'])) {
503             return;
504             
505         }
506         echo $str . "\n";
507     }
508     function output()
509     {
510         die("done\n");
511     }
512 }