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