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