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