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