DataObjects/Core_event_audit.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 = "Send out notification emails (usually from cron)";
20     
21     static $cli_opts = array(
22         'debug' => array(
23             'desc' => 'Turn on debugging (see DataObjects debugLevel )',
24             'default' => 0,
25             'short' => 'v',
26             'min' => 1,
27             'max' => 1,
28             
29         ),
30         'list' => array(
31             'desc' => 'List message to send, do not send them..',
32             'default' => 0,
33             'short' => 'l',
34             'min' => 0,
35             'max' => 0,
36             
37         ),
38         'old' => array(
39             'desc' => 'Show old messages..',
40             'default' => 0,
41             'short' => 'o',
42             'min' => 0,
43             'max' => 0,
44             
45         ),
46          'force' => array(
47             'desc' => 'Force redelivery, even if it has been sent before or not queued...',
48             'default' => 0,
49             'short' => 'f',
50             'min' => 0,
51             'max' => 0,
52         ),
53     );
54     
55     
56     
57     var $table = 'core_notify';
58     var $target = 'Core/NotifySend';
59     var $evtype = ''; // any notification...
60                     // this script should only handle EMAIL notifications..
61     
62     function getAuth()
63     {
64         $ff = HTML_FlexyFramework::get();
65         if (!$ff->cli) {
66             die("access denied");
67         }
68         HTML_FlexyFramework::ensureSingle(__FILE__, $this);
69         return true;
70         
71     }
72     
73     var $pool = array();
74     
75     function get($r,$opts)    
76     {
77         if ($opts['debug']) {
78             DB_DataObject::debugLevel($opts['debug']);
79             print_r($opts);
80         }
81         //date_default_timezone_set('UTC');
82        // phpinfo();exit;
83         $showold = !empty($opts['old']);
84         if (!empty($opts['old'])) {
85             $opts['list'] = 1; // force listing..
86         }
87         
88         $this->force = empty($opts['force']) ? 0 : 1;
89      
90         if (!empty($opts['send-to'])) {
91             $this->send_to = $opts['send-to'];
92         }
93      
94         
95         $w = DB_DataObject::factory($this->table);
96         
97         if (!$showold) {
98             $w->whereAdd('act_when > sent'); // eg.. sent is not valid..
99             
100             if (!$this->force) {
101                 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
102             }
103     
104             $w->orderBy('act_when ASC'); // oldest first.
105             $w->limit(1000); // we can run 1000 ...
106         } else {
107             $w->orderBy('act_when DESC'); // latest first
108             $w->limit(50); // we can run 1000 ...
109         }
110         if (!empty($this->evtype)) {
111             $w->evtype = $this->evtype;
112         }
113         
114         $w->autoJoin();
115         
116         
117         $ar = $w->fetchAll();
118         
119         if (!empty($opts['list'])) {
120             if (empty($ar)) {
121                 die("Nothing in Queue\n");
122             }
123             foreach($ar as $w) {
124                 $o = $w->object();
125                 
126                 
127                 echo "$w->id : $w->person_id_email email    : ".
128                         $o->toEventString()."    ". $w->status() . "\n";
129             }
130             exit;
131         }
132         
133         
134         
135         while (true) {
136             if (empty($ar)) {
137                 break;
138             }
139             
140             $p = array_shift($ar);
141             if (!$this->poolfree()) {
142                 array_unshift($ar,$p); /// put it back on..
143                 sleep(3);
144                 continue;
145             }
146             if ($this->poolHasDomain($p->person_id_email)) {
147                 $ar[] = $p; // push it on the end..
148                 echo "domain {$p->person_id_email} already on queue, pushing to end.\n";
149                 sleep(3);
150                 continue;
151             }
152             
153             
154             $this->run($p->id,$p->person_id_email);
155         }
156         while(count($this->pool)) {
157             $this->poolfree();
158             sleep(3);
159         }
160         
161         die("DONE\n");
162     }
163     
164     function run($id, $email)
165     {
166        // phpinfo();exit;
167         $tn = tempnam(ini_get('session.save_path'),'stdout') . '.stdout';
168         $descriptorspec = array(
169             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
170             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
171             2 => array("pipe", "w") // stderr is a file to write to
172          );
173         $php = $_SERVER["_"];
174         $sn =  $_SERVER["SCRIPT_NAME"];
175         
176         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . $sn)); // same as run on.. (so script should end up being same relatively..)
177         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
178         if ($this->force) {
179             $app .= ' -f';
180         }
181         if (!empty($this->send_to)) {
182             $app .= ' --sent-to='.escapeshellarg($this->send_to);
183         }
184         $cmd = $php . ' ' . $app. ' &';
185         
186         echo $cmd . "\n";
187         $pipe = array();
188         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
189         $this->pool[] = array(
190                 'proc' => $p,
191                 'out' => $tn,
192                 'cmd' => $cmd,
193                 'email' => $email
194         );
195     }
196     
197     function poolfree()
198     {
199         $pool = array();
200         foreach($this->pool as $p) {
201             $ar = proc_get_status($p['proc']);
202            // print_r($p);
203             //print_r($ar);
204             if ($ar['running']) {
205                 $pool[] = $p;
206                 continue;
207             }
208             echo $p['cmd'] . " : " . file_get_contents($p['out']);
209             //unlink($p['out']);
210         }
211         $this->pool = $pool;
212         if (count($pool) < 10) {
213             return true;
214         }
215         return false;
216         
217     }
218     /**
219      * see if pool is already trying to deliver to this domain.?
220      * -- if so it get's pushed to the end of the queue.
221      *
222      */
223     function poolHasDomain($email)
224     {
225         $dom = strtolower(array_pop(explode('@',$email)));
226         foreach($this->pool as $p) {
227             $mdom = strtolower(array_pop(explode('@',$p['email'])));
228             if ($mdom == $dom) {
229                 return true;
230             }
231         }
232         return false;
233         
234     }
235
236 }