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  * 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         
160         $lar = array(
161                 'ontable' => $w->ontable,
162                 'onid' => $w->onid,
163         );
164         $lar[strtolower($w->person_table).'_id'] = $w->{strtolower($w->person_table).'_id'};
165         
166         $l->setFrom( $lar );       
167         $l->whereAdd('id != '. $w->id);
168         $l->orderBy('sent DESC');
169         $l->limit(1);
170         $ar = $l->fetchAll('sent');
171         $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
172         
173         // find last event..
174         $ev = DB_DataObject::factory('Events');
175         $ev->on_id = $w->id;                           // int(11)
176         $ev->on_table = $this->table;
177         $ev->limit(1);
178         $ev->orderBy('event_when DESC');
179         $ar = $ev->fetchAll('event_when');
180         $last_event = empty($ar) ? 0 : $ar[0];
181         $next_try_min = 5;
182         if ($last_event) {
183             $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
184         }
185         $next_try = $next_try_min . ' MINUTES';
186          
187         // this may modify $p->email. (it will not update it though)
188         $email =  $this->makeEmail($o, $p, $last, $w, $force);
189         
190         if ($email === true)  {
191             
192             $ev = $this->addEvent('NOTIFY', $w,
193                             "Notification event cleared (not required any more)" );;
194             $ww = clone($w);
195             $w->sent = date('Y-m-d H:i:s');
196             $w->msgid = '';
197             $w->event_id = $ev->id;
198             $w->update($ww);
199             $this->errorHandler(date('Y-m-d h:i:s ') . 
200                      "Notification event cleared (not required any more)" 
201                     ."\n");
202         }
203      
204        
205         
206         if ($email === false || isset($email['error'])) {
207             // object returned 'false' - it does not know how to send it..
208             $ev = $this->addEvent('NOTIFY', $w, isset($email['error'])  ?
209                             $email['error'] : "INTERNAL ERROR  - We can not handle " . $w->ontable); 
210             $ww = clone($w);
211             $w->sent = date('Y-m-d H:i:s');
212             $w->msgid = '';
213             $w->event_id = $ev->id;
214             $w->update($ww);
215             $this->errorHandler(date('Y-m-d h:i:s ') . 
216                     (isset($email['error'])  ?
217                             $email['error'] : "INTERNAL ERROR  - We can not handle " . $w->ontable)
218                     ."\n");
219         }
220         
221         
222         if (isset($email['later'])) {
223             $old = clone($w);
224             $w->act_when = $email['later'];
225             $w->update($old);
226             $this->errorHandler(date('Y-m-d h:i:s ') . " Delivery postponed by email creator");
227         }
228         
229          
230         if (empty($email['headers']['Message-Id'])) {
231             $HOST = gethostname();
232             $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
233             
234         }
235         //$p->email = 'alan@akbkhome.com'; //for testing..
236         //print_r($email);exit;
237         // should we fetch the watch that caused it.. - which should contain the method to call..
238         // --send-to=test@xxx.com
239        
240         if (!empty($email['send-to'])) {
241             $p->email = $email['send-to'];
242         }
243          if (!empty($opts['send-to'])) {
244             $p->email = $opts['send-to'];
245         }
246         // since some of them have spaces?!?!
247         $p->email = trim($p->email);
248         
249         require_once 'Validate.php';
250         if (!Validate::email($p->email, true)) {
251             $ev = $this->addEvent('NOTIFY', $w, "INVALID ADDRESS: " . $p->email);
252             $ww = clone($w);
253             $w->sent = date('Y-m-d H:i:s');
254             $w->msgid = '';
255             $w->event_id = $ev->id;
256             $w->update($ww);
257             $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
258             
259         }
260         
261         
262         $ff = HTML_FlexyFramework::get();
263         
264         
265         $dom = array_pop(explode('@', $p->email));
266         
267         $mxs = $this->mxs($dom);
268         $ww = clone($w);
269
270         // we might fail doing this...
271         // need to handle temporary failure..
272        
273         
274           // we try for 3 days..
275         $retry = 5;
276         if (strtotime($w->act_start) <  strtotime('NOW - 1 HOUR')) {
277             // older that 1 hour.
278             $retry = 15;
279         }
280         
281         if (strtotime($w->act_start) <  strtotime('NOW - 1 DAY')) {
282             // older that 1 day.
283             $retry = 60;
284         }
285         if (strtotime($w->act_start) <  strtotime('NOW - 2 DAY')) {
286             // older that 1 day.
287             $retry = 120;
288         }
289         
290         if ($mxs === false) {
291             // only retry for 2 day son the MX issue..
292             if ($retry < 120) {
293                 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
294                 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
295                 $w->update($ww);
296                 $this->errorHandler(date('Y-m-d h:i:s') . " - MX LOOKUP FAILED\n");
297             }
298             
299             $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
300             $w->sent = date('Y-m-d H:i:s');
301             $w->msgid = '';
302             $w->event_id = $ev->id;
303             $w->update($ww);
304             $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED -  BAD EMAIL - {$p->email} \n");
305             
306             
307         }
308         
309         
310         
311         
312         if (!$force && strtotime($w->act_start) <  strtotime('NOW - 14 DAY')) {
313             $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
314             $w->sent = date('Y-m-d H:i:s');
315             $w->msgid = '';
316             $w->event_id = $ev->id;
317             $w->update($ww);
318             $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED -  GAVE UP TO OLD - {$p->email} \n");
319         }
320         
321         
322         
323         $w->to_email = $p->email; 
324         //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
325         $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
326         $w->update($ww);
327         
328         $ww = clone($w);   
329         
330         $fail = false;
331         require_once 'Mail.php';
332         
333         foreach($mxs as $dom) {
334             
335             
336             
337             if (!isset($ff->Mail['helo'])) {
338                 $this->errorHandler("config Mail[helo] is not set");
339             }
340             $this->debug_str = '';
341             $this->debug("Trying SMTP: $dom / HELO {$ff->Mail['helo']}");
342             $mailer = Mail::factory('smtp', array(
343                     'host'    => $dom ,
344                     'localhost' => $ff->Mail['helo'],
345                     'timeout' => 15,
346                     'socket_options' =>  isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
347                     //'debug' => isset($opts['debug']) ?  1 : 0,
348                     'debug' => 1,
349                     'debug_handler' => array($this, 'debugHandler')
350                 ));
351             $res = $mailer->send($p->email, $email['headers'], $email['body']);
352              
353             
354             if ($res === true) {
355                 // success....
356                 
357                 $ev = $this->addEvent('NOTIFYSENT', $w, "{$w->to_email} - {$email['headers']['Subject']}");
358                 
359                 $ev->writeEventLog($this->debug_str);
360                 
361                 $w->sent = date('Y-m-d H:i:s');
362                 $w->msgid = $email['headers']['Message-Id'];
363                 $w->event_id = $ev->id; // sent ok.. - no need to record it..
364                 $w->update($ww);
365                 
366                 // enable cc in notify..
367                 if (!empty($email['headers']['Cc'])) {
368                     $cmailer = Mail::factory('smtp', array(
369                        //'host'    => $dom ,
370                       //  'debug' => true
371                     ));
372                     $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
373                     $cmailer->send($email['headers']['Cc'],
374                                   $email['headers'], $email['body']);
375                     
376                 }
377                 
378                 if (!empty($email['bcc'])) {
379                     $cmailer = Mail::factory('smtp', array(
380                        //'host'    => $dom ,
381                       //  'debug' => true
382                     ));
383                     $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
384                     $cmailer->send($email['bcc'],
385                                   $email['headers'], $email['body']);
386                     
387                 }
388                 
389                 
390                 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT\n");
391             }
392             // what type of error..
393             $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
394             if (!empty($res->code) && $res->code == 10001) {
395                 // fake greylist if timed out.
396                 $code = 421;
397             }
398             
399             if ($code < 0) {
400                 $this->debug($res->message);
401                 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
402             }
403             // give up after 2 days..
404             if (in_array($code, array( 421, 450, 451, 452))   && $next_try_min < (2*24*60)) {
405                 // try again later..
406                 // check last event for this item..
407                 //$errmsg=  $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) :  " - UNKNOWN ERROR";
408                 $errmsg=  $res->userinfo['smtpcode'] . ': ' .$res->message ;
409                 if (!empty($res->userinfo['smtptext'])) {
410                     $errmsg=  $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
411                 }
412                 //print_r($res);
413                 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
414                 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
415                 $w->update($ww);
416                 
417                 
418                 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED -  $errmsg \n");
419             }
420             $fail = true;
421             break;
422         }
423         if ($fail || $next_try_min > (2*24*60)) {
424         // fail.. = log and give up..
425             $errmsg=  $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) :  " - UNKNOWN ERROR";
426             if (isset($res->userinfo['smtptext'])) {
427                 $errmsg=  $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
428             }
429             
430             $ev = $this->addEvent('NOTIFY', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .
431                        $errmsg);
432             $w->sent = date('Y-m-d H:i:s');
433             $w->msgid = '';
434             $w->event_id = $ev->id;
435             $w->update($ww);
436             $this->errorHandler(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
437         }
438         
439         // handle no host availalbe forever...
440         if (strtotime($w->act_start) < strtotime('NOW - 3 DAYS')) {
441             $ev = $this->addEvent('NOTIFY', $w, "RETRY TIME EXCEEDED - ". $p->email);
442             $w->sent = date('Y-m-d H:i:s');
443             $w->msgid = '';
444             $w->event_id = $ev->id;
445             $w->update($ww);
446             $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED - RETRY TIME EXCEEDED\n");
447             
448             
449         }
450         
451         
452         $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
453         $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
454         $w->update($ww);
455         $this->errorHandler(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
456
457         
458     }
459     function mxs($fqdn)
460     {
461         $ff = HTML_FlexyFramework::get();
462         if (isset($ff->Pman_Core_NotifySend['host'])) {
463             return array($ff->Pman_Core_NotifySend['host']);
464         }
465         
466         $mx_records = array();
467         $mx_weight = array();
468         $mxs = array();
469         if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
470             if (!checkdnsrr($fqdn)) {
471                 return false;
472             }
473             return array($fqdn);
474         }
475         
476         asort($mx_weight,SORT_NUMERIC);
477         
478         foreach($mx_weight as $k => $weight) {
479             $mxs[] = $mx_records[$k];
480         }
481         return $mxs;
482     }
483     
484     /**
485      * wrapper to call object->toEmail()
486      *
487      * return
488      *   {
489         headers : {AssocArray},
490         body: {String}
491         
492         // optional..
493         error :  {String} // error message in log.
494         send-to: {String} // use to override rcpt
495          
496      }
497      **/
498     function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
499     {
500         $m = 'notify'. $notify->evtype;
501         //var_dump(get_class($object) . '::' .$m);
502         if (!empty($notify->evtype) && method_exists($object,$m)) {
503             echo "calling :" . get_class($object) . '::' .$m . "\n";
504             return $object->$m($rcpt, $last_sent_date, $notify, $force);
505         }
506         
507         $type = explode('::', $notify->evtype);
508         
509         if(!empty($type[1]) && method_exists($object,$type[1])){
510             $m = $type[1];
511             echo "calling :" . get_class($object) . '::' .$m . "\n";
512             return $object->$m($rcpt, $last_sent_date, $notify, $force);
513         }
514                 
515         if (!method_exists($object, 'toEmail')) {
516             //var_Dump($object);
517             //exit;
518         }
519         
520         return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
521     }
522     
523     function debug($str)
524     {
525         if (empty($this->cli_args['debug'])) {
526             return;
527             
528         }
529         echo $str . "\n";
530     }
531     function output()
532     {
533         $this->errorHandler("done\n");
534     }
535     var $debug_str = '';
536     
537     function debugHandler ($smtp, $message)
538     {
539         $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
540         $this->debug_str .= $message;
541     }
542     
543     function errorHandler($msg)
544     {
545         if($this->error_handler == 'exception'){
546             throw new Exception($msg);
547         }
548         
549         die($msg);
550         
551         
552     }
553 }