fix #8131 - chinese translations
[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 seconds a child is allowed to run - defaut 2 minutes
101      */
102     var $maxruntime = 120;
103     
104     /**
105     * @var {Boolean} log_events - default true if events should be logged.
106     */
107     var $log_events = true;
108     /**
109     * @var {Number} try_again_minutes how long after failing to try again default = 30 if max runtime fails
110     */
111     var $try_again_minutes = 30;
112     
113     /**
114      * @var {String} table - the table that the class will query for notification events
115      */
116     var $table = 'core_notify';
117     /**
118      * @var {String} target - the application that will run for each Row in the table (eg. Pman/Core/NotifySend)
119      */
120     var $target = 'Core/NotifySend';
121     
122     
123     
124     var $evtype = ''; // any notification...
125                     // this script should only handle EMAIL notifications..
126     
127     var $server;  // core_notify_server
128     
129     var $poolname = 'core';
130     
131     var $opts; 
132     var $force = false;
133     
134     var $clear_interval = '1 WEEK'; // how long to clear the old queue of items.
135     
136     function getAuth()
137     {
138         $ff = HTML_FlexyFramework::get();
139         if (!$ff->cli) {
140             die("access denied");
141         }
142         HTML_FlexyFramework::ensureSingle($_SERVER["SCRIPT_NAME"] .'|'. __FILE__ .'|'. (empty($_SERVER['argv'][1]) ? '': $_SERVER['argv'][1]), $this);
143         return true;
144     }
145     
146     var $pool = array();
147     
148     function parseArgs(&$opts)
149     {
150         if ($opts['debug']) {
151             DB_DataObject::debugLevel($opts['debug']);
152             print_r($opts);
153         }
154         $this->opts = $opts;
155         if (!empty($opts['poolsize'])) {
156             $this->max_pool_size = $opts['poolsize'];
157         }
158         
159         if (empty($opts['limit'])) {
160             $opts['limit'] = '1000'; // not sure why it's not picking up the defautl..
161         }
162         
163         if (!empty($opts['old'])) {
164             $opts['list'] = 1; // force listing..
165         }
166         
167         $this->force = empty($opts['force']) ? 0 : 1;
168      
169         if (!empty($opts['send-to'])) {
170             $this->send_to = $opts['send-to'];
171         }
172     }
173     
174     var $queue = array();
175     var $domain_queue = array(); // false to use nextquee
176     var $next_queue = array();
177
178    
179     function get($r,$opts=array())    
180     {
181         
182        // if ($this->database_is_locked()) {
183         //    die("LATER - DATABASE IS LOCKED");
184         //}
185         
186         
187         $this->parseArgs($opts); 
188          
189         //date_default_timezone_set('UTC');
190         
191         
192         $this->generateNotifications();
193         
194          //DB_DataObject::debugLevel(1);
195         $w = DB_DataObject::factory($this->table);
196         $total = 0;
197         
198         
199         
200         $ff = HTML_FlexyFramework::get();
201         
202         
203         $this->server = DB_DataObject::Factory('core_notify_server')->getCurrent($this);
204         
205         $this->server->assignQueues($this);
206         
207         
208         $this->clearOld();
209         
210         
211         if (!empty($this->evtype)) {
212             $w->evtype = $this->evtype;
213         }
214         
215         $w->server_id = $this->server->id;
216
217         
218         if (!empty($opts['old'])) {
219             // show old and new...
220             
221             $w->orderBy('act_when DESC'); // latest first
222             $w->limit($opts['limit']); // we can run 
223             $total = min($w->count(), $opts['limit']);
224         } else {   
225             // standard
226             
227             //$w->whereAdd('act_when > sent'); // eg.. sent is not valid..
228             $w->whereAdd("sent < '1970-01-01' OR sent IS NULL"); // eg.. sent is not valid..
229             
230             $w->whereAdd('act_start > NOW() - INTERVAL 14 DAY'); // ignore the ones stuck in the queue
231             if (!$this->force) {
232                 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
233             }
234             
235     
236             $w->orderBy('act_when ASC'); // oldest first.
237             $total = min($w->count(), $opts['limit']);
238             $this->logecho("QUEUE is {$w->count()} only running " . ((int) $opts['limit']));
239             
240             $w->limit($opts['limit']); // we can run 1000 ...
241         }
242         
243         
244     
245         
246          
247         $w->autoJoin();
248         $total = $w->find();
249         
250         if (empty($total)) {
251             $this->logecho("Nothing In Queue - DONE");
252             exit;
253         }
254         
255         
256         if (!empty($opts['list'])) {
257             
258             
259             while ($w->fetch()) { 
260                 $o = $w->object();
261                 
262                 
263                 $this->logecho("{$w->id} : {$w->person()->email} email    : ".
264                         $o->toEventString()."    ". $w->status()  );
265             }
266             exit;
267         }
268         
269         //echo "BATCH SIZE: ".  count($ar) . "\n";
270        
271         
272         while (true) {
273             // only add if we don't have any queued up..
274             if (empty($this->queue) && $w->fetch()) {
275                 $this->queue[] = clone($w);
276                 $total--;
277             }
278           
279             $this->logecho("BATCH SIZE: Queue=".  count($this->queue) . " TOTAL = " . $total  );
280             
281             if (empty($this->queue)) {
282                 $this->logecho("COMPLETED MAIN QUEUE - running maxed out domains");
283                 if ($this->domain_queue !== false) {
284                     $this->queue  = $this->remainingDomainQueue();
285                      
286                     continue;
287                 }
288                 break; // nothing more in queue.. and no remaining one
289             }
290             
291             
292             $p = array_shift($this->queue);
293             if (!$this->poolfree()) {
294                 array_unshift($this->queue,$p); /// put it back on..
295                 sleep(3);
296                 continue;
297             }
298             // not sure what happesn if person email and to_email is empty!!?
299             $email = empty($p->to_email) ? ($p->person() ? $p->person()->email : $p->to_email) : $p->to_email;
300             
301             $black = $this->server->isBlacklisted($email);
302             if ($black !== false) {
303                 $this->logecho("Blacklisted - try giving it to next server");
304                 if (false === $this->server->updateNotifyToNextServer($p)) {
305                     $ev = $this->addEvent('NOTIFY', $p, 'BLACKLISTED  FROM our DB');
306                     // we dont have an althenative server to update it with.
307                     $this->logecho("Blacklisted - next server did not work - try again in 30 mins");
308                     $this->server->updateNotifyToNextServer($w,  date("Y-m-d H:i:s",  strtotime('NOW +  30 MINUTES')),true);
309                    // $this->errorHandler( $ev->remarks);
310                    
311                 }
312                 
313                 continue;
314             }
315              
316             
317             if ($this->poolHasDomain($email) > $this->max_to_domain) {
318                 
319                 // push it to a 'domain specific queue'
320                 $this->logecho("REQUEING - maxed out that domain - {$email}");
321                 $this->pushQueueDomain($p, $email);
322                    
323                 //sleep(3);
324                 continue;
325             }
326             
327             
328             $this->run($p->id,$email);
329             
330             
331             
332         }
333         $this->logecho("REQUEUING all emails that maxed out:" . count($this->next_queue));
334         if (!empty($this->next_queue)) {
335              
336             foreach($this->next_queue as $p) {
337                 if (false === $this->server->updateNotifyToNextServer($p)) {
338                     $p->updateState("????");
339                 }
340             }
341         }
342         
343         
344         $this->logecho("QUEUE COMPLETE - waiting for pool to end");
345         // we should have a time limit here...
346         while(count($this->pool)) {
347             $this->poolfree();
348             sleep(3);
349         }
350          
351         
352         
353         
354         $this->logecho("DONE");
355         exit;
356     }
357     
358     
359    
360     
361     // this sequentially distributes requeued emails.. - to other servers. (can exclude current one if we have that flagged.)
362      
363   
364     
365     function generateNotifications()
366     {
367         // this should check each module for 'GenerateNotifications.php' class..
368         //and run it if found..
369         $ff = HTML_FlexyFramework::get();
370        
371         $disabled = explode(',', $ff->disable);
372
373         $modules = array_reverse($this->modulesList());
374         
375         // move 'project' one to the end...
376         
377         foreach ($modules as $module){
378             if(in_array($module, $disabled)){
379                 continue;
380             }
381             $file = $this->rootDir. "/Pman/$module/GenerateNotifications.php";
382             if(!file_exists($file)){
383                 continue;
384             }
385             
386             require_once $file;
387             $class = "Pman_{$module}_GenerateNotifications";
388             $x = new $class;
389             if(!method_exists($x, 'generate')){
390                 continue;
391             };
392             //echo "$module\n";
393             $x->generate($this);
394         }
395                 
396     
397     }
398     
399      
400     
401     function run($id, $email='', $cmdOpts="")
402     {
403         
404         static $renice = false;
405         if (!$renice) {
406             require_once 'System.php';
407             $renice = System::which('renice');
408         }
409         
410         // phpinfo();exit;
411         
412         
413         $tn =  $this->tempName('stdout', true);
414         $tne =  $this->tempName('stderr', true);
415         $descriptorspec = array(
416             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
417             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
418             2 => array("file", $tne, 'w'),   // stderr is a file to write to
419           //  2 => array("pipe", "w") // stderr is a file to write to
420          );
421         
422         static $php = false;
423         if (!$php) {
424             require_once 'System.php';
425             $php = System::which('php');
426         }
427         
428         $sn =  $_SERVER["SCRIPT_NAME"];
429         
430         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
431         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
432         if ($this->force) {
433             $app .= ' -f';
434         }
435         if (!empty($this->send_to)) {
436             $app .= ' --sent-to='.escapeshellarg($this->send_to);
437         }
438         $cmd = 'exec ' . $php . ' ' . $app . ' ' . $cmdOpts; //. ' &';
439         
440        
441         $pipe = array();
442         //$this->logecho("call proc_open $cmd");
443         
444         
445         if ($this->max_pool_size === 1) {
446             $this->logecho("call passthru [{$email}] $cmd");
447             passthru($cmd);
448             return;
449         }
450         
451         
452         if (!empty($this->opts['dryrun'])) {
453             $this->logecho("DRY RUN");
454             return;
455         }
456         
457         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
458         $info =  proc_get_status($p);
459         
460         if ($this->nice_level !== false) { 
461             $rcmd = "$renice {$this->nice_level} {$info['pid']}";
462             `$rcmd`;
463         } 
464         $this->pool[] = array(
465                 'proc' => $p,
466                 'pid' => $info['pid'],
467                 'out' => $tn,
468                 'oute' => $tne,
469                 'cmd' => $cmd,
470                 'email' => $email,
471                 'pipes' => $pipes,
472                 'notify_id' => $id,
473                 'started' => time()
474             
475                 
476         );
477         $this->logecho("RUN [{$email}] ({$info['pid']}) $cmd ");
478     }
479     
480     function poolfree()
481     {
482         $pool = array();
483         clearstatcache();
484          
485         foreach($this->pool as $p) {
486              
487             //echo "CHECK PID: " . $p['pid'] . "\n";
488             
489             
490             $info =  proc_get_status($p['proc']);
491             //var_dump($info);
492             
493             // update if necessday.
494             if ($info['pid'] && $p['pid'] != $info['pid']) {
495                 $this->logecho("CHANING PID FROM " . $p['pid']  .  "  TO ". $info['pid']);
496                 $p['pid'] = $info['pid'];
497             }
498             
499             //echo @file_get_contents('/proc/'. $p['pid'] .'/cmdline') . "\n";
500             
501             if ($info['running']) {
502             
503                 //if (file_exists('/proc/'.$p['pid'])) {
504                 $runtime = time() - $p['started'];
505                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
506                 if ($runtime > $this->maxruntime) {
507                     
508                     proc_terminate($p['proc'], 9);
509                     //fclose($p['pipes'][1]);
510                     fclose($p['pipes'][0]);
511                     
512                     $this->logecho("TERMINATING: ({$p['pid']}) {$p['email']} " . $p['cmd'] . " : " . file_get_contents($p['out']) . " : " . file_get_contents($p['oute']));
513                     @unlink($p['out']);
514                     @unlink($p['oute']);
515                     
516                     // schedule again
517                     $w = DB_DataObject::factory($this->table);
518                     $w->get($p['notify_id']);
519                     $ww = clone($w);
520                     if ($this->log_events) {
521                         $this->addEvent('NOTIFY', $w, 'TERMINATED - TIMEOUT');
522                     }
523                     $w->act_when = date('Y-m-d H:i:s', strtotime("NOW + {$this->try_again_minutes} MINUTES"));
524                     $w->update($ww);
525                     
526                     continue;
527                 }
528                 
529                 $pool[] = $p;
530                 continue;
531             }
532             fclose($p['pipes'][0]);
533             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
534             //fclose($p['pipes'][1]);
535             
536             proc_close($p['proc']);
537              sleep(1);
538             clearstatcache();
539             if (file_exists('/proc/'. $p['pid'])) {
540                 $this->logecho("proc PID={$p['pid']} still here - trying to wait");
541                 pcntl_waitpid($p['pid'], $status, WNOHANG);
542             }
543
544             //clearstatcache();
545             //if (file_exists('/proc/'.$p['pid'])) {
546             //    $pool[] = $p;
547             //    continue;
548             //}
549             $this->logecho("ENDED: ({$p['pid']}) {$p['email']} " .  $p['cmd'] . " : " . file_get_contents($p['out']) . " : " . file_get_contents($p['oute']));
550             @unlink($p['out']);
551             @unlink($p['oute']);
552             // at this point we could pop onto the queue the 
553             $this->popQueueDomain($p['email']);
554             
555             //unlink($p['out']);
556         }
557         $this->logecho("POOL SIZE: ". count($pool) );
558         $this->pool = $pool;
559         if (count($pool) < $this->max_pool_size) {
560             return true;
561         }
562         return false;
563         
564     }
565     /**
566      * see if pool is already trying to deliver to this domain.?
567      * -- if so it get's pushed to the end of the queue.
568      *
569      */
570     function poolHasDomain($email)
571     {
572         $ret = 0;
573         $ea = explode('@',$email);
574         $dom = strtolower(array_pop($ea));
575         foreach($this->pool as $p) {
576             $ea = explode('@',$p['email']);
577             $mdom = strtolower(array_pop($ea));
578             if ($mdom == $dom) {
579                 $ret++;
580             }
581         }
582         return $ret;
583         
584     }
585     function popQueueDomain($email)
586     {
587         $ea = explode('@',$email);
588         $dom = strtolower(array_pop($ea));
589         if (empty($this->domain_queue[$dom])) {
590             return;
591         }
592         array_unshift($this->queue, array_shift($this->domain_queue[$dom]));
593         
594     }
595     
596     function pushQueueDomain($e, $email)
597     {
598         if ($this->domain_queue === false) {
599             $this->next_queue[] = $e;
600             return;
601         }
602         
603         $ea = explode('@',$email);
604         $dom = strtolower(array_pop($ea));
605         if (!isset($this->domain_queue[$dom])) {
606             $this->domain_queue[$dom] = array();
607         }
608         $this->domain_queue[$dom][] = $e;
609     }
610     function remainingDomainQueue()
611     {
612         $ret = array();
613         foreach($this->domain_queue as $dom => $ar) {
614             $ret = array_merge($ret, $ar);
615         }
616         $this->domain_queue = false;
617         return $ret;
618     }
619     function clearOld()
620      {
621           if ($this->server->isFirstServer()) {
622             
623             $p = DB_DataObject::factory($this->table);
624             $p->whereAdd("
625                 sent < '2000-01-01'
626                 and
627                 event_id = 0
628                 and
629                 act_start < NOW() - INTERVAL {$this->clear_interval}
630             ");
631            // $p->limit(1000);
632             if ($p->count()) {
633                 $ev = $this->addEvent('NOTIFY', false, "RETRY TIME EXCEEDED");
634                 $p = DB_DataObject::factory($this->table);
635                 $p->query("
636                     UPDATE
637                         {$this->table}
638                     SET
639                         sent = NOW(),
640                         msgid = '',
641                         event_id = {$ev->id}
642                     WHERE
643                         sent < '2000-01-01'
644                         and
645                         event_id = 0
646                         and
647                         act_start < NOW() - INTERVAL {$this->clear_interval}
648                     LIMIT
649                         1000
650                 ");
651                 
652             }
653         }
654      }
655     
656
657     function output()
658     {
659         $this->logecho("DONE");
660         exit;
661     }
662     function logecho($str)
663     {
664         echo date("Y-m-d H:i:s - ") . $str . "\n";
665     }
666 }