Merge branch 'master' of http://git.roojs.com:8081/Pman.Core
[Pman.Core] / Notify.php
1 <?php
2 require_once 'Pman.php';
3
4 /**
5  * notification script runner
6  *
7  * This does not actualy send stuf out, it only starts the NotifySend/{id}
8  * which does the actuall notifcations.
9  *
10  * It manages a pool of notifiers.
11  * 
12  * 
13  */
14
15
16 class Pman_Core_Notify extends Pman
17 {
18     
19     static $cli_desc = "Runs the notification queue (usually from cron)
20                         Normally used to sends out emails to anyone in the notification list.
21     
22                         /etc/cron.d/pman-core-notify
23                         * *  * * *     www-data     /usr/bin/php /home/gitlive/web.mtrack/admin.php  Core/Notify > /dev/null
24     
25 ";
26     
27     static $cli_opts = array(
28         'debug' => array(
29             'desc' => 'Turn on debugging (see DataObjects debugLevel )',
30             'default' => 0,
31             'short' => 'v',
32             'min' => 1,
33             'max' => 1,
34             
35         ),
36         'list' => array(
37             'desc' => 'List message to send, do not send them..',
38             'default' => 0,
39             'short' => 'l',
40             'min' => 0,
41             'max' => 0,
42             
43         ),
44         'old' => array(
45             'desc' => 'Show old messages..',
46             'default' => 0,
47             'short' => 'o',
48             'min' => 0,
49             'max' => 0,
50             
51         ),
52         'force' => array(
53             'desc' => 'Force redelivery, even if it has been sent before or not queued...',
54             'default' => 0,
55             'short' => 'f',
56             'min' => 0,
57             'max' => 0,
58         ),
59         'generate' => array(
60             'desc' => 'Generate notifications for a table, eg. cash_invoice',
61             'default' => '',
62             'short' => 'g',
63             'min' => 0,
64             'max' => 1,
65         ),
66     );
67     
68     
69     
70     var $table = 'core_notify';
71     var $target = 'Core/NotifySend';
72     var $evtype = ''; // any notification...
73                     // this script should only handle EMAIL notifications..
74     var $force = false;
75     function getAuth()
76     {
77         $ff = HTML_FlexyFramework::get();
78         if (!$ff->cli) {
79             die("access denied");
80         }
81         HTML_FlexyFramework::ensureSingle(__FILE__, $this);
82         return true;
83         
84     }
85     
86     var $pool = array();
87     
88     function get($r,$opts)    
89     {
90         if ($opts['debug']) {
91             DB_DataObject::debugLevel($opts['debug']);
92             print_r($opts);
93         }
94         //date_default_timezone_set('UTC');
95        // phpinfo();exit;
96         $showold = !empty($opts['old']);
97         if (!empty($opts['old'])) {
98             $opts['list'] = 1; // force listing..
99         }
100         
101         $this->force = empty($opts['force']) ? 0 : 1;
102      
103         if (!empty($opts['send-to'])) {
104             $this->send_to = $opts['send-to'];
105         }
106      
107         
108         $w = DB_DataObject::factory('core_notify_recur');
109         if (is_a($w, 'DB_DataObject')) {
110             $w->generateNotifications();
111         }
112         if (!empty($opts['generate'])) {
113             $w = DB_DataObject::factory($opts['generate']);
114             if (is_a($w, 'DB_DataObject')) {
115                 $w->generateNotifications();
116             }
117             exit;
118             
119             
120         }
121      
122         //DB_DataObject::debugLevel(1);
123         $w = DB_DataObject::factory($this->table);
124         
125         if (!$showold) {
126             
127             // standard
128             
129             $w->whereAdd('act_when > sent'); // eg.. sent is not valid..
130             $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
131             if (!$this->force) {
132                 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
133             }
134     
135             $w->orderBy('act_when ASC'); // oldest first.
136             $w->limit(1000); // we can run 1000 ...
137         } else {
138             $w->orderBy('act_when DESC'); // latest first
139             $w->limit(50); // we can run 1000 ...
140         }
141         if (!empty($this->evtype)) {
142             $w->evtype = $this->evtype;
143         }
144         
145         $w->autoJoin();
146         
147         
148         $ar = $w->fetchAll();
149         
150         if (!empty($opts['list'])) {
151             if (empty($ar)) {
152                 die("Nothing in Queue\n");
153             }
154             foreach($ar as $w) {
155                 $o = $w->object();
156                 
157                 
158                 echo "$w->id : $w->person_id_email email    : ".
159                         $o->toEventString()."    ". $w->status() . "\n";
160             }
161             exit;
162         }
163         
164         
165         $pushed = array();
166         while (true) {
167             if (empty($ar)) {
168                 break;
169             }
170             
171             
172             $p = array_shift($ar);
173             if (!$this->poolfree()) {
174                 array_unshift($ar,$p); /// put it back on..
175                 sleep(3);
176                 continue;
177             }
178             if ($this->poolHasDomain($p->person_id_email)) {
179                 if (in_array($p->person_id_email, $pushed)) {
180                     // it's been pushed to the end, and nothing has
181                     // been pushed since.
182                     // give up, let the next run sort it out.
183                     break;
184                 }
185                 
186                 $ar[] = $p; // push it on the end..
187                 
188                 $pushed[] = $p->person_id_email;
189                 
190                 echo "domain {$p->person_id_email} already on queue, pushing to end.\n";
191                 sleep(3);
192                 continue;
193             }
194             
195             
196             $this->run($p->id,$p->person_id_email);
197             $pushed = array();
198             
199         }
200         
201         // we should have a time limit here...
202         while(count($this->pool)) {
203             $this->poolfree();
204             sleep(3);
205         }
206         
207         die("DONE\n");
208     }
209     
210     function run($id, $email, $cmdOpts="")
211     {
212        // phpinfo();exit;
213         $tn = tempnam(ini_get('session.save_path'),'stdout') . '.stdout';
214         $descriptorspec = array(
215             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
216             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
217             2 => array("pipe", "w") // stderr is a file to write to
218          );
219         $php = $_SERVER["_"];
220         $sn =  $_SERVER["SCRIPT_NAME"];
221         
222         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
223         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
224         if ($this->force) {
225             $app .= ' -f';
226         }
227         if (!empty($this->send_to)) {
228             $app .= ' --sent-to='.escapeshellarg($this->send_to);
229         }
230         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
231         
232        
233         $pipe = array();
234         echo "call proc_open $cmd\n";
235         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
236         $info =  proc_get_status($p);
237         $this->pool[] = array(
238                 'proc' => $p,
239                 'pid' => $info['pid'],
240                 'out' => $tn,
241                 'cmd' => $cmd,
242                 'email' => $email,
243                 'pipes' => $pipes,
244                 'started' => time()
245             
246                 
247         );
248         echo "RUN ({$info['pid']}) $cmd  \n";
249     }
250     
251     function poolfree()
252     {
253         $pool = array();
254         clearstatcache();
255         $maxruntime = 2 * 60; // 2 minutes.. ?? should be long enoguh
256         
257         foreach($this->pool as $p) {
258              
259             //echo "CHECK PID: " . $p['pid'] . "\n";
260             $info =  proc_get_status($p['proc']);
261             //var_dump($info);
262             
263             // update if necessday.
264             if ($info['pid']) {
265                 echo "CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']. "\n";
266                 $p['pid'] = $info['pid'];
267             }
268             
269             echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
270             
271             if ($info['running']) {
272             
273                 //if (file_exists('/proc/'.$p['pid'])) {
274                 $runtime = time() - $p['started'];
275                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
276                 if ($runtime > $maxruntime) {
277                     
278                     proc_terminate($p['proc'], 9);
279                     //fclose($p['pipes'][1]);
280                     fclose($p['pipes'][0]);
281                     fclose($p['pipes'][2]);
282                     echo "\nTERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
283                     @unlink($p['out']);
284                     
285                     continue;
286                 }
287                 
288                 $pool[] = $p;
289                 continue;
290             }
291             fclose($p['pipes'][0]);
292             fclose($p['pipes'][2]);
293             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
294             //fclose($p['pipes'][1]);
295             
296             proc_close($p['proc']);
297             
298             
299             //clearstatcache();
300             //if (file_exists('/proc/'.$p['pid'])) {
301             //    $pool[] = $p;
302             //    continue;
303             //}
304             echo "\nENDED: ({$p['pid']}) " .  $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
305             @unlink($p['out']);
306             //unlink($p['out']);
307         }
308         echo "POOL SIZE: ". count($pool) ."\n";
309         $this->pool = $pool;
310         if (count($pool) < 10) {
311             return true;
312         }
313         return false;
314         
315     }
316     /**
317      * see if pool is already trying to deliver to this domain.?
318      * -- if so it get's pushed to the end of the queue.
319      *
320      */
321     function poolHasDomain($email)
322     {
323         $dom = strtolower(array_pop(explode('@',$email)));
324         foreach($this->pool as $p) {
325             $mdom = strtolower(array_pop(explode('@',$p['email'])));
326             if ($mdom == $dom) {
327                 return true;
328             }
329         }
330         return false;
331         
332     }
333
334     function output()
335     {
336         die("Done\n");
337     }
338 }