source: extensions/Mail_supervisor/main.inc.php @ 11529

Last change on this file since 11529 was 10822, checked in by cljosse, 13 years ago

[extensions] mail_supervisor add option debug_mail,

File size: 20.1 KB
Line 
1<?php
2/*
3Plugin Name: Mail supervisor
4Version: auto
5Description: Mail supervisor surveille l'envoie des mails.
6Plugin URI: http://piwigo.org/ext/extension_view.php?eid=315
7Author: cljosse
8Author URI:http://cljosse.free.fr
9*/
10if (!defined('PHPWG_ROOT_PATH')) die('Hacking attempt!');
11if (!defined('mail_superv_DIR')) define('mail_superv_DIR' , basename(dirname(__FILE__)));
12if (!defined('MAIL_SUPERV_PATH')) define('MAIL_SUPERV_PATH' , PHPWG_PLUGINS_PATH.basename(dirname(__FILE__)).'/');
13
14$MAIL_SUPERV_PATH_ABS = str_replace('\\','/',dirname(__FILE__) );
15if (!defined('MAIL_SUPERV_PATH_ABS')) define(  'MAIL_SUPERV_PATH_ABS',   $MAIL_SUPERV_PATH_ABS."/");
16
17global $conf,$mails_options ;
18include_once (MAIL_SUPERV_PATH.'include/constants.php');
19include_once(MAIL_SUPERV_PATH.'mail_super.inc.php');
20
21$mail_supervisor = new mail_supervisor();
22add_event_handler('get_admin_plugin_menu_links', array(&$mail_supervisor,'admin_menu')  );
23
24$mails_options = mail_supervisor::Get_Options($mails_options,"mail_superv");
25/* EVENT_HANDLER_PRIORITY_NEUTRAL  */
26//
27//
28include_once (PHPWG_ROOT_PATH.'include/functions_mail.inc.php' );
29include_once (MAIL_SUPERV_PATH.'include/fonctions.php');
30//===============loc_begin_index====loc_begin_page_header==========loc_after_page_header=============================================================
31add_event_handler('loc_after_page_header',  array(&$mail_supervisor,'init')  );
32add_event_handler('loc_begin_page_tail',  array(&$mail_supervisor,'affiche_message')  );
33
34//==========================================================================================
35add_event_handler('send_mail', 'clj_mail',EVENT_HANDLER_PRIORITY_NEUTRAL - 10, 6);
36function clj_mail($result, $mailto, $subject, $content, $headers, $args) {
37  global $conf, $user, $lang_info;
38  global $conf_mail,$mails_options,$mails_donnees ;
39  global  $template,$page ,$erreur_message,$infos_message, $lang;
40  global $errors;
41  // lecture config table -------------
42  include_once (MAIL_SUPERV_PATH.'include/fonctions.php');
43  load_language('plugin.lang', MAIL_SUPERV_PATH);
44
45  $arg_trigg= array($mailto, $subject, $content, $headers, $args);
46
47    trigger_event('mail_supervisor_clj_mail',$arg_trigg);
48
49 // remove_event_handler('send_mail', 'pwg_send_mail');
50    $message ="";
51  if (!isset($infos_message))   {   $infos_message = "";    }
52  if (!isset($erreur_message))  {   $erreur_message = '';   }
53
54  // $mails_options = explode("," , $conf['mail_superv']);
55  $envoie_ok=true ;
56  //======== verification si envoie de mail ou blocage connexion =====================
57
58  if ($mails_options['no_mail_list']=='on' || $mails_options['no_connect'] == 'on' )    {
59    if (kill_list()) {
60      $nb_destinataires=0; ;
61      $envoie_ok= false ;
62      $erreur_message .= "<BR />".l10n('Sv_is_a_spam') ;
63      $infos_message = l10n('Sv_mail_not_send')."<BR />";
64      if ($mails_options['no_connect'] == 'on' ){         
65          if ($user['status'] == 'webmaster'){
66          //---------- continuer si web master ----------
67          }else{
68             trigger_event('mail_supervisor_send_mail', "DIE(KILL) : " . $ip . ' = ' . $user['status']);
69              if (!isset($_GET['admin'])) {
70                      die('Blacklist : <br />' .$erreur_message. '<br /> Hacking attempt!');
71                        }elseif   ($_GET['admin'] != 'piwigo')
72                            {
73                      die('blacklist Hacking attempt!');
74              }
75          }
76      }
77      trigger_event('mail_supervisor_send_mail', "Kill : " . $ip . ' = ' . $user['status'] . "noconnect==off");
78      return true;
79      }
80    }
81  // lecture donnees       -------------
82  $mails_donnees = mail_supervisor::Get_Datas();
83  $nb_mails   = $mails_donnees['nb_mails'] ;
84  $next_day  =  $mails_donnees['date_mail'] ;
85  $reste =    $mails_donnees['reste'] ;
86    $rest_mail =    $mails_donnees['rest_mail'] ;
87    if ($rest_mail <=0 || $mails_donnees['nb_mails'] ==0 ){
88       $mails_donnees['nb_mails'] =0 ;
89       $mails_donnees['date_mail'] = time();
90    }
91    $rest_spam =    $mails_donnees['rest_spam'] ;
92    if ($rest_spam <=0 || $mails_donnees['nb_spams'] ==0 ){
93       $mails_donnees['nb_spams'] =0 ;
94       $mails_donnees['date_spam'] = time();
95    }
96    $alerte =   ( $mails_donnees['reste'] >0 ) ? true : false ;
97    $alerte_mail =    ( $mails_donnees['nb_mails'] >   $mails_donnees['nb_mails_maxi']-1 ) ? true : false ;
98    $alerte_spam =    ( $mails_donnees['nb_spams'] >   $mails_donnees['nb_spams_maxi']-1 ) ? true : false ;
99
100  if ( ( !$alerte  && !$alerte_spam  && !$alerte_mail ) ) {
101    $nb_destinataires=0;
102  //====================================================
103    $match_email = $conf_mail['email_webmaster'];
104
105    $new_args=array();
106    if( isset($args['Bcc']))
107    foreach($args['Bcc'] as $key => $val){
108      if (!preg_match('/'. $match_email.'/', $val)){
109          array_push($new_args, $val);
110      }else{
111            $mailto = $match_email;
112      }
113    }
114    $args['Bcc']=$new_args;
115     //=======================================================================
116     $nb_destinataires=0;
117    if ($mailto<>"" ) $nb_destinataires +=1;
118        if (!empty($args['Cc']))  {
119        $nb_destinataires += count($args['Cc']);
120
121    }
122        if (!empty($args['Bcc']))  {
123        $nb_destinataires += count($args['Bcc']);
124    }
125    if ($mailto == "" && $nb_destinataires==0 ) {
126      $mailto = $conf_mail['email_webmaster'];
127      $nb_destinataires ++;
128    }
129
130        if ($mails_options['check_mailto'] == 'on') {
131            if ($mailto == "" && $nb_destinataires > 1 )    $mailto = $conf_mail['email_webmaster'];
132        }
133
134    $infos_message .= "nb_destinataires : $nb_destinataires Theme :" . ($args['theme'] ) ."{". $lang_info['language_name'] ."}"."<br />";
135    //================= réecriture de l'entete ===============================
136    $match=array("<",">");
137    $string=array("&lt;","&gt;") ;
138    if ( $nb_destinataires  == 1 ) {
139      if ($mailto == "" ) {
140        if (!empty($args['Bcc'])){
141          $mailto = get_strict_email_list(implode(',', $args['Bcc']));
142          $args['Bcc']=array();
143        }else{
144          if (!empty($args['Cc']) ){  $mailto=get_strict_email_list(implode(',', $args['Cc']));
145           $args['Cc']=array();
146          };
147        }
148      }
149      if ($mailto == "" ) {$nb_destinataires  = 0 ;}
150      $mailto  = $mailto ." \n"   ;
151      $headers =  preg_replace('/.*Bcc(.*).\n/i', '', $headers);
152      $headers =  preg_replace('/.*Cc(.*).\n/i', '', $headers);
153      $infos_message .="Destinataire:" .$mailto ;
154      //=============================================================================
155
156    }else{
157          //=== plusieurs destinataires ===========
158      $cl_list_mail="";
159      if ($mailto !="") $infos_message .="To: " . $mailto . " "."<br />" ;
160      if (!empty($args['Cc'])) {
161        $ret= corrige_header('Cc',$headers,$args,$cl_list_mail,$mailto);
162        $headers = $ret->headers;
163        if($ret->list_mail!="") $infos_message .="Cc: " .  ( $ret->list_mail)."  <br />" ;
164
165      }
166      if (!empty($args['Bcc'])){
167          $ret  = corrige_header('Bcc',$headers,$args,$cl_list_mail,$mailto);
168          $headers = $ret->headers ;
169          if($ret->list_mail!="") $infos_message .="Bcc: " . ( $ret->list_mail) ."  <br />";
170
171       }
172         $infos_message .=  " " ;
173    }
174   
175     $pattern = '/(http:\/\/)([0-9].*)([0-9]\/)/'; 
176     //---- si adresse avec ip , certaine boite aux lettres traite ces messages en spam (orange+windowsmail)
177  if(preg_match($pattern, $content)){
178      // remplace 192.168.1.25 par rien ??
179      $replacement = '${1}'; 
180      $content = preg_replace( $pattern, $replacement,  $content );     
181}
182
183      $content= preg_replace('#(?<!\r)\n#si', "\r\n", $content); //drop LF barre
184
185    if (!preg_match('/'. $conf_mail['boundary_key'] .'/', $headers)){
186        $erreur_message .=   "<br />ERREUR manque : boundary_key dans le headers <br />";
187        $infos_message = l10n('Sv_mail_not_send'); 
188        $envoie_ok= false ;
189    }
190            $ret=false; 
191             ob_start();
192            //======== Non mise en quarantaine =============
193            //echo "warning spam" ;
194           // echo " Warning: mail() has been disabled for security reasons";
195         
196              if ($nb_destinataires > 0) {
197                if( $envoie_ok)  $ret = mail($mailto, $subject,$content, $headers);
198              }else{
199                $message .= l10n('Sv_no_receiver_available');
200              }
201              $message .= ob_get_contents();
202              ob_end_clean();
203              $arg_trigg= array("Nb destinataires: " . $nb_destinataires,"Mail to: ".$mailto,"content: ".$content, " Reponse : " . $message);
204              trigger_event('mail_supervisor_mail', $arg_trigg );
205              $mails_donnees['message']=$message;
206              Gestion_erreurs($message,$ret,$nb_destinataires,$headers,$mailto, $subject,$content);
207            } else {
208                //================== Est en quarantaine =======================
209                $erreur_message .=  l10n('Sv_To_day_is')."<br />";
210                if ($alerte_spam ) {
211                        $type="Spams";
212                        $d1=$mails_donnees['nb_spams'] . '  \\  ' . $mails_donnees['nb_spams_maxi'];
213                        $d2=$mails_donnees['nb_spams'];
214                        $d3= $mails_donnees['rest_spam'];
215                        $d4=time()+$d3 ;
216                }
217                if ($alerte_mail) {
218                    $type="Mails";
219                    $d1=$mails_donnees['nb_mails']. '  \\  ' . $mails_donnees['nb_mails_maxi'];;
220                    $d2=$mails_donnees['date_mail'];
221                    $d3= $mails_donnees['rest_mail'];
222                    $d4=time()+$d3 ;
223                }
224                if ($alerte) {
225                $type="Spams(Quarantaine)";
226                    $d1=$mails_donnees['nb_spams'] . '  \\  ' . $mails_donnees['nb_spams_maxi'];
227                    $d2=$mails_donnees['date_quarantaine'];
228                    $d3= $mails_donnees['reste'];
229                    $d4=time()+$d3 ;
230                }
231            $d2=date(l10n('Sv_formatdate'),$d2);
232            $d3=int_to_heure($d3) ;
233            $d4=date(l10n('Sv_formatdate'),$d4);
234            if ($alerte_mail) {
235                $erreur_message .='<br />'.sprintf(l10n('Sv_alerte_mail %s %s %s %s %s'),$type,$d1,$d2,$d3,$d4).'<br />';
236            }else{
237                $erreur_message .='<br />'.sprintf(l10n('Sv_mise_en_quarantaine %s %s %s %s %s'),$type,$d1,$d2,$d3,$d4).'<br />';
238            }
239            $infos_message .= l10n('Sv_mail_not_send');
240            }
241           $infos_message .= "<hr>"; 
242           trigger_event('mail_supervisor_message',  $infos_message );
243    mail_supervisor::sauve_donnees();
244    mail_supervisor::affiche_message();
245   
246    return true ;
247}
248//===========================================================================================
249function Gestion_erreurs($message,$ret,$nb_destinataires,$headers,$mailto, $subject,$content){
250     global $conf, $user,  $conf_mail,$mails_options,$mails_donnees , $template,$page ,$infos_message,$erreur_message,$args,$lang, $lang_info;
251     $match=array("<",">");
252     $string=array("&lt;","&gt;") ;
253     //  $headers=str_replace( $match,$string, $headers);
254    // Warning: mail() has been disabled for security reasons
255    $est_un_spam =!(strpos(strtolower($message), 'spam') === false); 
256    if ( ($ret==false) || ($est_un_spam==true) || ($nb_destinataires == 0) ) {
257        // Bad recipient address syntax
258        $pos1 = strpos(strtolower($message), 'bad recipient address syntax');
259        if (  !($pos1 === false) ){
260            $erreur_message .= l10n('Sv_detection_de').' Bad recipient address syntax .';
261            $erreur_message .= l10n('Sv_verifiez_les_destinataires').' (Bcc,Cc,To)<br />';
262            }               
263
264    $erreur_message .=sprintf(l10n('Sv_debug_message'),
265                              ($ret==true)? "true" : "false",
266                              htmlspecialchars($message) ,
267                              htmlspecialchars( $mailto) ,
268                              htmlspecialchars($subject) ,
269                              htmlspecialchars($headers) ,
270                              htmlspecialchars($content) ,
271                              $nb_destinataires );
272
273     Mail_supervisor_log($mailto,$erreur_message) ;   
274     //=============== La fonction mail retourne une erreur =========================
275      }else{ 
276           
277    if( isset($mails_options['debug_mail']) && $mails_options['debug_mail']=="on") {
278        $erreur_message .="DEBUG : <br />" .sprintf(l10n('Sv_debug_message'),
279                                  "DEBUG",
280                                  htmlspecialchars( $message) ,
281                                  htmlspecialchars( $mailto) ,
282                                  htmlspecialchars($subject) ,
283                                  htmlspecialchars($headers) ,
284                                  htmlspecialchars($content) ,
285                                  $nb_destinataires );
286
287         Mail_supervisor_log($mailto,$erreur_message) ; 
288        }
289      }
290
291
292
293        if ($est_un_spam == false){
294                if ($mails_donnees['nb_mails']==0) {    $mails_donnees['date_mail'] =  time();  }
295                $mails_donnees['nb_mails'] += $nb_destinataires;
296            } else {
297                $mails_donnees['nb_spams'] += $nb_destinataires;
298                //--- Detection de spam ------------------
299                if ($mails_donnees['nb_spams']==0) {$mails_donnees['date_spam'] = time();   }
300
301                $trop_de_spam =!(strpos(strtolower($message), 'trop de spam') === false);
302                if ( $trop_de_spam ) {
303                        $mails_donnees['nb_spams_maxi']=$mails_donnees['nb_spams'];
304
305                        $mails_donnees['date_quarantaine']= time()  ;
306                        $mails_donnees['quarantaine']= true    ;
307                        $infos_message .= mail_supervisor::Memo_Var($mails_donnees);
308                    }
309            }
310 $ret=true;
311 return $ret ;
312}
313//============================================================
314global $ms_file_log;
315$dir=$conf['local_data_dir'].'/Mail_supervisor_log';
316 if (!is_dir($dir)){ 
317    $umask = umask(0);
318    $mkd = @mkdir($dir, 0755, true );
319    umask($umask);
320
321      if ($mkd==false){
322      fatal_error( "$dir ".l10n('no write access'));
323      return false;
324    }
325        $file = $dir.'/.htaccess';
326       @file_put_contents( $file, 'allow from all' );
327
328    }
329   if($ms_file_log=="") $ms_file_log=$dir."/"."pw1.html";
330
331
332//============================================================
333function Mail_supervisor_log($label_,$lines){
334  global $ms_file_log,$conf; 
335  $nb_lignes=300 ;
336$t= var_export( $lines, true );
337$s  = htmlspecialchars(  $lines);
338 $s  =  (  $lines);
339    if (!file_exists($ms_file_log)) { 
340    $handle = fopen($ms_file_log, 'w');
341    fwrite($handle, "\n");
342    fclose($handle);
343    }
344  $tableau=file($ms_file_log);
345  $handle = fopen($ms_file_log, 'a');
346  $nb=count ($tableau);
347   if($nb>$nb_lignes) {
348      $handle = fopen($ms_file_log, 'w');
349      fwrite($handle, $nb. " > " . $nb_lignes . "  RAZ " ."\n");
350   }
351 //rewind ($handle); // Go back to the beginning
352 //fwrite ($handle, sprintf("%5d ", $nb)); // Don't forget to increment the counter
353 $s="\n".date('Y m d H:m:s ')."\n".$s;
354
355
356$s= nl2br($s);
357
358 if( $s !="") fwrite($handle,$s );
359      fclose($handle);
360}
361
362/*
363 *
364 *
365 * @param:
366 *   
367 *   - args: function params of mail function:
368 *       o from: sender [default value webmaster email]
369 *       o Cc: array of carbon copy receivers of the mail. [default value empty]
370 *       o Bcc: array of blind carbon copy receivers of the mail. [default value empty]
371 *       o subject  [default value 'Piwigo']
372 *       o content: content of mail    [default value '']
373 *       o content_format: format of mail content  [default value 'text/plain']
374 *       o email_format: global mail format  [default value $conf_mail['default_email_format']]
375 *       o theme: template to use [default get_default_theme()]
376 *
377 * @return boolean (Ok or not)
378 */
379function cl_pwg_mail(  $args = array())
380{
381  global $conf, $conf_mail, $lang_info, $page;   
382  global $erreur_message ;
383  if (!isset($conf_mail)) {
384    $conf_mail = get_mail_configuration();
385  }
386  if (empty($args['email_format']))  {
387    $args['email_format'] = $conf_mail['default_email_format'];
388  }
389  // Compute root_path in order have complete path
390  set_make_full_url(); 
391  if (!isset($args['content'])) {
392    $args['content'] = '';
393  }
394  if (empty($args['content_format']))  {
395    $args['content_format'] = 'text/plain';  }
396  if (empty($args['theme']))  {
397    $args['theme'] = get_default_theme();
398  }
399
400  // List on content-type
401  $content_type_list[] = $args['email_format'];
402  if (!empty($conf_mail['alternative_email_format']))  {
403    $content_type_list[] = $conf_mail['alternative_email_format'];
404  }
405  $content = '';
406  foreach (array_unique($content_type_list) as $content_type)
407  {
408    // key compose of indexes witch allow ti cache mail data
409    $cache_key = $content_type.'-'.$lang_info['code'].'-'.$args['theme'];
410    unset($conf_mail[$cache_key]);
411    if (!isset($conf_mail[$cache_key])){
412      if (!isset($conf_mail[$cache_key]['theme'])){
413        $conf_mail[$cache_key]['theme'] = get_mail_template($content_type, $args['theme']);
414      }
415      $conf_mail[$cache_key]['theme']->set_filename('mail_header', 'header.tpl');
416      $conf_mail[$cache_key]['theme']->set_filename('mail_footer', 'footer.tpl');
417      $conf_mail[$cache_key]['theme']->assign(
418        array(
419          //Header
420          'BOUNDARY_KEY' => $conf_mail['boundary_key'],
421          'CONTENT_TYPE' => $content_type,
422          'CONTENT_ENCODING' => get_pwg_charset(),
423
424          // Footer
425          'GALLERY_URL' => get_gallery_home_url(),
426          'GALLERY_TITLE' =>
427            isset($page['gallery_title']) ?
428                  $page['gallery_title'] : $conf['gallery_title'],
429          'VERSION' => $conf['show_version'] ? PHPWG_VERSION : '',
430          'PHPWG_URL' => PHPWG_URL,
431
432          'TITLE_MAIL' => urlencode(l10n('A comment on your site')),
433          'MAIL' => get_webmaster_mail_address()
434          ));
435
436      if ($content_type == 'text/html'){
437        if ($conf_mail[$cache_key]['theme']->smarty->template_exists('global-mail-css.tpl')){
438          $conf_mail[$cache_key]['theme']->set_filename('css', 'global-mail-css.tpl');
439          $conf_mail[$cache_key]['theme']->assign_var_from_handle('GLOBAL_MAIL_CSS', 'css');
440        }
441
442        $file = PHPWG_ROOT_PATH.'themes/'.$args['theme'].'/mail-css.tpl';
443        if (is_file($file)){
444          $conf_mail[$cache_key]['theme']->set_filename('css', realpath($file));
445          $conf_mail[$cache_key]['theme']->assign_var_from_handle('MAIL_CSS', 'css');
446        }
447      } 
448
449      // what are displayed on the header of each mail ?
450      $conf_mail[$cache_key]['header'] =
451        $conf_mail[$cache_key]['theme']->parse('mail_header', true);
452
453      // what are displayed on the footer of each mail ?
454      $conf_mail[$cache_key]['footer'] =
455        $conf_mail[$cache_key]['theme']->parse('mail_footer', true);
456    }
457
458    // Header
459   $content.= $conf_mail[$cache_key]['header'];
460       // Content
461    if (($args['content_format'] == 'text/plain') and ($content_type == 'text/html')){
462      $content.= '<p>'.
463                  nl2br(
464                    preg_replace("/(http:\/\/)([^\s,]*)/i",
465                                 "<a href='$1$2' class='thumblnk'>$1$2</a>",
466                                 htmlspecialchars($args['content']))).
467                  '</p>';
468    } else if (($args['content_format'] == 'text/html') and ($content_type == 'text/plain')) {
469      // convert html text to plain text
470      $content.= strip_tags($args['content']);
471    } else {
472      $content.= $args['content'];
473    }
474
475    // Footer 
476    $content.= $conf_mail[$cache_key]['footer']."\n\n";
477   
478    // Close boundary
479    $content.= "\n\n".'-----='.$conf_mail['boundary_key'].'--'."\n\n";
480  }
481   // Undo Compute root_path in order have complete path
482  unset_make_full_url(); 
483
484
485
486  return    $content;
487 
488}
489
490?>
Note: See TracBrowser for help on using the repository browser.