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

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

Fix bad default value for language on table user_info
Improve mail send (Undisclosed-recipients, switch language, ...)
Improve send an email to group members (Use Bcc, template, multi-language, ...) (But need more improvements)

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