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