DataObjects/Core_event_audit.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         if ($opts['DB_DataObject-debug']) {
80             DB_DataObject::debugLevel($opts['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             die("message has been sent already.\n");
100         }
101         
102         
103         $o = $w->object();
104         $p = $w->person();
105         
106         // let's work out the last notification sent to this user..
107         $l = DB_DataObject::factory($this->table);
108         $l->setFrom( array(
109                 'ontable' => $w->ontable,
110                 'onid' => $w->onid,
111                 'person_id' => $w->person_id,
112         ));        
113         $l->whereAdd('id != '. $w->id);
114         $l->orderBy('sent DESC');
115         $l->limit(1);
116         $ar = $l->fetchAll('sent');
117         $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
118         
119         // find last event..
120         $ev = DB_DataObject::factory('Events');
121         $ev->on_id = $w->id;                           // int(11)
122         $ev->on_table = $this->table;
123         $ev->limit(1);
124         $ev->orderBy('event_when DESC');
125         $ar = $ev->fetchAll('event_when');
126         $last_event = empty($ar) ? 0 : $ar[0];
127         $next_try_min = 5;
128         if ($last_event) {
129             $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
130         }
131         $next_try = $next_try_min . ' MINUTES';
132         
133         $email =  $this->makeEmail($o, $p, $last, $w);
134         
135         if ($email === false || isset($email['error'])) {
136             // object returned 'false' - it does not know how to send it..
137             $id = $this->addEvent('NOTIFY', $w, isset($email['error'])  ?
138                             $email['error'] : "INTERNAL ERROR  - We can not handle " . $w->ontable);;
139             $ww = clone($w);
140             $w->sent = date('Y-m-d H:i:s');
141             $w->msgid = '';
142             $w->event_id = $id;
143             $w->update($ww);
144             die(date('Y-m-d h:i:s ') . 
145                     (isset($email['error'])  ?
146                             $email['error'] : "INTERNAL ERROR  - We can not handle " . $w->ontable)
147                     ."\n");
148         }
149         
150         
151         
152         
153         if (!isset($email['headers']['Message-Id'])) {
154             $HOST = gethostname();
155             $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
156             
157         }
158         //$p->email = 'alan@akbkhome.com'; //for testing..
159         //print_r($email);exit;
160         // should we fetch the watch that caused it.. - which should contain the method to call..
161         
162         if (!empty($opts['send-to'])) {
163             $p->email = $opts['send-to'];
164         }
165         
166         
167         $dom = array_pop(explode('@', $p->email));
168         
169         $mxs = $this->mxs($dom);
170         $ww = clone($w);
171         
172         $fail = false;
173         require_once 'Mail.php';
174         
175         foreach($mxs as $dom) {
176             $this->debug("Trying SMTP: $dom");
177             $mailer = Mail::factory('smtp', array(
178                     'host'    => $dom ,
179                   //  'debug' => true
180                 ));
181             $res = $mailer->send($p->email, $email['headers'], $email['body']);
182             if ($res === true) {
183                 // success....
184                 
185                 $w->sent = date('Y-m-d H:i:s');
186                 $w->msgid = $email['headers']['Message-Id'];
187                 $w->event_id = -1; // sent ok.. - no need to record it..
188                 $w->update($ww);
189                 die(date('Y-m-d h:i:s') . " - SENT\n");
190             }
191             // what type of error..
192             $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
193             if ($code < 0) {
194                 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
195             }
196             // give up after 2 days..
197             if (in_array($code, array( 421, 451, 452))   && $next_try_min < (2*24*60)) {
198                 // try again later..
199                 // check last event for this item..
200                 $this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
201                 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
202                 $w->update($ww);
203                 die(date('Y-m-d h:i:s') . " - GREYLISTED\n");
204             }
205             $fail = true;
206             break;
207         }
208         if ($fail || $next_try_min > (2*24*60)) {
209         // fail.. = log and give up..
210             $id = $this->addEvent('NOTIFY', $w, "RETRY TIME EXCEEDED - ".
211                         $p->email . ' ' .
212                         ($fail ? ($res->userinfo['smtpcode'] . ' : ' .$res->toString()) :  " - UNKNOWN ERROR"));
213             $w->sent = date('Y-m-d H:i:s');
214             $w->msgid = '';
215             $w->event_id = $id;
216             $w->update($ww);
217             die(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
218         }
219         
220         $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED:' . $p->email);
221         $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
222         $w->update($ww);
223         die(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
224
225         
226     }
227     function mxs($fqdn)
228     {
229         $mx_records = array();
230         $mx_weight = array();
231         $mxs = array();
232         if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
233             return array($fqdn);
234         }
235         
236         asort($mx_weight,SORT_NUMERIC);
237         
238         foreach($mx_weight as $k => $weight) {
239             $mxs[] = $mx_records[$k];
240         }
241         return $mxs;
242     }
243     
244     /**
245      * wrapper to call object->toEmail()
246      * 
247      **/
248     function makeEmail($o, $p, $last, $notify)
249     {
250         return $o->toEmail($p,$last, $notify);
251     }
252     
253     function debug($str)
254     {
255         if (empty($this->cli_args['debug'])) {
256             return;
257             
258         }
259         echo $str . "\n";
260     }
261     
262 }