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