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

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

[extensions] mail_supervisor fix bug in test

File size: 18.4 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  $content= cl_pwg_mail($args);
176 
177
178    if (  !preg_match('/'. $conf_mail['boundary_key'] .'/', $headers)){
179        $erreur_message .=   "ERREUR manque : boundary_key dans le headers <br />";
180        $infos_message = l10n('Sv_mail_not_send'); 
181         $envoie_ok= false ;
182    }
183 
184
185
186    if( isset($conf['debug_mail']) && $conf['debug_mail']=="true") {
187
188    //    $erreur_message .="DEBUG:"."<br />Theme: ".    $file. "<br />";
189
190        $content1 =   htmlspecialchars( var_export($headers, true ) );   
191        $erreur_message .="<br />DEBUG -> "." Header: <br />".   $content1 ."<br />";
192
193        $content1 =   htmlspecialchars( var_export($mailto, true ) );   
194        $erreur_message .="<br />DEBUG -> "." Mail to: <br />".   $content1 ."<br />";
195
196        $content1 =   htmlspecialchars( var_export($subject ,true ) );   
197        $erreur_message .="<br />DEBUG -> "." Sujet: <br />".   $content1 ."<br />";
198
199        $content1 =   htmlspecialchars( var_export($content, true ) );   
200        $erreur_message .="<br />DEBUG -> "." Contenu:<br />" . $content1 ."<br />";
201    }
202
203
204            $ret=false;
205            //======== Non mise en quarantaine =============
206
207
208            ob_start();
209              if ($nb_destinataires > 0) {
210                if( $envoie_ok)  $ret = mail($mailto, $subject,$content, $headers);
211              }else{
212                $message .= l10n('Sv_no_receiver_available');
213              }
214              $message .= ob_get_contents();
215              ob_end_clean();
216              $arg_trigg= array("Nb destinataires: " . $nb_destinataires,"Mail to: ".$mailto,"content: ".$content, " Reponse : " . $message);
217              trigger_event('mail_supervisor_mail', $arg_trigg );
218              $mails_donnees['message']=$message;
219              Gestion_erreurs($message,$ret,$nb_destinataires,$headers,$mailto);
220            } else {
221                //================== Est en quarantaine =======================
222                $erreur_message .=  l10n('Sv_To_day_is')."<br />";
223                if ($alerte_spam ) {
224                        $type="Spams";
225                        $d1=$mails_donnees['nb_spams'] . '  \\  ' . $mails_donnees['nb_spams_maxi'];
226                        $d2=$mails_donnees['nb_spams'];
227                        $d3= $mails_donnees['rest_spam'];
228                        $d4=time()+$d3 ;
229                }
230                if ($alerte_mail) {
231                    $type="Mails";
232                    $d1=$mails_donnees['nb_mails']. '  \\  ' . $mails_donnees['nb_mails_maxi'];;
233                    $d2=$mails_donnees['date_mail'];
234                    $d3= $mails_donnees['rest_mail'];
235                    $d4=time()+$d3 ;
236                }
237                if ($alerte) {
238                $type="Spams(Quarantaine)";
239                    $d1=$mails_donnees['nb_spams'] . '  \\  ' . $mails_donnees['nb_spams_maxi'];
240                    $d2=$mails_donnees['date_quarantaine'];
241                    $d3= $mails_donnees['reste'];
242                    $d4=time()+$d3 ;
243                }
244            $d2=date(l10n('Sv_formatdate'),$d2);
245            $d3=int_to_heure($d3) ;
246            $d4=date(l10n('Sv_formatdate'),$d4);
247            if ($alerte_mail) {
248                $erreur_message .='<br />'.sprintf(l10n('Sv_alerte_mail %s %s %s %s %s'),$type,$d1,$d2,$d3,$d4).'<br />';
249            }else{
250                $erreur_message .='<br />'.sprintf(l10n('Sv_mise_en_quarantaine %s %s %s %s %s'),$type,$d1,$d2,$d3,$d4).'<br />';
251            }
252            $infos_message .= l10n('Sv_mail_not_send');
253            }
254           $infos_message .= "<hr>"; 
255           trigger_event('mail_supervisor_message',  $infos_message );
256    mail_supervisor::sauve_donnees();
257    mail_supervisor::affiche_message();
258   
259    return true ;
260}
261//===========================================================================================
262function Gestion_erreurs($message,$ret,$nb_destinataires,$headers,$mailto){
263     global $conf, $user,  $conf_mail,$mails_options,$mails_donnees , $template,$page ,$infos_message,$erreur_message,$args,$lang, $lang_info;
264     $match=array("<",">");
265    $string=array("&lt;","&gt;") ;
266//Warning: mail() has been disabled for security reasons
267
268    $est_un_spam =!(strpos(strtolower($message), 'spam') === false);
269    $headers=str_replace( $match,$string, $headers);
270
271    if ( ($ret==false) || ($est_un_spam==true) || ($nb_destinataires == 0) ) {
272         ;              // Bad recipient address syntax
273        $pos1 = strpos(strtolower($message), 'bad recipient address syntax');
274        if (  !($pos1 === false) ){
275            $erreur_message .= l10n('Sv_detection_de').' Bad recipient address syntax .';
276            $erreur_message .= l10n('Sv_verifiez_les_destinataires').' (Bcc,Cc,To)<br />';
277            }
278
279    $erreur_message .= sprintf(l10n('Sv_debug_message'),
280    ($ret==true)? "true" : "false",
281    $message ,
282    $mailto ,
283    $headers ,
284    $nb_destinataires );
285       //=============== La fonction mail retourne une erreur =========================
286                }
287
288        if ($est_un_spam == false)
289            {
290                if ($mails_donnees['nb_mails']==0) {    $mails_donnees['date_mail'] =  time();  }
291                $mails_donnees['nb_mails'] += $nb_destinataires;
292            }
293            else
294            {
295                $mails_donnees['nb_spams'] += $nb_destinataires;
296                //--- Detection de spam ------------------
297                if ($mails_donnees['nb_spams']==0) {$mails_donnees['date_spam'] = time();   }
298
299                $trop_de_spam =!(strpos(strtolower($message), 'trop de spam') === false);
300                if ( $trop_de_spam ) {
301                        $mails_donnees['nb_spams_maxi']=$mails_donnees['nb_spams'];
302
303                        $mails_donnees['date_quarantaine']= time()  ;
304                        $mails_donnees['quarantaine']= true    ;
305                        $infos_message .= mail_supervisor::Memo_Var($mails_donnees);
306                    }
307            }
308 $ret=true;
309 return $ret ;
310}
311
312/*
313 *
314 *
315 * @param:
316 *   
317 *   - args: function params of mail function:
318 *       o from: sender [default value webmaster email]
319 *       o Cc: array of carbon copy receivers of the mail. [default value empty]
320 *       o Bcc: array of blind carbon copy receivers of the mail. [default value empty]
321 *       o subject  [default value 'Piwigo']
322 *       o content: content of mail    [default value '']
323 *       o content_format: format of mail content  [default value 'text/plain']
324 *       o email_format: global mail format  [default value $conf_mail['default_email_format']]
325 *       o theme: template to use [default get_default_theme()]
326 *
327 * @return boolean (Ok or not)
328 */
329function cl_pwg_mail(  $args = array())
330{
331  global $conf, $conf_mail, $lang_info, $page;   
332  global $erreur_message ;
333  if (!isset($conf_mail)) {
334    $conf_mail = get_mail_configuration();
335  }
336  if (empty($args['email_format']))  {
337    $args['email_format'] = $conf_mail['default_email_format'];
338  }
339  // Compute root_path in order have complete path
340  set_make_full_url(); 
341  if (!isset($args['content'])) {
342    $args['content'] = '';
343  }
344  if (empty($args['content_format']))  {
345    $args['content_format'] = 'text/plain';  }
346  if (empty($args['theme']))  {
347    $args['theme'] = get_default_theme();
348  }
349
350  // List on content-type
351  $content_type_list[] = $args['email_format'];
352  if (!empty($conf_mail['alternative_email_format']))  {
353    $content_type_list[] = $conf_mail['alternative_email_format'];
354  }
355  $content = '';
356  foreach (array_unique($content_type_list) as $content_type)
357  {
358    // key compose of indexes witch allow ti cache mail data
359    $cache_key = $content_type.'-'.$lang_info['code'].'-'.$args['theme'];
360    unset($conf_mail[$cache_key]);
361    if (!isset($conf_mail[$cache_key])){
362      if (!isset($conf_mail[$cache_key]['theme'])){
363        $conf_mail[$cache_key]['theme'] = get_mail_template($content_type, $args['theme']);
364      }
365      $conf_mail[$cache_key]['theme']->set_filename('mail_header', 'header.tpl');
366      $conf_mail[$cache_key]['theme']->set_filename('mail_footer', 'footer.tpl');
367      $conf_mail[$cache_key]['theme']->assign(
368        array(
369          //Header
370          'BOUNDARY_KEY' => $conf_mail['boundary_key'],
371          'CONTENT_TYPE' => $content_type,
372          'CONTENT_ENCODING' => get_pwg_charset(),
373
374          // Footer
375          'GALLERY_URL' => get_gallery_home_url(),
376          'GALLERY_TITLE' =>
377            isset($page['gallery_title']) ?
378                  $page['gallery_title'] : $conf['gallery_title'],
379          'VERSION' => $conf['show_version'] ? PHPWG_VERSION : '',
380          'PHPWG_URL' => PHPWG_URL,
381
382          'TITLE_MAIL' => urlencode(l10n('A comment on your site')),
383          'MAIL' => get_webmaster_mail_address()
384          ));
385
386      if ($content_type == 'text/html'){
387        if ($conf_mail[$cache_key]['theme']->smarty->template_exists('global-mail-css.tpl')){
388          $conf_mail[$cache_key]['theme']->set_filename('css', 'global-mail-css.tpl');
389          $conf_mail[$cache_key]['theme']->assign_var_from_handle('GLOBAL_MAIL_CSS', 'css');
390        }
391
392        $file = PHPWG_ROOT_PATH.'themes/'.$args['theme'].'/mail-css.tpl';
393        if (is_file($file)){
394          $conf_mail[$cache_key]['theme']->set_filename('css', realpath($file));
395          $conf_mail[$cache_key]['theme']->assign_var_from_handle('MAIL_CSS', 'css');
396        }
397      } 
398
399      // what are displayed on the header of each mail ?
400      $conf_mail[$cache_key]['header'] =
401        $conf_mail[$cache_key]['theme']->parse('mail_header', true);
402
403      // what are displayed on the footer of each mail ?
404      $conf_mail[$cache_key]['footer'] =
405        $conf_mail[$cache_key]['theme']->parse('mail_footer', true);
406    }
407
408    // Header
409   $content.= $conf_mail[$cache_key]['header'];
410       // Content
411    if (($args['content_format'] == 'text/plain') and ($content_type == 'text/html')){
412      $content.= '<p>'.
413                  nl2br(
414                    preg_replace("/(http:\/\/)([^\s,]*)/i",
415                                 "<a href='$1$2' class='thumblnk'>$1$2</a>",
416                                 htmlspecialchars($args['content']))).
417                  '</p>';
418    } else if (($args['content_format'] == 'text/html') and ($content_type == 'text/plain')) {
419      // convert html text to plain text
420      $content.= strip_tags($args['content']);
421    } else {
422      $content.= $args['content'];
423    }
424
425    // Footer 
426    $content.= $conf_mail[$cache_key]['footer']."\n\n";
427   
428    // Close boundary
429    $content.= "\n\n".'-----='.$conf_mail['boundary_key'].'--'."\n\n";
430  }
431   // Undo Compute root_path in order have complete path
432  unset_make_full_url(); 
433
434  $pattern = '/(http:\/\/)([0-9].*)([0-9]\/)/'; 
435  if(preg_match($pattern, $content)){
436  //remplace 192.168.1.25 par rien ??
437      $replacement = '${1}'; 
438      $content = preg_replace( $pattern, $replacement,  $content ); 
439      //$content1 =   htmlspecialchars( var_export($content, true ) );     
440}
441
442      $content= preg_replace('#(?<!\r)\n#si', "\r\n", $content); //drop LF barre
443
444  return    $content;
445 
446}
447
448?>
Note: See TracBrowser for help on using the repository browser.