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  */
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             'short' => 't',
57             'min' => 0,
58             'max' => 1,
59         )
60         
61         
62         
63     );
64     var $table = 'core_notify';
65     function getAuth()
66     {
67         $ff = HTML_FlexyFramework::get();
68         if (!$ff->cli) {
69             die("access denied");
70         }
71         //HTML_FlexyFramework::ensureSingle(__FILE__, $this);
72         return true;
73         
74     }
75    
76     function get($id,$opts)
77     {
78         if ($opts['DB_DataObject-debug']) {
79             DB_DataObject::debugLevel($opts['debug']);
80         }
81         //DB_DataObject::debugLevel(1);
82         //date_default_timezone_set('UTC');
83         // phpinfo();exit;
84         $force = empty($opts['force']) 0 : 1;
85         
86         $w = DB_DataObject::factory($this->table);
87         
88         if (!$w->get($id)) {
89             die("invalid id\n");
90         }
91         if (!$force && strtotime($w->act_when) < strtotime($w->sent)) {
92             
93             
94             die("send repeat to early\n");
95         }
96         
97         if (!$force && !empty($w->msgid)) {
98             die("message has been sent already.\n");
99         }
100         
101         
102         $o = $w->object();
103         $p = $w->person();
104         
105         // let's work out the last notification sent to this user..
106         $l = DB_DataObject::factory($this->table);
107         $l->setFrom( array(
108                 'ontable' => $w->ontable,
109                 'onid' => $w->onid,
110                 'person_id' => $w->person_id,
111         ));        
112         $l->whereAdd('id != '. $w->id);
113         $l->orderBy('sent DESC');
114         $l->limit(1);
115         $ar = $l->fetchAll('sent');
116         $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
117         
118         // find last event..
119         $ev = DB_DataObject::factory('Events');
120         $ev->on_id = $w->id;                           // int(11)
121         $ev->od_table = $this->table;
122         $ev->limit(1);
123         $ev->orderBy('event_when DESC');
124         $ar = $ev->fetchAll('event_when');
125         $last_event = empty($ar) ? 0 : $ar[0];
126         $next_try_min = 5;
127         if ($last_event) {
128             $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
129         }
130         $next_try = $next_try_min . ' MINUTES';
131         
132         $email =  $this->makeEmail($o, $p, $last, $ev);
133         
134         
135         
136         if (!isset($email['headers']['Message-Id'])) {
137             $HOST = gethostname();
138             $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
139             
140         }
141         //$p->email = 'alan@akbkhome.com'; //for testing..
142         //print_r($email);exit;
143         // should we fetch the watch that caused it.. - which should contain the method to call..
144         
145         if (!empty($opts['send-to'])) {
146             $p->email = $opts['send-to'];
147         }
148         
149         
150         $dom = array_pop(explode('@', $p->email));
151         
152         $mxs = $this->mxs($dom);
153         $ww = clone($w);
154         
155         $fail = false;
156         require_once 'Mail.php';
157         
158         foreach($mxs as $dom) {
159             $this->debug("Trying SMTP: $dom");
160             $mailer = Mail::factory('smtp', array(
161                     'host'    => $dom ,
162                   //  'debug' => true
163                 ));
164             $res = $mailer->send($p->email, $email['headers'], $email['body']);
165             if ($res === true) {
166                 // success....
167                 
168                 $w->sent = date('Y-m-d H:i:s');
169                 $w->msgid = $email['headers']['Message-Id'];
170                 $w->event_id = -1; // sent ok.. - no need to record it..
171                 $w->update($ww);
172                 die(date('Y-m-d h:i:s') . " - SENT\n");
173             }
174             // what type of error..
175             $code = empty($res->smtpcode) ? -1 : $res->smtpcode;
176             if ($code < 0) {
177                 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
178             }
179             // give up after 2 days..
180             if ($code == 421 && $next_try_min < (2*24*60)) {
181                 // try again later..
182                 // check last event for this item..
183                 $this->addEvent('NOTIFY', $w, 'GREYLISTED\n');
184                 $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
185                 $w->update($ww);
186                 die(date('Y-m-d h:i:s') . " - GREYLISTED\n");
187             }
188             $fail = true;
189             break;
190         }
191         if ($fail || $next_try_min > (2*24*60)) {
192         // fail.. = log and give up..
193             $id = $this->addEvent('NOTIFY', $w, "FAILED - ". ($fail ? ($res->smtpcode . ' : ' .$res->toString()) :  " - RETRY TIME EXCEEDED"));
194             $w->sent = date('Y-m-d H:i:s');
195             $w->msgid = '';
196             $w->event_id = $id;
197             $w->update($ww);
198             die(date('Y-m-d h:i:s') . ' - FAILED - '. ($fail ? $res->toString() : "RETRY TIME EXCEEDED\n"));
199         }
200         
201         $this->addEvent('NOTIFY', $w, 'NO HOST CAN BE CONTACTED');
202         $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 5 MINUTES'));
203         $w->update($ww);
204         die(date('Y-m-d h:i:s') ." - NO HOST AVAILABLE\n");
205
206         
207     }
208     function mxs($fqdn)
209     {
210         $mx_records = array();
211         $mx_weight = array();
212         $mxs = array();
213         if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
214             return array($fqdn);
215         }
216         
217         asort($mx_weight,SORT_NUMERIC);
218         
219         foreach($mx_weight as $k => $weight) {
220             $mxs[] = $mx_records[$k];
221         }
222         return $mxs;
223     }
224     
225     /**
226      * wrapper to call object->toEmail()
227      * 
228      **/
229     function makeEmail($o, $p, $last, $notify)
230     {
231         return $o->toEmail($p,$last);
232     }
233     
234     function debug($str)
235     {
236         if (empty($this->cli_args['debug'])) {
237             return;
238             
239         }
240         echo $str . "\n";
241     }
242     
243 }