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         $w = DB_DataObject::factory('core_notify_recur');
95         $w->generateNotifications();
96         
97         //DB_DataObject::debugLevel(1);
98         $w = DB_DataObject::factory($this->table);
99         
100         if (!$showold) {
101             $w->whereAdd('act_when > sent'); // eg.. sent is not valid..
102             
103             if (!$this->force) {
104                 $w->whereAdd('act_when < NOW()'); // eg.. not if future..
105             }
106     
107             $w->orderBy('act_when ASC'); // oldest first.
108             $w->limit(1000); // we can run 1000 ...
109         } else {
110             $w->orderBy('act_when DESC'); // latest first
111             $w->limit(50); // we can run 1000 ...
112         }
113         if (!empty($this->evtype)) {
114             $w->evtype = $this->evtype;
115         }
116         
117         $w->autoJoin();
118         
119         
120         $ar = $w->fetchAll();
121         
122         if (!empty($opts['list'])) {
123             if (empty($ar)) {
124                 die("Nothing in Queue\n");
125             }
126             foreach($ar as $w) {
127                 $o = $w->object();
128                 
129                 
130                 echo "$w->id : $w->person_id_email email    : ".
131                         $o->toEventString()."    ". $w->status() . "\n";
132             }
133             exit;
134         }
135         
136         
137         $pushed = array();
138         while (true) {
139             if (empty($ar)) {
140                 break;
141             }
142             
143             
144             $p = array_shift($ar);
145             if (!$this->poolfree()) {
146                 array_unshift($ar,$p); /// put it back on..
147                 sleep(3);
148                 continue;
149             }
150             if ($this->poolHasDomain($p->person_id_email)) {
151                 if (in_array($p->person_id_email, $pushed)) {
152                     // it's been pushed to the end, and nothing has
153                     // been pushed since.
154                     // give up, let the next run sort it out.
155                     break;
156                 }
157                 
158                 $ar[] = $p; // push it on the end..
159                 
160                 $pushed[] = $p->person_id_email;
161                 
162                 echo "domain {$p->person_id_email} already on queue, pushing to end.\n";
163                 sleep(3);
164                 continue;
165             }
166             
167             
168             $this->run($p->id,$p->person_id_email);
169             $pushed = array();
170             
171         }
172         
173         // we should have a time limit here...
174         while(count($this->pool)) {
175             $this->poolfree();
176             sleep(3);
177         }
178         
179         die("DONE\n");
180     }
181     
182     function run($id, $email)
183     {
184        // phpinfo();exit;
185         $tn = tempnam(ini_get('session.save_path'),'stdout') . '.stdout';
186         $descriptorspec = array(
187             0 => array("pipe", 'r'),  // stdin is a pipe that the child will read from
188             1 => array("file", $tn, 'w'),  // stdout is a pipe that the child will write to
189             2 => array("pipe", "w") // stderr is a file to write to
190          );
191         $php = $_SERVER["_"];
192         $sn =  $_SERVER["SCRIPT_NAME"];
193         
194         $cwd = $sn[0] == '/' ? dirname($sn) : dirname(realpath(getcwd() . '/'. $sn)); // same as run on.. (so script should end up being same relatively..)
195         $app = $cwd . '/' . basename($_SERVER["SCRIPT_NAME"]) . '  ' . $this->target . '/'. $id;
196         if ($this->force) {
197             $app .= ' -f';
198         }
199         if (!empty($this->send_to)) {
200             $app .= ' --sent-to='.escapeshellarg($this->send_to);
201         }
202         $cmd = $php . ' ' . $app; //. ' &';
203         
204        
205         $pipe = array();
206         echo "call proc_open $cmd\n";
207         $p = proc_open($cmd, $descriptorspec, $pipes, $cwd );
208         $info =  proc_get_status($p);
209         $this->pool[] = array(
210                 'proc' => $p,
211                 'pid' => $info['pid'],
212                 'out' => $tn,
213                 'cmd' => $cmd,
214                 'email' => $email,
215                 'pipes' => $pipes,
216                 'started' => time()
217             
218                 
219         );
220         echo "RUN ({$info['pid']}) $cmd  \n";
221     }
222     
223     function poolfree()
224     {
225         $pool = array();
226         clearstatcache();
227         $maxruntime = 2 * 60; // 2 minutes.. ?? should be long enoguh
228         
229         foreach($this->pool as $p) {
230              
231             //echo "CHECK PID: " . $p['pid'] . "\n";
232             $info =  proc_get_status($p['proc']);
233             //var_dump($info);
234             
235             // update if necessday.
236             if ($info['pid']) {
237                 $p['pid'] = $info['pid'];
238             }
239             
240             if ($info['running']) {
241             
242                 //if (file_exists('/proc/'.$p['pid'])) {
243                 $runtime = time() - $p['started'];
244                 //echo "RUNTIME ({$p['pid']}): $runtime\n";
245                 if ($runtime > $maxruntime) {
246                     
247                     proc_terminate($p['proc'], 9);
248                     //fclose($p['pipes'][1]);
249                     fclose($p['pipes'][0]);
250                     fclose($p['pipes'][2]);
251                     echo "TERMINATING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
252                     @unlink($p['out']);
253                     
254                     continue;
255                 }
256                 
257                 $pool[] = $p;
258                 continue;
259             }
260             fclose($p['pipes'][0]);
261             fclose($p['pipes'][2]);
262             //echo "CLOSING: ({$p['pid']}) " . $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
263             //fclose($p['pipes'][1]);
264             
265             proc_close($p['proc']);
266             
267             
268             //clearstatcache();
269             //if (file_exists('/proc/'.$p['pid'])) {
270             //    $pool[] = $p;
271             //    continue;
272             //}
273             echo "ENDED: ({$p['pid']}) " .  $p['cmd'] . " : " . file_get_contents($p['out']) . "\n";
274             @unlink($p['out']);
275             //unlink($p['out']);
276         }
277         echo "POOL SIZE: ". count($pool) ."\n";
278         $this->pool = $pool;
279         if (count($pool) < 10) {
280             return true;
281         }
282         return false;
283         
284     }
285     /**
286      * see if pool is already trying to deliver to this domain.?
287      * -- if so it get's pushed to the end of the queue.
288      *
289      */
290     function poolHasDomain($email)
291     {
292         $dom = strtolower(array_pop(explode('@',$email)));
293         foreach($this->pool as $p) {
294             $mdom = strtolower(array_pop(explode('@',$p['email'])));
295             if ($mdom == $dom) {
296                 return true;
297             }
298         }
299         return false;
300         
301     }
302
303 }