fix #8131 - chinese translations
[Pman.Core] / NotifySend.php
1 <?php
2 require_once 'Pman.php';
3
4 /**
5  * notification script sender - designed to be run by the Notify script - with many children running
6  * in parallel.
7  *
8  * called with an id of a core_notify element
9  *
10  * uses core_notify - to find an event to object and person.
11  *
12  * uses Events table to log failures
13  * 
14  * 
15  * calls $object->toEmail($person,$last_send, $notify) to generate an email struct with
16  *  array (
17  *      headers =>
18  *      recipients =>
19  *      body =>
20  *  )
21  *
22  *
23  * Note uses configuration
24  *
25  * Pman_Core_NotifySend[host] = 'localhost' << to override direct sending..
26  * Mail[helo] << helo host name
27  * Mail[socket_options] << any socket option.
28  */
29 class Pman_Core_NotifySend_Exception_Success extends Exception {}
30 class Pman_Core_NotifySend_Exception_Fail extends Exception {}
31
32
33 class Pman_Core_NotifySend extends Pman
34 {
35     static $cli_desc = "Send out single notification email (usually called from  Core/Notify)";
36     
37     static $cli_opts = array(
38         'debug' => array(
39             'desc' => 'Turn on debugging (see DataObjects debugLevel )',
40             'default' => 0,
41             'short' => 'v',
42             'min' => 0,
43             'max' => 0,
44             
45         ),
46         'DB_DataObject-debug' => array(
47             'desc' => 'Turn on debugging (see DataObjects debugLevel )',
48             'default' => 0,
49             'short' => 'd',
50             'min' => 1,
51             'max' => 1,
52             
53         ),
54         'force' => array(
55             'desc' => 'Force redelivery, even if it has been sent before or not queued...',
56             'default' => 0,
57             'short' => 'f',
58             'min' => 0,
59             'max' => 0,
60         ),
61         'send-to' => array(
62             'desc' => 'Send the message to this address, rather than the one listed.',
63             'default' => '',
64             'short' => 't',
65             'min' => 0,
66             'max' => 1,
67         )
68         
69         
70         
71     );
72     var $table = 'core_notify';
73     var $error_handler = 'die';
74     var $poolname = 'core';
75     var $server; // core_notify_server
76     
77     function getAuth()
78     {
79         $ff = HTML_FlexyFramework::get();
80         if (!$ff->cli) {
81             $this->errorHandler("access denied");
82         }
83         //HTML_FlexyFramework::ensureSingle(__FILE__, $this);
84         return true;
85         
86     }
87    
88     function get($id,$opts=array())
89     {
90
91         //print_r($opts);
92         if (!empty($opts['DB_DataObject-debug'])) {
93             DB_DataObject::debugLevel($opts['DB_DataObject-debug']);
94         }
95         
96         //DB_DataObject::debugLevel(1);
97         //date_default_timezone_set('UTC');
98         // phpinfo();exit;
99         $force = empty($opts['force']) ? 0 : 1;
100         
101         $w = DB_DataObject::factory($this->table);
102
103         if (!$w->get($id)) {
104             $this->errorHandler("invalid id\n");
105         }
106
107         if (!$force && !empty($w->sent) && strtotime($w->act_when) < strtotime($w->sent)) {
108              
109             $this->errorHandler("already sent - repeat to early\n");
110         }
111         
112         $this->server = DB_DataObject::Factory('core_notify_server')->getCurrent($this, $force);
113         if (!$force &&  $w->server_id != $this->server->id) {
114             $this->errorHandler("Server id does not match - use force to try again\n");
115         }
116         
117         
118         if (!empty($opts['debug'])) {
119             print_r($w);
120             $ff = HTML_FlexyFramework::get();
121             if (!isset($ff->Core_Mailer)) {
122                 $ff->Core_Mailer = array();
123             }
124             HTML_FlexyFramework::get()->Core_Mailer['debug'] = true;
125         }
126         
127         $sent = (empty($w->sent) || strtotime( $w->sent) < 100 ) ? false : true;
128         
129         if (!$force && (!empty($w->msgid) || $sent)) {
130             $ww = clone($w);
131             if (!$sent) {   // fix sent.
132                 $w->sent = strtotime( $w->sent) < 100 ? $w->sqlValue('NOW()') :$w->sent; // do not update if sent.....
133                 $w->update($ww);
134             }    
135             $this->errorHandler("message has been sent already.\n");
136         }
137         
138         // we have a bug with msgid not getting filled.
139         $cev = DB_DataObject::Factory('Events');
140         $cev->on_table =  $this->table;
141         $cev->on_id =  $w->id;
142         $cev->whereAdd("action IN ('NOTIFYSENT', 'NOTIFYFAIL')");
143         $cev->limit(1);
144         if ($cev->count()) {
145             $cev->find(true);
146             $w->flagDone($cev, $cev->action == 'NOTIFYSENT' ? 'alreadysent' : '');
147             $this->errorHandler( $cev->action . " (fix old) ".  $cev->remarks);
148         }
149         
150         
151         $o = $w->object();
152         
153         if ($o === false)  {
154              
155             $ev = $this->addEvent('NOTIFY', $w,   "Notification event cleared (underlying object does not exist)" );
156             $w->flagDone($ev, '');
157             $this->errorHandler(  $ev->remarks);
158         }
159      
160         
161         
162         $p = $w->person();
163         
164         if (isset($p->active) && empty($p->active)) {
165             $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (not user not active any more)" );;
166              $w->flagDone($ev, '');
167             $this->errorHandler(  $ev->remarks);
168         }
169         // has it failed mutliple times..
170         
171         if (!empty($w->field) && isset($p->{$w->field .'_fails'}) && $p->{$w->field .'_fails'} > 9) {
172             $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (user has to many failures)" );;
173             $w->flagDone($ev, '');
174             $this->errorHandler(  $ev->remarks);
175         }
176         
177         // let's work out the last notification sent to this user..
178         $l = DB_DataObject::factory($this->table);
179         
180         $lar = array(
181                 'ontable' => $w->ontable,
182                 'onid' => $w->onid,
183         );
184         // only newer version of the database us this..
185         if (isset($w->person_table)) {
186             $personid_col = strtolower($w->person_table).'_id';
187             if (isset($w->{$personid_col})) {
188                 $lar[$personid_col] = $w->{$personid_col};
189             }
190         }
191         
192         
193         $l->setFrom( $lar );       
194         $l->whereAdd('id != '. $w->id);
195         $l->orderBy('sent DESC');
196         $l->limit(1);
197         $ar = $l->fetchAll('sent');
198         $last = empty($ar) ? date('Y-m-d H:i:s', 0) : $ar[0];
199         
200         // find last event..
201         $ev = DB_DataObject::factory('Events');
202         $ev->on_id = $w->id;                           // int(11)
203         $ev->on_table = $this->table;
204         $ev->limit(1);
205         $ev->orderBy('event_when DESC');
206         $ar = $ev->fetchAll('event_when');
207         $last_event = empty($ar) ? 0 : $ar[0];
208         $next_try_min = 5;
209         if ($last_event) {
210             $next_try_min = floor((time() - strtotime($last_event)) / 60) * 2;
211         }
212         $next_try = $next_try_min . ' MINUTES';
213          
214         // this may modify $p->email. (it will not update it though)
215         $email =  $this->makeEmail($o, $p, $last, $w, $force);
216         
217         if ($email === true)  {
218             $ev = $this->addEvent('NOTIFY', $w, "Notification event cleared (not required any more) - toEmail=true" );;
219             $w->flagDone($ev, '');
220             $this->errorHandler( $ev->remarks);
221         }
222         if (is_a($email, 'PEAR_Error')) {
223             $email =array(
224                 'error' => $email->toString()
225             );
226         }
227         
228         if (empty($p) && !empty($email['recipients'])) {
229             // make a fake person..
230             $p = (object) array(
231                 'email' => $email['recipients']
232             );
233         }
234          
235         if ($email === false || isset($email['error']) || empty($p)) {
236             // object returned 'false' - it does not know how to send it..
237             $ev = $this->addEvent('NOTIFYFAIL', $w, isset($email['error'])  ? $email['error'] : "INTERNAL ERROR  - We can not handle " . $w->ontable); 
238             $w->flagDone($ev, '');
239             $this->errorHandler(  $ev->remarks);
240         }
241         
242          
243         
244         if (isset($email['later'])) {
245              
246             $this->server->updateNotifyToNextServer($w, $email['later'],true);
247              
248             $this->errorHandler("Delivery postponed by email creator to {$email['later']}");
249         }
250         
251          
252         if (empty($email['headers']['Message-Id'])) {
253             $HOST = gethostname();
254             $email['headers']['Message-Id'] = "<{$this->table}-{$id}@{$HOST}>";
255             
256         }
257         
258         
259             
260         
261         //$p->email = 'alan@akbkhome.com'; //for testing..
262         //print_r($email);exit;
263         // should we fetch the watch that caused it.. - which should contain the method to call..
264         // --send-to=test@xxx.com
265        
266         if (!empty($email['send-to'])) {
267             $p->email = $email['send-to'];
268         }
269          if (!empty($opts['send-to'])) {
270             $p->email = $opts['send-to'];
271         }
272         
273             // since some of them have spaces?!?!
274         $p->email = trim($p->email);
275         $ww = clone($w);
276         $ww->to_email = empty($ww->to_email) ? $p->email : $ww->to_email;
277         $explode_email = explode('@', $ww->to_email);
278         $dom = array_pop($explode_email);
279         
280         $core_domain = DB_DataObject::factory('core_domain')->loadOrCreate($dom);
281
282         
283         $ww->domain_id = $core_domain->id;
284         // if to_email has not been set!?
285         $ww->update($w); // if nothing has changed this will not do anything.
286         $w = clone($ww);
287     
288       
289         
290         require_once 'Validate.php';
291         if (!Validate::email($p->email, true)) {
292             $ev = $this->addEvent('NOTIFYFAIL', $w, "INVALID ADDRESS: " . $p->email);
293             $w->flagDone($ev, '');
294             $this->errorHandler($ev->remarks);
295             
296         }
297         
298         
299         $ff = HTML_FlexyFramework::get();
300         
301      
302         $mxs = $this->mxs($dom);
303         $ww = clone($w);
304
305         // we might fail doing this...
306         // need to handle temporary failure..
307        
308         
309           // we try for 2 days..
310         $retry = 15;
311         if (strtotime($w->act_start) <  strtotime('NOW - 1 HOUR')) {
312             // older that 1 hour.
313             $retry = 60;
314         }
315         
316         if (strtotime($w->act_start) <  strtotime('NOW - 1 DAY')) {
317             // older that 1 day.
318             $retry = 120;
319         }
320         if (strtotime($w->act_start) <  strtotime('NOW - 2 DAY')) {
321             // older that 1 day.
322             $retry = 240;
323         }
324         
325         if (empty($mxs)) {
326             // only retry for 1 day if the MX issue..
327             if ($retry < 240) {
328                 $this->addEvent('NOTIFY', $w, 'MX LOOKUP FAILED ' . $dom );
329                 $w->flagLater(date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES')));
330                 $this->errorHandler($ev->remarks);
331             }
332             
333             $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - BAD DOMAIN - ". $p->email );
334             $w->flagDone($ev, '');
335             $this->errorHandler($ev->remarks);
336             
337             
338         }
339         
340         
341         
342         
343         if (!$force && strtotime($w->act_start) <  strtotime('NOW - 3 DAY')) {
344             $ev = $this->addEvent('NOTIFYFAIL', $w, "BAD ADDRESS - GIVE UP - ". $p->email );
345             $w->flagDone($ev, '');
346             $this->errorHandler(  $ev->remarks);
347         }
348         
349         $retry_when = date('Y-m-d H:i:s', strtotime('NOW + ' . $retry . ' MINUTES'));
350         
351         //$this->addEvent('NOTIFY', $w, 'GREYLISTED ' . $p->email . ' ' . $res->toString());
352         // we can only update act_when if it has not been sent already (only happens when running in force mode..)
353         // set act when if it's empty...
354         $w->act_when =  (!$w->act_when || $w->act_when == '0000-00-00 00:00:00') ? $retry_when : $w->act_when;
355         
356         $w->update($ww);
357         
358         $ww = clone($w);   
359         
360         $fail = false;
361         require_once 'Mail.php';
362         
363         
364         $this->server->initHelo();
365         
366         if (!isset($ff->Mail['helo'])) {
367             $this->errorHandler("config Mail[helo] is not set");
368         }
369         
370         $email = DB_DataObject::factory('core_notify_sender')->filterEmail($email, $w);
371             
372                         
373         foreach($mxs as $mx) {
374             
375            
376             $this->debug_str = '';
377             $this->debug("Trying SMTP: $mx / HELO {$ff->Mail['helo']}");
378             $mailer = Mail::factory('smtp', array(
379                     'host'    => $mx ,
380                     'localhost' => $ff->Mail['helo'],
381                     'timeout' => 15,
382                     'socket_options' =>  isset($ff->Mail['socket_options']) ? $ff->Mail['socket_options'] : null,
383                     //'debug' => isset($opts['debug']) ?  1 : 0,
384                     'debug' => 1,
385                     'debug_handler' => array($this, 'debugHandler')
386             ));
387             
388             // if the host is the mail host + it's authenticated add auth details
389             // this normally will happen if you sent  Pman_Core_NotifySend['host']
390              
391             
392             if (isset($ff->Mail['host']) && $ff->Mail['host'] == $mx && !empty($ff->Mail['auth'] )) {
393                 
394                 $mailer->auth = true;
395                 $mailer->username = $ff->Mail['username'];
396                 $mailer->password = $ff->Mail['password'];        
397             }
398             
399             if(!empty($ff->Core_Notify) && !empty($ff->Core_Notify['routes'])){
400                 
401                 // we might want to regex 'office365 as a mx host 
402                 foreach ($ff->Core_Notify['routes'] as $server => $settings){
403                     if(!in_array($dom, $settings['domains'])){
404                         continue;
405                     }
406                     
407                     // what's the minimum timespan.. - if we have 60/hour.. that's 1 every minute.
408                     // if it's newer that '1' minute...
409                     // then shunt it..
410                     
411                     $settings['rate'] = isset( $settings['rate']) ?  $settings['rate']  : 360;
412                     
413                     $seconds = floor((60 * 60) / $settings['rate']);
414                     
415                     $core_notify = DB_DataObject::factory($this->table);
416                     $core_notify->domain_id = $core_domain->id;
417                     $core_notify->server_id = $this->server->id;
418                     $core_notify->whereAdd("
419                         sent >= NOW() - INTERVAL $seconds SECOND
420                     ");
421                     
422                     if($core_notify->count()){
423                         $this->server->updateNotifyToNextServer( $w , date("Y-m-d H:i:s", time() + $seconds), true);
424                         $this->errorHandler( " Too many emails sent by {$dom} - requeing");
425                     }
426                      
427                     
428                     
429                     $mailer->host = $server;
430                     $mailer->auth = isset($settings['auth']) ? $settings['auth'] : true;
431                     $mailer->username = $settings['username'];
432                     $mailer->password = $settings['password'];
433                     if (isset($settings['port'])) {
434                         $mailer->port = $settings['port'];
435                     }
436                     if (isset($settings['socket_options'])) {
437                         $mailer->socket_options = $settings['socket_options'];
438                         
439                     }
440                     
441                     
442                     break;
443                 }
444                 
445             }
446         
447            
448             
449             
450             $res = $mailer->send($p->email, $email['headers'], $email['body']);
451             if (is_object($res)) {
452                 $res->backtrace = array(); 
453             }
454             $this->debug("GOT response to send: ". print_r($res,true)); 
455             
456             if ($res === true) {
457                 // success....
458                 
459                 $successEventName = (empty($email['successEventName'])) ? 'NOTIFYSENT' : $email['successEventName'];
460                 
461                 $ev = $this->addEvent($successEventName, $w, "{$w->to_email} - {$email['headers']['Subject']}");
462                 
463                 $ev->writeEventLog($this->debug_str);
464                  
465                 $w->flagDone($ev, $email['headers']['Message-Id']);
466                 
467                  
468                 // enable cc in notify..
469                 if (!empty($email['headers']['Cc'])) {
470                     $cmailer = Mail::factory('smtp',  isset($ff->Mail) ? $ff->Mail : array() );
471                     $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
472                     $cmailer->send($email['headers']['Cc'],    $email['headers'], $email['body']);
473                     
474                 }
475                 
476                 if (!empty($email['bcc'])) {
477                     $cmailer = Mail::factory('smtp', isset($ff->Mail) ? $ff->Mail : array() );
478                     $email['headers']['Subject'] = "(CC): " . $email['headers']['Subject'];
479                     $res = $cmailer->send($email['bcc'],  $email['headers'], $email['body']);
480                     if (!$res || is_a($res, 'PEAR_Error')) {
481                         echo "could not send bcc..\n";
482                     } else {
483                         echo "Sent BCC to {$email['bcc']}\n";
484                     }
485                 }
486                  
487                 $this->errorHandler( " SENT {$w->id} - {$ev->remarks}", true);
488             }
489             // what type of error..
490             $code = empty($res->userinfo['smtpcode']) ? -1 : $res->userinfo['smtpcode'];
491             if (!empty($res->code) && $res->code == 10001) {
492                 // fake greylist if timed out.
493                 $code = -1; 
494             }
495             
496             if ($code < 0) {
497                 $this->debug($res->message);
498                 continue; // try next mx... ??? should we wait??? - nope we did not even connect..
499             }
500             // give up after 2 days..
501             if (in_array($code, array( 421, 450, 451, 452))   && $next_try_min < (2*24*60)) {
502                 // try again later..
503                 // check last event for this item..
504                 //$errmsg=  $fail ? ($res->userinfo['smtpcode'] . ': ' .$res->toString()) :  " - UNKNOWN ERROR";
505                 $errmsg=  $res->userinfo['smtpcode'] . ': ' .$res->message ;
506                 if (!empty($res->userinfo['smtptext'])) {
507                     $errmsg=  $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
508                 }
509                 //print_r($res);
510                 $ev = $this->addEvent('NOTIFY', $w, 'GREYLISTED - ' . $errmsg);
511                 
512                 $this->server->updateNotifyToNextServer($w,  $retry_when,true);
513                 
514                 $this->errorHandler(  $ev->remarks);
515             }
516             
517             $fail = true;
518             break;
519         }
520         
521         // after trying all mxs - could not connect...
522         if  (!$fail && ($next_try_min > (2*24*60) || strtotime($w->act_start) < strtotime('NOW - 3 DAYS'))) {
523             
524             $errmsg=  " - UNKNOWN ERROR";
525             if (isset($res->userinfo['smtptext'])) {
526                 $errmsg=  $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
527             }
528             
529             $ev = $this->addEvent('NOTIFYFAIL', $w,  "RETRY TIME EXCEEDED - " .  $errmsg);
530             $w->flagDone($ev, '');
531             $this->errorHandler( $ev->remarks);
532         }
533         
534         if ($fail) { //// !!!!<<< BLACKLIST DETECT?
535         // fail.. = log and give up..
536             $errmsg=   $res->userinfo['smtpcode'] . ': ' .$res->toString();
537             if (isset($res->userinfo['smtptext'])) {
538                 $errmsg=  $res->userinfo['smtpcode'] . ':' . $res->userinfo['smtptext'];
539             }
540             
541             if ( $res->userinfo['smtpcode']> 500 ) {
542                 
543                 DB_DataObject::factory('core_notify_sender')->checkSmtpResponse($email, $w, $errmsg);
544
545                 
546                 if ($this->server->checkSmtpResponse($errmsg, $core_domain)) {
547                     $ev = $this->addEvent('NOTIFY', $w, 'BLACKLISTED  - ' . $errmsg);
548                     $this->server->updateNotifyToNextServer($w,  $retry_when,true);
549                     $this->errorHandler( $ev->remarks);
550                 }
551             }
552              
553             $ev = $this->addEvent('NOTIFYFAIL', $w, ($fail ? "FAILED - " : "RETRY TIME EXCEEDED - ") .  $errmsg);
554             $w->flagDone($ev, '');
555              
556             $this->errorHandler( $ev->remarks);
557         }
558         
559         // at this point we just could not find any MX records..
560         
561         
562         // try again.
563         
564         $ev = $this->addEvent('NOTIFY', $w, 'GREYLIST - NO HOST CAN BE CONTACTED:' . $p->email);
565         
566         $this->server->updateNotifyToNextServer($w,  $retry_when ,true);
567
568         
569          
570         $this->errorHandler($ev->remarks);
571
572         
573     }
574     function mxs($fqdn)
575     {
576         $ff = HTML_FlexyFramework::get();
577         if (isset($ff->Pman_Core_NotifySend['host'])) {
578             return array($ff->Pman_Core_NotifySend['host']);
579         }
580         
581         $mx_records = array();
582         $mx_weight = array();
583         $mxs = array();
584         if (!getmxrr($fqdn, $mx_records, $mx_weight)) {
585             if (!checkdnsrr($fqdn)) {
586                 return false;
587             }
588             return array($fqdn);
589         }
590         
591         asort($mx_weight,SORT_NUMERIC);
592         
593         foreach($mx_weight as $k => $weight) {
594             if (!empty($mx_records[$k])) {
595                 $mxs[] = $mx_records[$k];
596             }
597         }
598         return empty($mxs) ? false : $mxs;
599     }
600     
601     /**
602      * wrapper to call object->toEmail()
603      *
604      * return
605      *   {
606         headers : {AssocArray},
607         body: {String}
608         
609         // optional..
610         error :  {String} // error message in log.
611         send-to: {String} // use to override rcpt
612          
613      }
614      **/
615     function makeEmail($object, $rcpt, $last_sent_date, $notify, $force =false)
616     {
617         $m = 'notify'. $notify->evtype;
618         //var_dump(get_class($object) . '::' .$m);
619         if (!empty($notify->evtype) && method_exists($object,$m)) {
620             echo "calling :" . get_class($object) . '::' .$m . "\n";
621             return $object->$m($rcpt, $last_sent_date, $notify, $force);
622         }
623         
624         $type = explode('::', $notify->evtype);
625         
626         if(!empty($type[1]) && method_exists($object,$type[1])){
627             $m = $type[1];
628             echo "calling :" . get_class($object) . '::' .$m . "\n";
629             return $object->$m($rcpt, $last_sent_date, $notify, $force);
630         }
631         // fallback if evtype is empty..
632         
633         if (method_exists($object, 'toMailerData')) {
634             return $object->toMailerData(array(
635                 'rcpts'=>$rcpt,
636                 'person'=>$rcpt, // added as mediaoutreach used this?
637             )); //this is core_email - i think it's only used for testing...
638             //var_Dump($object);
639             //exit;
640         }
641         if (method_exists($object, 'toEmail')) {
642             return $object->toEmail($rcpt, $last_sent_date, $notify, $force);
643         }
644         // no way to send this.. - this needs to handle core_notify how we have used it for the approval stuff..
645         
646         return false;
647     }
648     
649     function debug($str)
650     {
651         if (empty($this->cli_args['debug'])) {
652             return;
653             
654         }
655         echo $str . "\n";
656     }
657     function output()
658     {
659         $this->errorHandler("done\n");
660     }
661     var $debug_str = '';
662     
663     function debugHandler ($smtp, $message)
664     {
665         $this->debug_str .= strlen($this->debug_str) ? "\n" : '';
666         $this->debug_str .= $message;
667         //echo $message ."\n";
668     }
669     
670     function errorHandler($msg, $success = false)
671     {
672         if($this->error_handler == 'exception'){
673             if($success){
674                 throw new Pman_Core_NotifySend_Exception_Success($msg);
675             }
676             
677             throw new Pman_Core_NotifySend_Exception_Fail($msg);
678         }
679         
680         die(date('Y-m-d h:i:s') . ' ' . $msg ."\n");
681         
682         
683     }
684     
685     function updateServer($w)
686     {
687         $ff = HTML_FlexyFramework::get();
688          
689         if (empty($ff->Core_Notify['servers'])) {
690             return;
691         }
692         // some classes dont support server routing
693         if (!property_exists($w, 'server_id')) {
694             return;
695         }
696         // next server..
697         $w->server_id = ($w->server_id + 1) % count(array_keys($ff->Core_Notify['servers']));
698          
699     }
700     
701
702     
703 }