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         'remote' => array(
60             'desc' => 'Return to referer rather then die',
61             'default' => 0,
62             'short' => 'r',
63             'min' => 0,
64             'max' => 0,
65         ),
66         'send-to' => array(
67             'desc' => 'Send the message to this address, rather than the one listed.',
68             'default' => '',
69             'short' => 't',
70             'min' => 0,
71             'max' => 1,
72         )
73         
74         
75         
76     );
77     var $table = 'core_notify';
78     var $remote = false;
79     
80     function getAuth()
81     {
82         $ff = HTML_FlexyFramework::get();
83         if (!$ff->cli) {
84             $this->errorHandler("access denied");
85         }
86         //HTML_FlexyFramework::ensureSingle(__FILE__, $this);
87         return true;
88         
89     }
90    
91     function get($id,$opts)
92     {
93         
94         //print_r($opts);
95         if (!empty($opts['DB_DataObject-debug'])) {
96             DB_DataObject::debugLevel($opts['DB_DataObject-debug']);
97         }
98         
99         if(!empty($opts['remote'])){
100             $this->remote = true;
101         }
102         //DB_DataObject::debugLevel(1);
103         //date_default_timezone_set('UTC');
104         // phpinfo();exit;
105         $force = empty($opts['force']) ? 0 : 1;
106         
107         $w = DB_DataObject::factory($this->table);
108         
109         if (!$w->get($id)) {
110             $this->errorHandler("invalid id\n");
111         }
112         if (!$force && strtotime($w->act_when) < strtotime($w->sent)) {
113             
114             
115             $this->errorHandler("send repeat to early\n");
116         }
117         if (!empty($opts['debug'])) {
118             print_r($w);
119         }
120         
121         $sent = (empty($w->sent) || preg_match('/^0000/', $w->sent)) ? false : true;
122         
123         if (!$force && (!empty($w->msgid) || $sent)) {
124             $ww = clone($w);
125             if (!$sent) { 
126                 $w->sent = $w->sqlValue("NOW()");
127                 $w->update($ww);
128             }    
129             $this->errorHandler("message has been sent already.\n");
130         }
131         
132         $o = $w->object();
133         
134         if ($o === false)  {
135             
136             $ev = $this->addEvent('NOTIFY', $w,
137                             "Notification event cleared (underlying object does not exist)" );;
138             $ww = clone($w);
139             $w->sent = date('Y-m-d H:i:s');
140             $w->msgid = '';
141             $w->event_id = $ev->id;
142             $w->update($ww);
143             $this->errorHandler(date('Y-m-d h:i:s ') . 
144                      "Notification event cleared (underlying object does not exist)" 
145                     ."\n");
146         }
147      
148         
149         
150         $p = $w->person();
151         
152         if (isset($p->active) && empty($p->active)) {
153             $ev = $this->addEvent('NOTIFY', $w,
154                             "Notification event cleared (not user not active any more)" );;
155             $ww = clone($w);
156             $w->sent = date('Y-m-d H:i:s');
157             $w->msgid = '';
158             $w->event_id = $ev->id;
159             $w->update($ww);
160             $this->errorHandler(date('Y-m-d h:i:s ') . 
161                      "Notification event cleared (not user not active any more)" 
162                     ."\n");
163             $this->errorHandler("message has been sent already.\n");
164         }
165         
166         
167         // let's work out the last notification sent to this user..
168         $l = DB_DataObject::factory($this->table);
169         $l->setFrom( array(
170                 'ontable' => $w->ontable,
171                 'onid' => $w->onid,
172                 'person_id' => $w->person_id,
173         ));        
174         $l->whereAdd('id != '. $w->id);
175         $l->orderBy('sent DESC');
176         $l->limit(1);
177         $ar = $l->fetchAll('sent');
178         $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
179         
180         // find last event..
181         $ev = DB_DataObject::factory('Events');
182         $ev->on_id = $w->id;                           // int(11)
183         $ev->on_table = $this->table;
184         $ev->limit(1);
185         $ev->orderBy('event_when DESC');
186         $ar = $ev->fetchAll('event_when');
187         $last_event = empty($ar) ? 0 : $ar[0];
188         $next_try_min = 5;
189         if ($last_event) {
190             $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
191         }
192         $next_try = $next_try_min . ' MINUTES';
193          
194         // this may modify $p->email. (it will not update it though)
195         $email =  $this->makeEmail($o, $p, $last, $w, $force);
196         
197         if ($email === true)  {
198             
199             $ev = $this->addEvent('NOTIFY', $w,
200                             "Notification event cleared (not required any more)" );;
201             $ww = clone($w);
202             $w->sent = date('Y-m-d H:i:s');
203             $w->msgid = '';
204             $w->event_id = $ev->id;
205             $w->update($ww);
206             $this->errorHandler(date('Y-m-d h:i:s ') . 
207                      "Notification event cleared (not required any more)" 
208                     ."\n");
209         }
210      
211        
212         
213         if ($email === false || isset($email['error'])) {
214             // object returned 'false' - it does not know how to send it..
215             $ev = $this->addEvent('NOTIFY', $w, isset($email['error'])  ?
216                             $email['error'] : "INTERNAL ERROR  - We can not handle " . $w->ontable); 
217             $ww = clone($w);
218             $w->sent = date('Y-m-d H:i:s');
219             $w->msgid = '';
220             $w->event_id = $ev->id;
221             $w->update($ww);
222             $this->errorHandler(date('Y-m-d h:i:s ') . 
223                     (isset($email['error'])  ?
224                             $email['error'] : "INTERNAL ERROR  - We can not handle " . $w->ontable)
225                     ."\n");
226         }
227         
228         
229         if (isset($email['later'])) {
230             $old = clone($w);
231             $w->act_when = $email['later'];
232             $w->update($old);
233             $this->errorHandler(date('Y-m-d h:i:s ') . " Delivery postponed by email creator");
234         }
235         
236          
237         if (empty($email['headers']['Message-Id'])) {
238             $HOST = gethostname();
239             $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
240             
241         }
242         //$p->email = 'alan@akbkhome.com'; //for testing..
243         //print_r($email);exit;
244         // should we fetch the watch that caused it.. - which should contain the method to call..
245         // --send-to=test@xxx.com
246        
247         if (!empty($email['send-to'])) {
248             $p->email = $email['send-to'];
249         }
250          if (!empty($opts['send-to'])) {
251             $p->email = $opts['send-to'];
252         }
253         // since some of them have spaces?!?!
254         $p->email = trim($p->email);
255         
256         
257         require_once 'Validate.php';
258         if (!Validate::email($p->email, true)) {
259             $ev = $this->addEvent('NOTIFY', $w, "INVALID ADDRESS: " . $p->email);
260             $ww = clone($w);
261             $w->sent = date('Y-m-d H:i:s');
262             $w->msgid = '';
263             $w->event_id = $ev->id;
264             $w->update($ww);
265             $this->errorHandler(date('Y-m-d h:i:s ') . "INVALID ADDRESS: " . $p->email. "\n");
266             
267         }
268         
269         
270         $ff = HTML_FlexyFramework::get();
271         
272         
273         $dom = array_pop(explode('@', $p->email));
274         
275         $mxs = $this->mxs($dom);
276         $ww = clone($w);
277
278         // we might fail doing this...
279         // need to handle temporary failure..
280        
281         
282           // we try for 3 days..
283         $retry = 5;
284         if (strtotime($w->act_start) <  strtotime('NOW - 1 HOUR')) {
285             // older that 1 hour.
286             $retry = 15;
287         }
288         
289         if (strtotime($w->act_start) <  strtotime('NOW - 1 DAY')) {
290             // older that 1 day.
291             $retry = 60;
292         }
293         if (strtotime($w->act_start) <  strtotime('NOW - 2 DAY')) {
294             // older that 1 day.
295             $retry = 120;
296         }
297         
298         if ($mxs === false) {
299             // only retry for 2 day son the MX issue..
300             if ($retry < 120) {
301                 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
302                 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
303                 $w->update($ww);
304                 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED\n");
305             }
306             
307             $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
308             $w->sent = date('Y-m-d H:i:s');
309             $w->msgid = '';
310             $w->event_id = $ev->id;
311             $w->update($ww);
312             $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED -  BAD EMAIL - {$p->email} \n");
313             
314             
315         }
316         
317         
318         
319         
320         if (!$force && strtotime($w->act_start) <  strtotime('NOW - 14 DAY')) {
321             $ev = $this->addEvent('NOTIFY', $w, "BAD ADDRESS - ". $p->email );
322             $w->sent = date('Y-m-d H:i:s');
323             $w->msgid = '';
324             $w->event_id = $ev->id;
325             $w->update($ww);
326             $this->errorHandler(date('Y-m-d h:i:s') . " - FAILED -  GAVE UP TO OLD - {$p->email} \n");
327         }
328         
329         
330         
331         $w->to_email = $p->email; 
332         //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
333         $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
334         $w->update($ww);
335         
336         $ww = clone($w);   
337         
338         $fail = false;
339         require_once 'Mail.php';
340         
341         foreach($mxs as $dom) {
342             
343             
344             
345             if (!isset($ff->Mail['helo'])) {
346                 $this->errorHandler("config Mail[helo] is not set");
347             }
348             $this->debug_str = '';
349             $this->debug("Trying SMTP: $dom / HELO {$ff->Mail['helo']}");
350             $mailer = Mail::factory('smtp', array(
351                     'host'    => $dom ,
352                     'localhost' => $ff->Mail['helo'],
353                     'timeout' => 15,
354                     'socket_options' =>  isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
355                     //'debug' => isset($opts['debug']) ?  1 : 0,
356                     'debug' => 1,
357                     'debug_handler' => array($this, 'debugHandler')
358                 ));
359             $res = $mailer->send($p->email, $email['headers'], $email['body']);
360              
361             
362             if ($res === true) {
363                 // success....
364                 
365                 $ev = $this->addEvent('NOTIFYSENT', $w, "{$w->to_email} - {$email['headers']['Subject']}");
366                 
367                 $ev->writeEventLog($this->debug_str);
368                 
369                 $w->sent = date('Y-m-d H:i:s');
370                 $w->msgid = $email['headers']['Message-Id'];
371                 $w->event_id = $ev->id; // sent ok.. - no need to record it..
372                 $w->update($ww);
373                 
374                 // enable cc in notify..
375                 if (!empty($email['headers']['Cc'])) {
376                     $mailer = Mail::factory('smtp', array(
377                        //'host'    => $dom ,
378                       //  'debug' => true
379                     ));
380                     $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
381                     $mailer->send($email['headers']['Cc'],
382                                   $email['headers'], $email['body']);
383                     
384                 }
385                 
386                 if (!empty($email['bcc'])) {
387                     $mailer = Mail::factory('smtp', array(
388                        //'host'    => $dom ,
389                       //  'debug' => true
390                     ));
391                     $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
392                     $mailer->send($email['bcc'],
393                                   $email['headers'], $email['body']);
394                     
395                 }
396                 
397                 
398                 $this->errorHandler(date('Y-m-d h:i:s') . " - SENT\n");
399             }
400             // what type of error..
401             $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
402             if (!empty($res->code) && $res->code == 10001) {
403                 // fake greylist if timed out.
404                 $code = 421;
405             }
406             
407             if ($code < 0) {
408                 $this->debug($res->message);
409                 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
410             }
411             // give up after 2 days..
412             if (in_array($code, array( 421, 450, 451, 452))   && $next_try_min < (2*24*60)) {
413                 // try again later..
414                 // check last event for this item..
415                 $errmsg=  $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) :  " - UNKNOWN ERROR";
416                 if (isset($res->userinfo['smtptext'])) {
417                     $errmsg=  $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
418                 }
419                 //print_r($res);
420                 $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
421                 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
422                 $w->update($ww);
423                 $this->errorHandler(date('Y-m-d h:i:s') . " - GREYLISTED\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(empty($this->remote)){
551             die($msg);
552         }
553         
554         return $msg;
555         
556         
557     }
558 }