PHP7 fix
[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.. (and new 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        /* removed - use GenerateNotifcations.php hooked classes
60          'generate' =>  'Generate notifications for a table, eg. cash_invoice',
61             
62         ),
63         */
64          'limit' => array(
65             'desc' => 'Limit search for no. to send to ',
66             'default' => 1000,
67             'short' => 'L',
68             'min' => 0,
69             'max' => 999,
70         ),
71         'dryrun' => array(
72             'desc' => 'Dry run - do not send.',
73             'default' => 0,
74             'short' => 'D',
75             'min' => 0,
76             'max' => 0,
77         ),
78         'poolsize' => array(
79             'desc' => 'Pool size',
80             'default' => 10,
81             'short' => 'P',
82             'min' => 0,
83             'max' => 100,
84         ),
85     );
86     /**
87      * @var $nice_level Unix 'nice' level to stop it jamming server up.
88      */
89     var $nice_level = false;
90     /**
91      * @var $max_pool_size maximum runners to start at once.
92      */
93     var $max_pool_size = 10;
94     /**
95      * @var $max_to_domain maximum connections to make to a single domain
96      */
97     var $max_to_domain = 10;
98     
99     /**
100      * @var $maxruntime - maximum time a child is allowed to run - defaut 2 minutes
101      */
102     var $maxruntime = 120;
103     
104     var $table = 'core_notify';
105     var $target = 'Core/NotifySend';
106     var $evtype = ''; // any notification...
107                     // this script should only handle EMAIL notifications..
108     var $force = false;
109     function getAuth()
110     {
111         $ff = HTML_FlexyFramework::get();
112         if (!$ff->cli) {
113             die("access denied");
114         }
115         HTML_FlexyFramework::ensureSingle($_SERVER["SCRIPT_NAME"] .'|'. __FILE__, $this);
116         return true;
117     }
118     
119     var $pool = array();
120     
121     function parseArgs(&$opts)
122     {
123         if ($opts['debug']) {
124             DB_DataObject::debugLevel($opts['debug']);
125             print_r($opts);
126         }
127         $this->opts = $opts;
128         if (!empty($opts['poolsize'])) {
129             $this->max_pool_size = $opts['poolsize'];
130         }
131         
132         if (empty($opts['limit'])) {
133             $opts['limit'] = '1000'; // not sure why it's not picking up the defautl..
134         }
135         
136         if (!empty($opts['old'])) {
137             $opts['list'] = 1; // force listing..
138         }
139         
140         $this->force = empty($opts['force']) ? 0 : 1;
141      
142         if (!empty($opts['send-to'])) {
143             $this->send_to = $opts['send-to'];
144         }
145     }
146     
147     
148     function get($r,$opts=array())    
149     {
150         $this->parseArgs($opts); 
151          
152         //date_default_timezone_set('UTC');
153         
154         
155         $this->generateNotifications();
156         
157          
158         //DB_DataObject::debugLevel(1);
159         $w = DB_DataObject::factory($this->table);
160         $total = 0;
161         
162         if (!empty($opts['old'])) {
163             // show old and new...
164             
165             $w->orderBy('act_when DESC'); // latest first
166             $w->limit($opts['limit']); // we can run 
167             $total = min($w->count(), $opts['limit']);
168         } else {   
169             // standard
170             
171             //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
172             $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
173             
174             $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
175             if (!$this->force) {
176                 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
177             }
178     
179             $w->orderBy('act_when ASC'); // oldest first.
180             $total = min($w->count(), $opts['limit']);
181             $this->logecho("QUEUE is {$w->count()} only running " . ((int) $opts['limit']));
182             
183             $w->limit($opts['limit']); // we can run 1000 ...
184         }
185         
186         if (!empty($this->evtype)) {
187             $w->evtype = $this->evtype;
188         }
189         
190         $w->autoJoin();
191         $w->find();
192         
193         $ar = array(); // $w->fetchAll();
194         
195         if (!empty($opts['list'])) {
196             
197             
198             while ($w->fetch()) { 
199                 $o = $w->object();
200                 
201                 
202                 $this->logecho("{$w->id} : {$w->person()->email} email    : ".
203                         $o->toEventString()."    ". $w->status()  );
204             }
205             exit;
206         }
207         
208         //echo "BATCH SIZE: ".  count($ar) . "\n";
209         $pushed = array();
210         $requeue = array();
211         while (true) {
212             if ($w->fetch()) {
213                 $ar[] = clone($w);
214                 $total--;
215             }
216             
217             $this->logecho("BATCH SIZE: ".  (count($ar) + $total) );
218             
219             if (empty($ar)) {
220                 $this->logecho("COMPLETED MAIN QUEUE - running deleted");
221                 
222                 if (empty($pushed)) {
223                     break;
224                 }
225                 $ar = $pushed;
226                 $pushed = false;
227                 continue;
228             }
229             
230             
231             $p = array_shift($ar);
232             if (!$this->poolfree()) {
233                 array_unshift($ar,$p); /// put it back on..
234                 sleep(3);
235                 continue;
236             }
237             $email = $p->person() ? $p->person()->email : $p->to_email;
238             
239             if ($this->poolHasDomain($email) > $this->max_to_domain) {
240                 
241                 if ($pushed === false) {
242                     // we only try once to requeue..
243                     $requeue[] = $p;
244                     continue;
245                 }
246                 $pushed[] = $p;
247                 
248                 
249                 //sleep(3);
250                 continue;
251             }
252             
253             
254             $this->run($p->id,$email);
255             
256             
257             
258         }
259         
260         // we should have a time limit here...
261         while(count($this->pool)) {
262             $this->poolfree();
263              sleep(3);
264         }
265          
266         foreach($requeue as $p) {
267             $pp = clone($p);
268             $p->act_when = $p->sqlValue('NOW + INTERVAL 1 MINUTE');
269             $p->update($pp);
270             
271         }
272         
273         
274         $this->logecho("DONE");
275         exit;
276     }
277     
278     function generateNotifications()
279     {
280         // this should check each module for 'GenerateNotifications.php' class..
281         //and run it if found..
282         $ff = HTML_FlexyFramework::get();
283        
284         $disabled = explode(',', $ff->disable);
285
286         $modules = array_reverse($this->modulesList());
287         
288         // move 'project' one to the end...
289         
290         foreach ($modules as $module){
291             if(in_array($module, $disabled)){
292                 continue;
293             }
294             $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
295             if(!file_exists($file)){
296                 continue;
297             }
298             
299             require_once $file;
300             $class = "Pman_{$module}_GenerateNotifications";
301             $x = new $class;
302             if(!method_exists($x, 'generate')){
303                 continue;
304             };
305             //echo "$module\n";
306             $x->generate($this);
307         }
308                 
309     
310     }
311     
312     
313     
314     function run($id, $email, $cmdOpts="")
315     {
316         
317         static $renice = false;
318         if (!$renice) {
319             require_once 'System.php';
320             $renice = System::which('renice');
321         }
322         
323         // phpinfo();exit;
324         $tnx = tempnam(ini_get('session.save_path'),'stdout');
325         unlink($tnx);
326         $tn =  $tnx . '.stdout';
327         $descriptorspec = array(
328             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
329             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
330             2 => array("pipe", "w") // stderr is a file to write to
331          );
332         
333         static $php = false;
334         if (!$php) {
335             require_once 'System.php';
336             $php = System::which('php');
337         }
338         
339         $sn =  $_SERVER["SCRIPT_NAME"];
340         
341         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
342         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
343         if ($this->force) {
344             $app .= ' -f';
345         }
346         if (!empty($this->send_to)) {
347             $app .= ' --sent-to='.escapeshellarg($this->send_to);
348         }
349         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
350         
351        
352         $pipe = array();
353         $this->logecho("call proc_open $cmd");
354         
355         
356         if ($this->max_pool_size === 1) {
357             passthru($cmd);
358             return;
359         }
360         
361         
362         if (!empty($this->opts['dryrun'])) {
363             $this->logecho("DRY RUN");
364             return;
365         }
366         
367         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
368         $info =  proc_get_status($p);
369         
370         if ($this->nice_level !== false) { 
371             $rcmd = "$renice {$this->nice_level} {$info['pid']}";
372             `$rcmd`;
373         } 
374         $this->pool[] = array(
375                 'proc' => $p,
376                 'pid' => $info['pid'],
377                 'out' => $tn,
378                 'cmd' => $cmd,
379                 'email' => $email,
380                 'pipes' => $pipes,
381                 'notify_id' => $id,
382                 'started' => time()
383             
384                 
385         );
386         $this->logecho("RUN ({$info['pid']}) $cmd ");
387     }
388     
389     function poolfree()
390     {
391         $pool = array();
392         clearstatcache();
393          
394         foreach($this->pool as $p) {
395              
396             //echo "CHECK PID: " . $p['pid'] . "\n";
397             $info =  proc_get_status($p['proc']);
398             //var_dump($info);
399             
400             // update if necessday.
401             if ($info['pid'] && $p['pid'] != $info['pid']) {
402                 $this->logecho("CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']);
403                 $p['pid'] = $info['pid'];
404             }
405             
406             //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
407             
408             if ($info['running']) {
409             
410                 //if (file_exists('/proc/'.$p['pid'])) {
411                 $runtime = time() - $p['started'];
412                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
413                 if ($runtime > $this->maxruntime) {
414                     
415                     proc_terminate($p['proc'], 9);
416                     //fclose($p['pipes'][1]);
417                     fclose($p['pipes'][0]);
418                     fclose($p['pipes'][2]);
419                     $this->logecho("TERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']));
420                     @unlink($p['out']);
421                     
422                     $w = DB_DataObject::factory($this->table);
423                     $w->get($p['notify_id']);
424                     $ww = clone($w);
425                     $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
426                     $w->act_when = date('Y-m-d H:i:s', strtotime('NOW + 30  MINUTES'));
427                     $w->update($ww);
428                     
429                     
430                     continue;
431                 }
432                 
433                 $pool[] = $p;
434                 continue;
435             }
436             fclose($p['pipes'][0]);
437             fclose($p['pipes'][2]);
438             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
439             //fclose($p['pipes'][1]);
440             
441             proc_close($p['proc']);
442             
443             
444             //clearstatcache();
445             //if (file_exists('/proc/'.$p['pid'])) {
446             //    $pool[] = $p;
447             //    continue;
448             //}
449             $this->logecho("ENDED: ({$p['pid']}) " .  $p['cmd'] . " : " . file_get_contents($p['out']) );
450             @unlink($p['out']);
451             //unlink($p['out']);
452         }
453         $this->logecho("POOL SIZE: ". count($pool) );
454         $this->pool = $pool;
455         if (count($pool) < $this->max_pool_size) {
456             return true;
457         }
458         return false;
459         
460     }
461     /**
462      * see if pool is already trying to deliver to this domain.?
463      * -- if so it get's pushed to the end of the queue.
464      *
465      */
466     function poolHasDomain($email)
467     {
468         $ret = 0;
469         $dom = strtolower(array_pop(explode('@',$email)));
470         foreach($this->pool as $p) {
471             $mdom = strtolower(array_pop(explode('@',$p['email'])));
472             if ($mdom == $dom) {
473                 $ret++;
474             }
475         }
476         return $ret;
477         
478     }
479
480     function output()
481     {
482         $this->logecho("DONE");
483         exit;
484     }
485     function logecho($str)
486     {
487         echo date("Y-m-d H:i:s - ") . $str . "\n";
488     }
489 }