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