Notify.php
[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          'limit' => array(
67             'desc' => 'Limit search for no. to send to ',
68             'default' => 50,
69             'short' => 'L',
70             'min' => 0,
71             'max' => 999,
72         ),
73           'limit' => array(
74             'desc' => 'Dry run - do not send.',
75             'default' => -,
76             'short' => 'D',
77             'min' => 0,
78             'max' => 0,
79         ),
80     );
81     
82     var $max_pool_size = 10;
83     
84     var $table = 'core_notify';
85     var $target = 'Core/NotifySend';
86     var $evtype = ''; // any notification...
87                     // this script should only handle EMAIL notifications..
88     var $force = false;
89     function getAuth()
90     {
91         $ff = HTML_FlexyFramework::get();
92         if (!$ff->cli) {
93             die("access denied");
94         }
95         HTML_FlexyFramework::ensureSingle(__FILE__, $this);
96         return true;
97         
98     }
99     
100     var $pool = array();
101     
102     function get($r,$opts)    
103     {
104         if ($opts['debug']) {
105             DB_DataObject::debugLevel($opts['debug']);
106             print_r($opts);
107         }
108         //date_default_timezone_set('UTC');
109        // phpinfo();exit;
110         $showold = !empty($opts['old']);
111         if (!empty($opts['old'])) {
112             $opts['list'] = 1; // force listing..
113         }
114         
115         $this->force = empty($opts['force']) ? 0 : 1;
116      
117         if (!empty($opts['send-to'])) {
118             $this->send_to = $opts['send-to'];
119         }
120      
121         
122         $w = DB_DataObject::factory('core_notify_recur');
123         if (is_a($w, 'DB_DataObject')) {
124             $w->generateNotifications();
125         }
126         if (!empty($opts['generate'])) {
127             $w = DB_DataObject::factory($opts['generate']);
128             if (is_a($w, 'DB_DataObject')) {
129                 $w->generateNotifications();
130             }
131             exit;
132             
133             
134         }
135      
136         //DB_DataObject::debugLevel(1);
137         $w = DB_DataObject::factory($this->table);
138         
139         if (!$showold) {
140             
141             // standard
142             
143             //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
144             $w->whereAdd("sent < '1970-01-01'"); // eg.. sent is not valid..
145             
146             $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
147             if (!$this->force) {
148                 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
149             }
150     
151             $w->orderBy('act_when ASC'); // oldest first.
152             $w->limit(1000); // we can run 1000 ...
153         } else {
154             $w->orderBy('act_when DESC'); // latest first
155             $w->limit(50); // we can run 1000 ...
156         }
157         if (!empty($this->evtype)) {
158             $w->evtype = $this->evtype;
159         }
160         
161         $w->autoJoin();
162         
163         
164         $ar = $w->fetchAll();
165         
166         if (!empty($opts['list'])) {
167             if (empty($ar)) {
168                 die("Nothing in Queue\n");
169             }
170             foreach($ar as $w) {
171                 $o = $w->object();
172                 
173                 
174                 echo "$w->id : $w->person_id_email email    : ".
175                         $o->toEventString()."    ". $w->status() . "\n";
176             }
177             exit;
178         }
179         
180         
181         $pushed = array();
182         while (true) {
183             if (empty($ar)) {
184                 break;
185             }
186             
187             
188             $p = array_shift($ar);
189             if (!$this->poolfree()) {
190                 array_unshift($ar,$p); /// put it back on..
191                 sleep(1);
192                 continue;
193             }
194             if ($this->poolHasDomain($p->person_id_email)) {
195                 if (in_array($p->person_id_email, $pushed)) {
196                     // it's been pushed to the end, and nothing has
197                     // been pushed since.s
198                     // give up, let the next run sort it out.
199                     break;
200                 }
201                 
202                 $ar[] = $p; // push it on the end..
203                 
204                 $pushed[] = $p->person_id_email;
205                 
206                 echo "domain {$p->person_id_email} already on queue, pushing to end.\n";
207                 //sleep(3);
208                 continue;
209             }
210             
211             
212             $this->run($p->id,$p->person_id_email);
213             
214             
215             
216             $pushed = array();
217             
218         }
219         
220         // we should have a time limit here...
221         while(count($this->pool)) {
222             $this->poolfree();
223              sleep(1);
224         }
225         
226         die("DONE\n");
227     }
228     
229     function run($id, $email, $cmdOpts="")
230     {
231        // phpinfo();exit;
232         $tn = tempnam(ini_get('session.save_path'),'stdout') . '.stdout';
233         $descriptorspec = array(
234             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
235             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
236             2 => array("pipe", "w") // stderr is a file to write to
237          );
238         $php = $_SERVER["_"];
239         $sn =  $_SERVER["SCRIPT_NAME"];
240         
241         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
242         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
243         if ($this->force) {
244             $app .= ' -f';
245         }
246         if (!empty($this->send_to)) {
247             $app .= ' --sent-to='.escapeshellarg($this->send_to);
248         }
249         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
250         
251        
252         $pipe = array();
253         echo "call proc_open $cmd\n";
254         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
255         $info =  proc_get_status($p);
256         $this->pool[] = array(
257                 'proc' => $p,
258                 'pid' => $info['pid'],
259                 'out' => $tn,
260                 'cmd' => $cmd,
261                 'email' => $email,
262                 'pipes' => $pipes,
263                 'started' => time()
264             
265                 
266         );
267         echo "RUN ({$info['pid']}) $cmd  \n";
268     }
269     
270     function poolfree()
271     {
272         $pool = array();
273         clearstatcache();
274         $maxruntime = 2 * 60; // 2 minutes.. ?? should be long enoguh
275         
276         foreach($this->pool as $p) {
277              
278             //echo "CHECK PID: " . $p['pid'] . "\n";
279             $info =  proc_get_status($p['proc']);
280             //var_dump($info);
281             
282             // update if necessday.
283             if ($info['pid']) {
284                 echo "CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']. "\n";
285                 $p['pid'] = $info['pid'];
286             }
287             
288             echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
289             
290             if ($info['running']) {
291             
292                 //if (file_exists('/proc/'.$p['pid'])) {
293                 $runtime = time() - $p['started'];
294                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
295                 if ($runtime > $maxruntime) {
296                     
297                     proc_terminate($p['proc'], 9);
298                     //fclose($p['pipes'][1]);
299                     fclose($p['pipes'][0]);
300                     fclose($p['pipes'][2]);
301                     echo "\nTERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
302                     @unlink($p['out']);
303                     
304                     continue;
305                 }
306                 
307                 $pool[] = $p;
308                 continue;
309             }
310             fclose($p['pipes'][0]);
311             fclose($p['pipes'][2]);
312             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
313             //fclose($p['pipes'][1]);
314             
315             proc_close($p['proc']);
316             
317             
318             //clearstatcache();
319             //if (file_exists('/proc/'.$p['pid'])) {
320             //    $pool[] = $p;
321             //    continue;
322             //}
323             echo "\nENDED: ({$p['pid']}) " .  $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
324             @unlink($p['out']);
325             //unlink($p['out']);
326         }
327         echo "POOL SIZE: ". count($pool) ."\n";
328         $this->pool = $pool;
329         if (count($pool) < $this->max_pool_size) {
330             return true;
331         }
332         return false;
333         
334     }
335     /**
336      * see if pool is already trying to deliver to this domain.?
337      * -- if so it get's pushed to the end of the queue.
338      *
339      */
340     function poolHasDomain($email)
341     {
342         $dom = strtolower(array_pop(explode('@',$email)));
343         foreach($this->pool as $p) {
344             $mdom = strtolower(array_pop(explode('@',$p['email'])));
345             if ($mdom == $dom) {
346                 return true;
347             }
348         }
349         return false;
350         
351     }
352
353     function output()
354     {
355         die("Done\n");
356     }
357 }