source: trunk/include/functions_mail.inc.php @ 1914

Last change on this file since 1914 was 1914, checked in by rub, 17 years ago

Fix bug: Don't invoke mail function when there aren't recipient.

  • Property svn:keywords set to Author Date Id Revision
File size: 18.6 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | PhpWebGallery - a PHP based picture gallery                           |
4// | Copyright (C) 2002-2003 Pierrick LE GALL - pierrick@phpwebgallery.net |
5// | Copyright (C) 2003-2007 PhpWebGallery Team - http://phpwebgallery.net |
6// | Copyright (C) 2006-2007 Ruben ARNAUD - team@phpwebgallery.net         |
7// +-----------------------------------------------------------------------+
8// | file          : $Id: functions_mail.inc.php 1914 2007-03-16 12:08:25Z rub $
9// | last update   : $Date: 2007-03-16 12:08:25 +0000 (Fri, 16 Mar 2007) $
10// | last modifier : $Author: rub $
11// | revision      : $Revision: 1914 $
12// +-----------------------------------------------------------------------+
13// | This program is free software; you can redistribute it and/or modify  |
14// | it under the terms of the GNU General Public License as published by  |
15// | the Free Software Foundation                                          |
16// |                                                                       |
17// | This program is distributed in the hope that it will be useful, but   |
18// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
19// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
20// | General Public License for more details.                              |
21// |                                                                       |
22// | You should have received a copy of the GNU General Public License     |
23// | along with this program; if not, write to the Free Software           |
24// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
25// | USA.                                                                  |
26// +-----------------------------------------------------------------------+
27
28// +-----------------------------------------------------------------------+
29// |                               functions                               |
30// +-----------------------------------------------------------------------+
31
32/*
33 * Returns an array of mail configuration parameters :
34 *
35 * - mail_options: see $conf['mail_options']
36 * - send_bcc_mail_webmaster: see $conf['send_bcc_mail_webmaster']
37 * - email_webmaster: mail corresponding to $conf['webmaster_id']
38 * - formated_email_webmaster: the name of webmaster is $conf['gallery_title']
39 * - text_footer: PhpWebGallery and version
40 *
41 * @return array
42 */
43function get_mail_configuration()
44{
45  global $conf;
46
47  $conf_mail = array(
48    'mail_options' => $conf['mail_options'],
49    'send_bcc_mail_webmaster' => $conf['send_bcc_mail_webmaster'],
50    'default_email_format' => $conf['default_email_format']
51    );
52
53  // we have webmaster id among user list, what's his email address ?
54  $conf_mail['email_webmaster'] = get_webmaster_mail_address();
55
56  // name of the webmaster is the title of the gallery
57  $conf_mail['formated_email_webmaster'] =
58    format_email($conf['gallery_title'], $conf_mail['email_webmaster']);
59
60  $conf_mail['boundary_key'] = generate_key(32);
61
62  return $conf_mail;
63}
64
65/**
66 * Returns an email address with an associated real name
67 *
68 * @param string name
69 * @param string email
70 */
71function format_email($name, $email)
72{
73  global $conf;
74
75  if ($conf['enabled_format_email'])
76  {
77    $cvt7b_name = str_translate_to_ascii7bits($name);
78
79    if (strpos($email, '<') === false)
80    {
81      return $cvt7b_name.' <'.$email.'>';
82    }
83    else
84    {
85      return $cvt7b_name.$email;
86    }
87  }
88  else
89  {
90    return $email;
91  }
92}
93
94/**
95 * Returns an completed array template/theme
96 * completed with $conf['default_template']
97 *
98 * @params:
99 *   - args: incompleted array of template/theme
100 *       o template: template to use [default $conf['default_template']]
101 *       o theme: template to use [default $conf['default_template']]
102 */
103function get_array_template_theme($args = array())
104{
105  global $conf;
106
107  $res = array();
108 
109  if (empty($args['template']) or empty($args['theme']))
110  {
111    list($res['template'], $res['theme']) = explode('/', $conf['default_template']);
112  }
113
114  if (!empty($args['template']))
115  {
116    $res['template'] = $args['template'];
117  }
118
119  if (!empty($args['theme']))
120  {
121    $res['theme'] = $args['theme'];
122  }
123
124  return $res;
125}
126
127/**
128 * Return an new mail template
129 *
130 * @params:
131 *   - email_format: mail format
132 *   - args: function params of mail function:
133 *       o template: template to use [default $conf['default_template']]
134 *       o theme: template to use [default $conf['default_template']]
135 */
136function get_mail_template($email_format, $args = array())
137{
138  $args = get_array_template_theme($args);
139
140  $mail_template = new Template(PHPWG_ROOT_PATH.'template/'.$args['template'], $args['theme']);
141  $mail_template->set_rootdir(PHPWG_ROOT_PATH.'template/'.$args['template'].'/mail/'.$email_format);
142
143  return $mail_template;
144}
145
146/**
147 * Return string email format (html or not)
148 *
149 * @param string format
150 */
151function get_str_email_format($is_html)
152{
153  return ($is_html ? 'text/html' : 'text/plain');
154}
155
156/*
157 * Switch language to param language
158 * All entries are push on language stack
159 *
160 * @param string language
161 */
162function switch_lang_to($language)
163{
164  global $switch_lang, $user, $lang, $lang_info;
165
166  if (count($switch_lang['stack']) == 0)
167  {
168    $prev_language = $user['language'];
169  }
170  else
171  {
172    $prev_language = end($switch_lang['stack']);
173  }
174
175  $switch_lang['stack'][] = $language;
176
177  if ($prev_language != $language)
178  {
179    if (!isset($switch_lang['language'][$prev_language]))
180    {
181      $switch_lang[$prev_language]['lang_info'] = $lang_info;
182      $switch_lang[$prev_language]['lang'] = $lang;
183    }
184
185    if (!isset($switch_lang['language'][$language]))
186    {
187      // Re-Init language arrays
188      $lang_info = array();
189      $lang  = array();
190
191      // language files
192      include(get_language_filepath('common.lang.php', '', $language));
193      // No test admin because script is checked admin (user selected no)
194      // Translations are in admin file too
195      include(get_language_filepath('admin.lang.php', '', $language));
196      trigger_action('loading_lang');
197      @include(get_language_filepath('local.lang.php', '', $language));
198
199      $switch_lang[$language]['lang_info'] = $lang_info;
200      $switch_lang[$language]['lang'] = $lang;
201    }
202    else
203    {
204      $lang_info = $switch_lang[$language]['lang_info'];
205      $lang = $switch_lang[$language]['lang'];
206    }
207  }
208}
209
210/*
211 * Switch back language pushed with switch_lang_to function
212 *
213 * @param: none
214 */
215function switch_lang_back()
216{
217  global $switch_lang, $user, $lang, $lang_info;
218
219  $last_language = array_pop($switch_lang['stack']);
220
221  if (count($switch_lang['stack']) > 0)
222  {
223    $language = end($switch_lang['stack']);
224  }
225  else
226  {
227    $language = $user['language'];
228  }
229
230  if ($last_language != $language)
231  {
232    if (!isset($switch_lang['language'][$language]))
233    {
234      $lang_info = $switch_lang[$language]['lang_info'];
235      $lang = $switch_lang[$language]['lang'];
236    }
237  }
238}
239
240/**
241 * Returns email of all administrator
242 *
243 * @return string
244 */
245/*
246 * send en notification email to all administrators
247 * if a administrator is doing action,
248 * he's be removed to email list
249 *
250 * @param:
251 *   - keyargs_subject: mail subject on l10n_args format
252 *   - keyargs_content: mail content on l10n_args format
253 *
254 * @return boolean (Ok or not)
255 */
256function pwg_mail_notification_admins($keyargs_subject, $keyargs_content)
257{
258  global $conf, $user;
259  $return = true;
260
261  $admins = array();
262
263  $query = '
264select
265  U.'.$conf['user_fields']['username'].' as username,
266  U.'.$conf['user_fields']['email'].' as mail_address
267from
268  '.USERS_TABLE.' as U,
269  '.USER_INFOS_TABLE.' as I
270where
271  I.user_id =  U.'.$conf['user_fields']['id'].' and
272  I.status in (\'webmaster\',  \'admin\') and
273  I.adviser = \'false\' and
274  '.$conf['user_fields']['email'].' is not null and
275  I.user_id <> '.$user['id'].'
276order by
277  username
278';
279
280  $datas = pwg_query($query);
281  if (!empty($datas))
282  {
283    while ($admin = mysql_fetch_array($datas))
284    {
285      if (!empty($admin['mail_address']))
286      {
287        array_push($admins, format_email($admin['username'], $admin['mail_address']));
288      }
289    }
290  }
291
292  if (count($admins) > 0)
293  {
294    $keyargs_content_admin_info = array
295    (
296      get_l10n_args('Connected user: %s', $user['username']),
297      get_l10n_args('IP: %s', $_SERVER['REMOTE_ADDR']),
298      get_l10n_args('Browser: %s', $_SERVER['HTTP_USER_AGENT'])
299    );
300
301    switch_lang_to($conf['default_language']);
302
303    $return = pwg_mail
304    (
305      '',
306      array
307      (
308        'Bcc' => $admins,
309        'subject' => '['.$conf['gallery_title'].'] '.l10n_args($keyargs_subject),
310        'content' => 
311           l10n_args($keyargs_content)."\n\n"
312          .l10n_args($keyargs_content_admin_info)."\n",
313        'content_format' => 'text/plain'
314      )
315    ) and $return;
316
317    switch_lang_back();
318  }
319
320  return $return;
321}
322
323/*
324 * send en email to user's group
325 *
326 * @param:
327 *   - group_id: mail are sent to group with this Id
328 *   - email_format: mail format
329 *   - keyargs_subject: mail subject on l10n_args format
330 *   - tpl_shortname: short template name without extension
331 *   - assign_vars: array used to assign_vars to mail template
332 *   - language_selected: send mail only to user with this selected language
333 *
334 * @return boolean (Ok or not)
335 */
336function pwg_mail_group(
337  $group_id, $email_format, $keyargs_subject, 
338  $tpl_shortname, $assign_vars = array(), $language_selected = '')
339{
340  global $conf;
341  $return = true;
342
343  $query = '
344SELECT
345  distinct language, template
346FROM
347  '.USER_GROUP_TABLE.' as ug
348  INNER JOIN '.USERS_TABLE.' as u  ON '.$conf['user_fields']['id'].' = ug.user_id
349  INNER JOIN '.USER_INFOS_TABLE.' as ui  ON ui.user_id = ug.user_id
350WHERE
351        '.$conf['user_fields']['email'].' IS NOT NULL
352    AND group_id = '.$group_id;
353
354  if (!empty($language_selected))
355  {
356    $query .= '
357    AND language = \''.$language_selected.'\'';
358  }
359
360    $query .= '
361;';
362
363  $result = pwg_query($query);
364
365  if (mysql_num_rows($result) > 0)
366  {
367    $list = array();
368    while ($row = mysql_fetch_array($result))
369    {
370      list($row['template'], $row['theme']) = explode('/', $row['template']);
371      $list[] = $row;
372    }
373  }
374
375  foreach ($list as $elem)
376  {
377    $query = '
378SELECT
379  u.'.$conf['user_fields']['username'].' as username,
380  u.'.$conf['user_fields']['email'].' as mail_address
381FROM
382  '.USER_GROUP_TABLE.' as ug
383  INNER JOIN '.USERS_TABLE.' as u  ON '.$conf['user_fields']['id'].' = ug.user_id
384  INNER JOIN '.USER_INFOS_TABLE.' as ui  ON ui.user_id = ug.user_id
385WHERE
386        '.$conf['user_fields']['email'].' IS NOT NULL
387    AND group_id = '.$group_id.'
388    AND language = \''.$elem['language'].'\'
389;';
390
391    $result = pwg_query($query);
392
393    if (mysql_num_rows($result) > 0)
394    {
395      $Bcc = array();
396      while ($row = mysql_fetch_array($result))
397      {
398        if (!empty($row['mail_address']))
399        {
400          array_push($Bcc, format_email($row['username'], $row['mail_address']));
401        }
402      }
403
404      if (count($Bcc) > 0)
405      {
406        switch_lang_to($elem['language']);
407
408        $mail_template = get_mail_template($email_format, $elem);
409        $mail_template->set_filename($tpl_shortname, 
410          (IN_ADMIN ? 'admin/' : '').$tpl_shortname.'.tpl');
411        $mail_template->assign_vars($assign_vars);
412
413        $return = pwg_mail
414        (
415          '',
416          array
417          (
418            'Bcc' => $Bcc,
419            'subject' => l10n_args($keyargs_subject),
420            'email_format' => $email_format,
421            'content' => $mail_template->parse($tpl_shortname, true),
422            'content_format' => $email_format,
423            'template' => $elem['template'],
424            'theme' => $elem['theme']
425          )
426        ) and $return;
427
428        switch_lang_back();
429      }
430    }
431  }
432
433  return $return;
434}
435
436
437/*
438 * sends an email, using PhpWebGallery specific informations
439 *
440 * @param:
441 *   - to: Receiver, or receivers of the mail.
442 *   - args: function params of mail function:
443 *       o from: sender [default value webmaster email]
444 *       o Cc: array of carbon copy receivers of the mail. [default value empty]
445 *       o Bcc: array of blind carbon copy receivers of the mail. [default value empty]
446 *       o subject  [default value 'PhpWebGallery']
447 *       o content: content of mail    [default value '']
448 *       o content_format: format of mail content  [default value 'text/plain']
449 *       o email_format: global mail format  [default value $conf_mail['default_email_format']]
450 *       o template: template to use [default $conf['default_template']]
451 *       o theme: template to use [default $conf['default_template']]
452 *
453 * @return boolean (Ok or not)
454 */
455function pwg_mail($to, $args = array())
456{
457  global $conf, $conf_mail, $lang_info, $page;
458
459  if (empty($to) and empty($args['Cc']) and empty($args['Bcc']))
460  {
461    return true;
462  }
463 
464  if (!isset($conf_mail))
465  {
466    $conf_mail = get_mail_configuration();
467  }
468
469  if (empty($args['email_format']))
470  {
471    $args['email_format'] = $conf_mail['default_email_format'];
472  }
473
474  // Compute root_path in order have complete path
475  if ($args['email_format'] == 'text/html')
476  {
477    set_make_full_url();
478  }
479
480  if (!empty($to))
481  {
482    $to = format_email('', $to);
483  }
484
485  if (empty($args['from']))
486  {
487    $args['from'] = $conf_mail['formated_email_webmaster'];
488  }
489  else
490  {
491    $args['from'] = format_email('', $args['from']);
492  }
493
494  if (empty($args['subject']))
495  {
496    $args['subject'] = 'PhpWebGallery';
497  }
498  $cvt7b_subject = str_translate_to_ascii7bits($args['subject']);
499
500  if (!isset($args['content']))
501  {
502    $args['content'] = '';
503  }
504
505  if (empty($args['content_format']))
506  {
507    $args['content_format'] = 'text/plain';
508  }
509
510  if ($conf_mail['send_bcc_mail_webmaster'])
511  {
512    $args['Bcc'][] = $conf_mail['formated_email_webmaster'];
513  }
514
515  if (($args['content_format'] == 'text/html') and ($args['email_format'] == 'text/plain'))
516  {
517    // Todo find function to convert html text to plain text
518    return false;
519  }
520
521  $args = array_merge($args, get_array_template_theme($args));
522
523  $headers = 'From: '.$args['from']."\n";
524  $headers.= 'Reply-To: '.$args['from']."\n";
525  if (empty($to))
526  {
527    $headers.= 'To: undisclosed-recipients: ;'."\n";
528  }
529
530  if (!empty($args['Cc']))
531  {
532    $headers.= 'Cc: '.implode(',', $args['Cc'])."\n";
533  }
534
535  if (!empty($args['Bcc']))
536  {
537    $headers.= 'Bcc: '.implode(',', $args['Bcc'])."\n";
538  }
539
540  $headers.= 'Content-Type: multipart/alternative;'."\n";
541  $headers.= '  boundary="---='.$conf_mail['boundary_key'].'";'."\n";
542  $headers.= '  reply-type=original'."\n";
543  $headers.= 'MIME-Version: 1.0'."\n";
544
545  $content = '';
546
547  if (!isset($conf_mail[$args['email_format']][$lang_info['charset']][$args['template']][$args['theme']]))
548  {
549    if (!isset($mail_template))
550    {
551      $mail_template = get_mail_template($args['email_format']);
552    }
553
554    $mail_template->set_filename('mail_header', 'header.tpl');
555    $mail_template->set_filename('mail_footer', 'footer.tpl');
556
557    $mail_template->assign_vars(
558      array(
559        //Header
560        'BOUNDARY_KEY' => $conf_mail['boundary_key'],
561        'CONTENT_TYPE' => $args['email_format'],
562        'CONTENT_ENCODING' => $lang_info['charset'],
563        'LANG' => $lang_info['code'],
564        'DIR' => $lang_info['direction'],
565       
566        // Footer
567        'GALLERY_URL' =>
568          isset($page['gallery_url']) ?
569                $page['gallery_url'] : $conf['gallery_url'],
570        'GALLERY_TITLE' =>
571          isset($page['gallery_title']) ?
572                $page['gallery_title'] : $conf['gallery_title'],
573        'VERSION' => $conf['show_version'] ? PHPWG_VERSION : '',
574        'PHPWG_URL' => PHPWG_URL,
575
576        'TITLE_MAIL' => urlencode(l10n('title_send_mail')),
577        'MAIL' => get_webmaster_mail_address()
578        ));
579
580    if ($args['email_format'] == 'text/html')
581    {
582      $old_root = $mail_template->root;
583
584      if (is_file($mail_template->root.'/global-mail-css.tpl'))
585      {
586        $mail_template->set_filename('global_mail_css', 'global-mail-css.tpl');
587        $mail_template->assign_var_from_handle('GLOBAL_MAIL_CSS', 'global_mail_css');
588      }
589
590      $mail_template->root = PHPWG_ROOT_PATH.'template/'.$args['template'].'/theme/'.$args['theme'];
591      if (is_file($mail_template->root.'/mail-css.tpl'))
592      {
593        $mail_template->set_filename('mail_css', 'mail-css.tpl');
594        $mail_template->assign_var_from_handle('MAIL_CSS', 'mail_css');
595      }
596
597      $mail_template->root = PHPWG_ROOT_PATH.'template-common';
598      if (is_file($mail_template->root.'/local-mail-css.tpl'))
599      {
600        $mail_template->set_filename('local_mail_css', 'local-mail-css.tpl');
601        $mail_template->assign_var_from_handle('LOCAL_MAIL_CSS', 'local_mail_css');
602      }
603
604      $mail_template->root = $old_root;
605    }
606
607    // what are displayed on the header of each mail ?
608    $conf_mail[$args['email_format']]
609      [$lang_info['charset']]
610      [$args['template']][$args['theme']]['header'] =
611        $mail_template->parse('mail_header', true);
612
613    // what are displayed on the footer of each mail ?
614    $conf_mail[$args['email_format']]
615      [$lang_info['charset']]
616      [$args['template']][$args['theme']]['footer'] =
617        $mail_template->parse('mail_footer', true);
618  }
619
620  // Header
621  $content.= $conf_mail[$args['email_format']]
622              [$lang_info['charset']]
623              [$args['template']][$args['theme']]['header'];
624
625  // Content
626  if (($args['content_format'] == 'text/plain') and ($args['email_format'] == 'text/html'))
627  {
628    $content.= '<p>'.
629                nl2br(
630                  preg_replace("/(http:\/\/)([^\s,]*)/i",
631                               "<a href='$1$2'>$1$2</a>",
632                               htmlentities($args['content']))).
633                '</p>';
634  }
635  else
636  {
637    $content.= $args['content'];
638  }
639
640  // Footer
641  $content.= $conf_mail[$args['email_format']]
642              [$lang_info['charset']]
643              [$args['template']][$args['theme']]['footer'];
644
645  // Close boundary
646  $content.= "\n".'-----='.$conf_mail['boundary_key'].'--'."\n";
647
648   // Undo Compute root_path in order have complete path
649  if ($args['email_format'] == 'text/html')
650  {
651    unset_make_full_url();
652  }
653
654  /*Testing block
655  {
656    global $user;
657    @mkdir(PHPWG_ROOT_PATH.'testmail');
658    $filename = PHPWG_ROOT_PATH.'testmail/mail.'.$user['username'];
659    if ($args['content_format'] == 'text/plain')
660    {
661      $filename .= '.txt';
662    }
663    else
664    {
665      $filename .= '.html';
666    }
667    $file = fopen($filename, 'w+');
668    fwrite($file, $content);
669    fclose($file);
670    return true;
671  }*/
672
673  if ($conf_mail['mail_options'])
674  {
675    $options = '-f '.$conf_mail['email_webmaster'];
676   
677    return mail($to, $cvt7b_subject, $content, $headers, $options);
678  }
679  else
680  {
681    return mail($to, $cvt7b_subject, $content, $headers);
682  }
683}
684
685?>
Note: See TracBrowser for help on using the repository browser.