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     );
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("sent < '1970-01-01'"); // eg.. sent is not valid..
131             
132             $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
133             if (!$this->force) {
134                 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
135             }
136     
137             $w->orderBy('act_when ASC'); // oldest first.
138             $w->limit(1000); // we can run 1000 ...
139         } else {
140             $w->orderBy('act_when DESC'); // latest first
141             $w->limit(50); // we can run 1000 ...
142         }
143         if (!empty($this->evtype)) {
144             $w->evtype = $this->evtype;
145         }
146         
147         $w->autoJoin();
148         
149         
150         $ar = $w->fetchAll();
151         
152         if (!empty($opts['list'])) {
153             if (empty($ar)) {
154                 die("Nothing in Queue\n");
155             }
156             foreach($ar as $w) {
157                 $o = $w->object();
158                 
159                 
160                 echo "$w->id : $w->person_id_email email    : ".
161                         $o->toEventString()."    ". $w->status() . "\n";
162             }
163             exit;
164         }
165         
166         
167         $pushed = array();
168         while (true) {
169             if (empty($ar)) {
170                 break;
171             }
172             
173             
174             $p = array_shift($ar);
175             if (!$this->poolfree()) {
176                 array_unshift($ar,$p); /// put it back on..
177                 sleep(3);
178                 continue;
179             }
180             if ($this->poolHasDomain($p->person_id_email)) {
181                 if (in_array($p->person_id_email, $pushed)) {
182                     // it's been pushed to the end, and nothing has
183                     // been pushed since.
184                     // give up, let the next run sort it out.
185                     break;
186                 }
187                 
188                 $ar[] = $p; // push it on the end..
189                 
190                 $pushed[] = $p->person_id_email;
191                 
192                 echo "domain {$p->person_id_email} already on queue, pushing to end.\n";
193                 //sleep(3);
194                 continue;
195             }
196             
197             
198             $this->run($p->id,$p->person_id_email);
199             $pushed = array();
200             
201         }
202         
203         // we should have a time limit here...
204         while(count($this->pool)) {
205             $this->poolfree();
206             //sleep(3);
207         }
208         
209         die("DONE\n");
210     }
211     
212     function run($id, $email, $cmdOpts="")
213     {
214        // phpinfo();exit;
215         $tn = tempnam(ini_get('session.save_path'),'stdout') . '.stdout';
216         $descriptorspec = array(
217             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
218             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
219             2 => array("pipe", "w") // stderr is a file to write to
220          );
221         $php = $_SERVER["_"];
222         $sn =  $_SERVER["SCRIPT_NAME"];
223         
224         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
225         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
226         if ($this->force) {
227             $app .= ' -f';
228         }
229         if (!empty($this->send_to)) {
230             $app .= ' --sent-to='.escapeshellarg($this->send_to);
231         }
232         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
233         
234        
235         $pipe = array();
236         echo "call proc_open $cmd\n";
237         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
238         $info =  proc_get_status($p);
239         $this->pool[] = array(
240                 'proc' => $p,
241                 'pid' => $info['pid'],
242                 'out' => $tn,
243                 'cmd' => $cmd,
244                 'email' => $email,
245                 'pipes' => $pipes,
246                 'started' => time()
247             
248                 
249         );
250         echo "RUN ({$info['pid']}) $cmd  \n";
251     }
252     
253     function poolfree()
254     {
255         $pool = array();
256         clearstatcache();
257         $maxruntime = 2 * 60; // 2 minutes.. ?? should be long enoguh
258         
259         foreach($this->pool as $p) {
260              
261             //echo "CHECK PID: " . $p['pid'] . "\n";
262             $info =  proc_get_status($p['proc']);
263             //var_dump($info);
264             
265             // update if necessday.
266             if ($info['pid']) {
267                 echo "CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']. "\n";
268                 $p['pid'] = $info['pid'];
269             }
270             
271             echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
272             
273             if ($info['running']) {
274             
275                 //if (file_exists('/proc/'.$p['pid'])) {
276                 $runtime = time() - $p['started'];
277                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
278                 if ($runtime > $maxruntime) {
279                     
280                     proc_terminate($p['proc'], 9);
281                     //fclose($p['pipes'][1]);
282                     fclose($p['pipes'][0]);
283                     fclose($p['pipes'][2]);
284                     echo "\nTERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
285                     @unlink($p['out']);
286                     
287                     continue;
288                 }
289                 
290                 $pool[] = $p;
291                 continue;
292             }
293             fclose($p['pipes'][0]);
294             fclose($p['pipes'][2]);
295             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
296             //fclose($p['pipes'][1]);
297             
298             proc_close($p['proc']);
299             
300             
301             //clearstatcache();
302             //if (file_exists('/proc/'.$p['pid'])) {
303             //    $pool[] = $p;
304             //    continue;
305             //}
306             echo "\nENDED: ({$p['pid']}) " .  $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
307             @unlink($p['out']);
308             //unlink($p['out']);
309         }
310         echo "POOL SIZE: ". count($pool) ."\n";
311         $this->pool = $pool;
312         if (count($pool) < 10) {
313             return true;
314         }
315         return false;
316         
317     }
318     /**
319      * see if pool is already trying to deliver to this domain.?
320      * -- if so it get's pushed to the end of the queue.
321      *
322      */
323     function poolHasDomain($email)
324     {
325         $dom = strtolower(array_pop(explode('@',$email)));
326         foreach($this->pool as $p) {
327             $mdom = strtolower(array_pop(explode('@',$p['email'])));
328             if ($mdom == $dom) {
329                 return true;
330             }
331         }
332         return false;
333         
334     }
335
336     function output()
337     {
338         die("Done\n");
339     }
340 }