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 = "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         //DB_DataObject::debugLevel(1);
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         $pushed = array();
135         while (true) {
136             if (empty($ar)) {
137                 break;
138             }
139             
140             
141             $p = array_shift($ar);
142             if (!$this->poolfree()) {
143                 array_unshift($ar,$p); /// put it back on..
144                 sleep(3);
145                 continue;
146             }
147             if ($this->poolHasDomain($p->person_id_email)) {
148                 if (in_array($p->person_id_email, $pushed)) {
149                     // it's been pushed to the end, and nothing has
150                     // been pushed since.
151                     // give up, let the next run sort it out.
152                     break;
153                 }
154                 
155                 $ar[] = $p; // push it on the end..
156                 
157                 $pushed[] = $p->person_id_email;
158                 
159                 echo "domain {$p->person_id_email} already on queue, pushing to end.\n";
160                 sleep(3);
161                 continue;
162             }
163             
164             
165             $this->run($p->id,$p->person_id_email);
166             $pushed = array();
167             
168         }
169         
170         // we should have a time limit here...
171         while(count($this->pool)) {
172             $this->poolfree();
173             sleep(3);
174         }
175         
176         die("DONE\n");
177     }
178     
179     function run($id, $email)
180     {
181        // phpinfo();exit;
182         $tn = tempnam(ini_get('session.save_path'),'stdout') . '.stdout';
183         $descriptorspec = array(
184             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
185             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
186             2 => array("pipe", "w") // stderr is a file to write to
187          );
188         $php = $_SERVER["_"];
189         $sn =  $_SERVER["SCRIPT_NAME"];
190         
191         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . $sn)); // same as run on.. (so script should end up being same relatively..)
192         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
193         if ($this->force) {
194             $app .= ' -f';
195         }
196         if (!empty($this->send_to)) {
197             $app .= ' --sent-to='.escapeshellarg($this->send_to);
198         }
199         $cmd = $php . ' ' . $app. ' &';
200         
201         echo $cmd . "\n";
202         $pipe = array();
203         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
204         $info =  proc_get_status($p);
205         $this->pool[] = array(
206                 'proc' => $p,
207                 'pid' => $info['pid'],
208                 'out' => $tn,
209                 'cmd' => $cmd,
210                 'email' => $email,
211                 'pipes' => $pipes
212             
213                 
214         );
215     }
216     
217     function poolfree()
218     {
219         $pool = array();
220         clearstatcache();
221         foreach($this->pool as $p) {
222              
223             //echo "CHECK PID: " . $p['pid'] . "\n";
224             $info =  proc_get_status($p['proc']);
225             //var_dump($info);
226             
227             // update if necessday.
228             if ($info['pid']) {
229                 $p['pid'] = $info['pid'];
230             }
231             
232             if ($info['running']) {
233             
234             //if (file_exists('/proc/'.$p['pid'])) {
235                 $pool[] = $p;
236                 continue;
237             }
238             
239             echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
240             //fclose($p['pipes'][1]);
241             fclose($p['pipes'][0]);
242             fclose($p['pipes'][2]);
243             proc_close($p['proc']);
244             
245             
246             clearstatcache();
247             if (file_exists('/proc/'.$p['pid'])) {
248                 $pool[] = $p;
249                 continue;
250             }
251             echo "ENDED: ({$p['pid']}) " .  $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
252             
253             //unlink($p['out']);
254         }
255         echo "POOL SIZE: ". count($pool) ."\n";
256         $this->pool = $pool;
257         if (count($pool) < 10) {
258             return true;
259         }
260         return false;
261         
262     }
263     /**
264      * see if pool is already trying to deliver to this domain.?
265      * -- if so it get's pushed to the end of the queue.
266      *
267      */
268     function poolHasDomain($email)
269     {
270         $dom = strtolower(array_pop(explode('@',$email)));
271         foreach($this->pool as $p) {
272             $mdom = strtolower(array_pop(explode('@',$p['email'])));
273             if ($mdom == $dom) {
274                 return true;
275             }
276         }
277         return false;
278         
279     }
280
281 }