initialize array
[Pman.Core] / DataObjects / Core_notify_server.php
1 <?php
2 /**
3  * Table Definition for core_notify_server
4  */
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
6
7 class Pman_Core_DataObjects_Core_notify_server extends DB_DataObject 
8 {
9     ###START_AUTOCODE
10     /* the code below is auto generated do not remove the above tag */
11
12     public $__table = 'core_notify_server';    // table name
13     public $id;                              // int(11)  not_null primary_key auto_increment
14     public $hostname;
15     public $helo;
16     public $poolname;
17     public $is_active;
18     public $last_send;
19     
20     
21     
22     function  applyFilters($q, $au, $roo)
23     {
24         if (isset($q['_with_queue_size'])) {
25             $this->addQueueSize();
26         }
27     }
28     
29     
30     function addQueueSize()
31     {
32         // look for database links for server_id (which should find core_notify + others..)
33         $cn = get_class(DB_DataObject::factory('core_notify'));
34         $tables = array();
35         foreach($this->databaseLinks() as $tbl => $kv) {
36             foreach($kv as $k=>$v) {
37                 if ($v != 'core_notify_server:id') {
38                     continue;
39                 }
40                 
41                 $test = DB_DAtaObject::factory($tbl);
42                 if (!is_a($test, $cn)) {
43                     break;
44                 }
45                 $tables[] = $tbl;
46             }
47         }
48         if (empty($tables)) {
49             die("OOPS - no tables for notify_server references");
50         }
51         $totals = array();
52         foreach($tables as $t) {
53             $totals[] = "
54                 COALESCE((SELECT
55                     count(id)
56                 FROM
57                     $t
58                 WHERE
59                     server_id = core_notify_server.id
60                 AND
61                     sent < '1970-01-01' OR sent IS NULL
62                  and
63                         event_id = 0
64                 ),0)
65             ";
66         }
67         $this->selectAdd("(" . implode(" + ", $totals) . ") as in_queue ");
68         
69         
70         
71         
72         
73     }
74     
75     
76     // most services should call this first..
77     
78     function getCurrent($notify, $force = false)
79     {
80         static $current = false;;
81         
82         if ($current !== false) {
83             return $current;
84         }
85         
86         $ns = DB_DataObject::factory('core_notify_server');
87         
88         $ns->poolname = $notify->poolname;
89         $ns->is_active = 1;
90         $ns->hostname = gethostname();
91         $ns->limit(1);
92         if ($ns->find(true)) {
93             $current = $ns;
94             return $ns;
95         }
96         if (!$force) {
97             $notify->jerr("Server not found for this server " .  gethostname() . " in core_notify_server" );
98         }
99         // fallback to any server - if we are using force. (this is so helo will work...)
100         
101         $ns = DB_DataObject::factory('core_notify_server');
102         $ns->is_active = 1;
103         $ns->hostname = gethostname();
104         if (!$ns->find(true)) {
105             $notify->jerr("Server not found for this server " .  gethostname() . " in core_notify_server" );
106         }
107         $current = $ns;
108         return $ns;
109     }
110     
111     
112     function isFirstServer()
113     {
114         $servers = $this->availableServers();
115         if (empty($servers)) {
116             return false;
117         }
118         // only run this on the first server...
119         return $this->id == $servers[0]->id;
120     }
121     
122     
123     // called on current server.
124     function assignQueues($notify)
125     {
126          
127         
128         $servers = $this->availableServers();
129         $ids = array();
130         $up = array();
131         foreach($servers as $s) {
132             $ids[] = $s->id;
133         }
134         
135         
136         if (empty($ids)) {
137             $notify->jerr("no configured servers in core_notify_server for poolname = {$notify->poolname}");
138             
139         }
140          
141         // only run this on the first server...
142         if ($this->id != $ids[0]) {
143             return; 
144         }
145         foreach($ids as $rn) {
146             $up[$rn]  = array();
147         }
148         
149         $num_servers = count($ids);
150         
151         if ($num_servers == 1) {
152             $p = DB_DataObject::factory($notify->table);
153             $p->query("
154                 UPDATE
155                     {$notify->table}
156                 SET
157                     server_id = {$ids[0]}
158                 WHERE
159                     sent < '2000-01-01'
160                     and
161                     event_id = 0
162                     and
163                     act_start < NOW() +  INTERVAL 3 HOUR 
164                     and
165                     server_id != {$ids[0]}
166             ");
167             return;
168         }
169         
170         
171         
172         $p = DB_DataObject::factory($notify->table);
173         $p->whereAdd("
174                 sent < '2000-01-01'
175                 and
176                 event_id = 0
177                 and
178                 act_start < NOW() +  INTERVAL 3 HOUR 
179                 and
180                 server_id NOT IN (" . implode(",", $ids) . ")
181         ");
182         $p->orderBy('act_when asc'); //?
183         $total_add = $p->count();
184         if ($total_add < 1) {
185             return;
186         }
187         
188         $to_add = $p->fetchAll('id');
189         
190         $p = DB_DataObject::factory($notify->table);
191         $p->whereAdd("
192                 sent < '2000-01-01'
193                 and
194                 event_id = 0
195         
196                 and
197                 server_id IN (" . implode(",", $ids) . ")
198         ");
199         $p->selectAdd();
200         $p->selectAdd('server_id, count(id) as  n');
201         $p->groupBy('server_id');
202         $in_q = $p->fetchAll('server_id', 'n');
203         
204         // if queue is empty it will not get allocated anything.
205         foreach($ids as $sid) {
206             if (!isset($in_q[$sid])) {
207                 $in_q[$sid] = 0;
208             }
209         }
210         $totalq = 0;
211         foreach($in_q as $sid => $n) {
212             $totalq += $n;
213         }
214         
215         
216         // new average queue
217         $target_len = floor(  ($totalq + $total_add) / $num_servers );
218         
219         foreach($in_q as $sid => $cq) {
220             if ( $cq > $target_len) {
221                 continue;
222             }
223             $up[ $sid ] = array_slice($to_add, 0, $target_len - $cq);
224         }
225         
226         // add the reminder evently
227         foreach($to_add as $n=>$i) {
228             
229             $up[  $ids[$n % $num_servers] ][] = $i;
230         }
231         
232         // distribution needs to go to ones that have the shortest queues. - so to balance out the queues
233         
234          
235         
236         foreach($up as $sid => $nids) {
237             if (empty($nids)) {
238                 continue;
239             }
240             $p = DB_DataObject::factory($notify->table);
241             $p->query("
242                 UPDATE
243                     {$notify->table}
244                 SET
245                     server_id = $sid
246                 WHERE
247                     id IN (". implode(',', $nids). ')'
248             );
249         }
250          
251         DB_DataObject::factory("core_notify_blacklist")->prune();
252         
253     }
254         // called on current server.
255
256     function availableServers()
257     {
258         $ns = DB_DataObject::factory('core_notify_server');
259         $ns->poolname = $this->poolname;
260         $ns->is_active = 1;
261         $ns->orderBy('id ASC');
262         return  $ns->fetchAll();
263         
264     }
265     
266     function updateNotifyToNextServer( $cn , $when = false, $allow_same = false)
267     {
268         // fixme - this should take into account blacklisted - and return false if no more servers are available
269         $email = empty($cn->to_email) ? ($cn->person() ? $cn->person()->email : $cn->to_email) : $cn->to_email;
270
271         $w = DB_DataObject::factory($cn->tableName());
272         $w->get($cn->id);
273         
274         $servers = $this->availableServers();
275         $start = 0;
276         foreach($servers as $i => $s) {
277             if ($s->id == $this->id) {
278                 $start = $i;
279             }
280         }
281         
282         $offset = ($start + 1)  % count($servers);
283         $good = false;
284         while ($offset  != $start) {
285             $s = $servers[$offset];
286             if (!$s->isBlacklisted($email)) {
287                 $good = $s;
288                 break;
289             }
290             $offset = ($offset + 1)  % count($servers);
291             var_dump($offset);
292         }
293         if ($good == false && $allow_same) {
294             $good = $this;
295         }
296         
297         if ($good == false) {
298             return false;
299         }
300         
301         
302         // next server..
303         $pp = clone($w);
304         $w->server_id = $good->id;   
305         $w->act_when = $when === false ? $w->sqlValue('NOW() + INTERVAL 1 MINUTE') : $when;
306         $w->update($pp);
307         return true;
308     }
309     
310     
311     function isBlacklisted($email)
312     {
313         // return current server id..
314         static $cache = array();
315          // get the domain..
316         $ea = explode('@',$email);
317         $dom = strtolower(array_pop($ea));
318         if (isset( $cache[$this->id . '-'. $dom])) {
319             return  $cache[$this->id . '-'. $dom];
320         }
321         
322         $cd = DB_DataObject::factory('core_domain')->loadOrCreate($dom);
323         
324         $bl = DB_DataObject::factory('core_notify_blacklist');
325         $bl->server_id = $this->id;
326         $bl->domain_id = $cd->id;
327         if ($bl->count()) {
328             $cache[$this->id . '-'. $dom] = true;
329             return true;
330         }
331         
332         return false; 
333     }
334     function initHelo()
335     {
336         $ff = HTML_FlexyFramework::get();
337         $ff->Mail['helo'] = $this->helo;
338         
339     }
340     function checkSmtpResponse($errmsg, $core_domain)
341     {
342         $bl = DB_DataObject::factory('core_notify_blacklist');
343         $bl->server_id = $this->id;
344         $bl->domain_id = $core_domain->id;
345         if ($bl->count()) {
346             return true;
347         }
348         // is it a blacklist message
349         if (!$bl->messageIsBlacklisted($errmsg)) {
350             return false;
351         }
352         $bl->error_str = $errmsg;
353         $bl->added_dt = $bl->sqlValue("NOW()");
354         $bl->insert();
355         return true;
356         
357     }
358     
359 }