source: branches/branch-1_7/include/functions_mail.inc.php @ 2049

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

Resolved issue 0000715: Fix bad format of email with name contains special character.

+ Ignore all for plugins and theme directories

  • Property svn:keywords set to Author Date Id Revision
File size: 18.8 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 2049 2007-07-02 06:26:44Z rub $
9// | last update   : $Date: 2007-07-02 06:26:44 +0000 (Mon, 02 Jul 2007) $
10// | last modifier : $Author: rub $
11// | revision      : $Revision: 2049 $
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 '"'.addslashes($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 get_default_template()
97 *
98 * @params:
99 *   - args: incompleted array of template/theme
100 *       o template: template to use [default get_default_template()]
101 *       o theme: template to use [default get_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('/', get_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 get_default_template()]
134 *       o theme: template to use [default get_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(get_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 *   - dirname: short name of directory including template
331 *   - tpl_shortname: short template name without extension
332 *   - assign_vars: array used to assign_vars to mail template
333 *   - language_selected: send mail only to user with this selected language
334 *
335 * @return boolean (Ok or not)
336 */
337function pwg_mail_group(
338  $group_id, $email_format, $keyargs_subject, 
339  $dirname, $tpl_shortname,
340  $assign_vars = array(), $language_selected = '')
341{
342  global $conf;
343  $return = true;
344
345  $query = '
346SELECT
347  distinct language, template
348FROM
349  '.USER_GROUP_TABLE.' as ug
350  INNER JOIN '.USERS_TABLE.' as u  ON '.$conf['user_fields']['id'].' = ug.user_id
351  INNER JOIN '.USER_INFOS_TABLE.' as ui  ON ui.user_id = ug.user_id
352WHERE
353        '.$conf['user_fields']['email'].' IS NOT NULL
354    AND group_id = '.$group_id;
355
356  if (!empty($language_selected))
357  {
358    $query .= '
359    AND language = \''.$language_selected.'\'';
360  }
361
362    $query .= '
363;';
364
365  $result = pwg_query($query);
366
367  if (mysql_num_rows($result) > 0)
368  {
369    $list = array();
370    while ($row = mysql_fetch_array($result))
371    {
372      $row['template_theme'] = $row['template'];
373      list($row['template'], $row['theme']) = explode('/', $row['template_theme']);
374      $list[] = $row;
375    }
376  }
377
378  foreach ($list as $elem)
379  {
380    $query = '
381SELECT
382  u.'.$conf['user_fields']['username'].' as username,
383  u.'.$conf['user_fields']['email'].' as mail_address
384FROM
385  '.USER_GROUP_TABLE.' as ug
386  INNER JOIN '.USERS_TABLE.' as u  ON '.$conf['user_fields']['id'].' = ug.user_id
387  INNER JOIN '.USER_INFOS_TABLE.' as ui  ON ui.user_id = ug.user_id
388WHERE
389        '.$conf['user_fields']['email'].' IS NOT NULL
390    AND group_id = '.$group_id.'
391    AND language = \''.$elem['language'].'\'
392    AND template = \''.$elem['template_theme'].'\'
393;';
394
395    $result = pwg_query($query);
396
397    if (mysql_num_rows($result) > 0)
398    {
399      $Bcc = array();
400      while ($row = mysql_fetch_array($result))
401      {
402        if (!empty($row['mail_address']))
403        {
404          array_push($Bcc, format_email($row['username'], $row['mail_address']));
405        }
406      }
407
408      if (count($Bcc) > 0)
409      {
410        switch_lang_to($elem['language']);
411
412        $mail_template = get_mail_template($email_format, $elem);
413        $mail_template->set_filename($tpl_shortname, 
414          (empty($dirname) ? '' : $dirname.'/').$tpl_shortname.'.tpl');
415        $mail_template->assign_vars($assign_vars);
416
417        $return = pwg_mail
418        (
419          '',
420          array
421          (
422            'Bcc' => $Bcc,
423            'subject' => l10n_args($keyargs_subject),
424            'email_format' => $email_format,
425            'content' => $mail_template->parse($tpl_shortname, true),
426            'content_format' => $email_format,
427            'template' => $elem['template'],
428            'theme' => $elem['theme']
429          )
430        ) and $return;
431
432        switch_lang_back();
433      }
434    }
435  }
436
437  return $return;
438}
439
440
441/*
442 * sends an email, using PhpWebGallery specific informations
443 *
444 * @param:
445 *   - to: Receiver, or receivers of the mail.
446 *   - args: function params of mail function:
447 *       o from: sender [default value webmaster email]
448 *       o Cc: array of carbon copy receivers of the mail. [default value empty]
449 *       o Bcc: array of blind carbon copy receivers of the mail. [default value empty]
450 *       o subject  [default value 'PhpWebGallery']
451 *       o content: content of mail    [default value '']
452 *       o content_format: format of mail content  [default value 'text/plain']
453 *       o email_format: global mail format  [default value $conf_mail['default_email_format']]
454 *       o template: template to use [default get_default_template()]
455 *       o theme: template to use [default get_default_template()]
456 *
457 * @return boolean (Ok or not)
458 */
459function pwg_mail($to, $args = array())
460{
461  global $conf, $conf_mail, $lang_info, $page;
462
463  if (empty($to) and empty($args['Cc']) and empty($args['Bcc']))
464  {
465    return true;
466  }
467 
468  if (!isset($conf_mail))
469  {
470    $conf_mail = get_mail_configuration();
471  }
472
473  if (empty($args['email_format']))
474  {
475    $args['email_format'] = $conf_mail['default_email_format'];
476  }
477
478  // Compute root_path in order have complete path
479  if ($args['email_format'] == 'text/html')
480  {
481    set_make_full_url();
482  }
483
484  if (!empty($to))
485  {
486    $to = format_email('', $to);
487  }
488
489  if (empty($args['from']))
490  {
491    $args['from'] = $conf_mail['formated_email_webmaster'];
492  }
493  else
494  {
495    $args['from'] = format_email('', $args['from']);
496  }
497
498  if (empty($args['subject']))
499  {
500    $args['subject'] = 'PhpWebGallery';
501  }
502  $cvt7b_subject = str_translate_to_ascii7bits($args['subject']);
503
504  if (!isset($args['content']))
505  {
506    $args['content'] = '';
507  }
508
509  if (empty($args['content_format']))
510  {
511    $args['content_format'] = 'text/plain';
512  }
513
514  if ($conf_mail['send_bcc_mail_webmaster'])
515  {
516    $args['Bcc'][] = $conf_mail['formated_email_webmaster'];
517  }
518
519  if (($args['content_format'] == 'text/html') and ($args['email_format'] == 'text/plain'))
520  {
521    // Todo find function to convert html text to plain text
522    return false;
523  }
524
525  $args = array_merge($args, get_array_template_theme($args));
526
527  $headers = 'From: '.$args['from']."\n";
528  $headers.= 'Reply-To: '.$args['from']."\n";
529  if (empty($to))
530  {
531    $headers.= 'To: undisclosed-recipients: ;'."\n";
532  }
533
534  if (!empty($args['Cc']))
535  {
536    $headers.= 'Cc: '.implode(',', $args['Cc'])."\n";
537  }
538
539  if (!empty($args['Bcc']))
540  {
541    $headers.= 'Bcc: '.implode(',', $args['Bcc'])."\n";
542  }
543
544  $headers.= 'Content-Type: multipart/alternative;'."\n";
545  $headers.= '  boundary="---='.$conf_mail['boundary_key'].'";'."\n";
546  $headers.= '  reply-type=original'."\n";
547  $headers.= 'MIME-Version: 1.0'."\n";
548
549  $content = '';
550
551  if (!isset($conf_mail[$args['email_format']][$lang_info['charset']][$args['template']][$args['theme']]))
552  {
553    if (!isset($mail_template))
554    {
555      $mail_template = get_mail_template($args['email_format']);
556    }
557
558    $mail_template->set_filename('mail_header', 'header.tpl');
559    $mail_template->set_filename('mail_footer', 'footer.tpl');
560
561    $mail_template->assign_vars(
562      array(
563        //Header
564        'BOUNDARY_KEY' => $conf_mail['boundary_key'],
565        'CONTENT_TYPE' => $args['email_format'],
566        'CONTENT_ENCODING' => $lang_info['charset'],
567        'LANG' => $lang_info['code'],
568        'DIR' => $lang_info['direction'],
569       
570        // Footer
571        'GALLERY_URL' =>
572          isset($page['gallery_url']) ?
573                $page['gallery_url'] : $conf['gallery_url'],
574        'GALLERY_TITLE' =>
575          isset($page['gallery_title']) ?
576                $page['gallery_title'] : $conf['gallery_title'],
577        'VERSION' => $conf['show_version'] ? PHPWG_VERSION : '',
578        'PHPWG_URL' => PHPWG_URL,
579
580        'TITLE_MAIL' => urlencode(l10n('title_send_mail')),
581        'MAIL' => get_webmaster_mail_address()
582        ));
583
584    if ($args['email_format'] == 'text/html')
585    {
586      $old_root = $mail_template->root;
587
588      if (is_file($mail_template->root.'/global-mail-css.tpl'))
589      {
590        $mail_template->set_filename('global_mail_css', 'global-mail-css.tpl');
591        $mail_template->assign_var_from_handle('GLOBAL_MAIL_CSS', 'global_mail_css');
592      }
593
594      $mail_template->root = PHPWG_ROOT_PATH.'template/'.$args['template'].'/theme/'.$args['theme'];
595      if (is_file($mail_template->root.'/mail-css.tpl'))
596      {
597        $mail_template->set_filename('mail_css', 'mail-css.tpl');
598        $mail_template->assign_var_from_handle('MAIL_CSS', 'mail_css');
599      }
600
601      $mail_template->root = PHPWG_ROOT_PATH.'template-common';
602      if (is_file($mail_template->root.'/local-mail-css.tpl'))
603      {
604        $mail_template->set_filename('local_mail_css', 'local-mail-css.tpl');
605        $mail_template->assign_var_from_handle('LOCAL_MAIL_CSS', 'local_mail_css');
606      }
607
608      $mail_template->root = $old_root;
609    }
610
611    // what are displayed on the header of each mail ?
612    $conf_mail[$args['email_format']]
613      [$lang_info['charset']]
614      [$args['template']][$args['theme']]['header'] =
615        $mail_template->parse('mail_header', true);
616
617    // what are displayed on the footer of each mail ?
618    $conf_mail[$args['email_format']]
619      [$lang_info['charset']]
620      [$args['template']][$args['theme']]['footer'] =
621        $mail_template->parse('mail_footer', true);
622  }
623
624  // Header
625  $content.= $conf_mail[$args['email_format']]
626              [$lang_info['charset']]
627              [$args['template']][$args['theme']]['header'];
628
629  // Content
630  if (($args['content_format'] == 'text/plain') and ($args['email_format'] == 'text/html'))
631  {
632    $content.= '<p>'.
633                nl2br(
634                  preg_replace("/(http:\/\/)([^\s,]*)/i",
635                               "<a href='$1$2'>$1$2</a>",
636                               htmlentities($args['content']))).
637                '</p>';
638  }
639  else
640  {
641    $content.= $args['content'];
642  }
643
644  // Footer
645  $content.= $conf_mail[$args['email_format']]
646              [$lang_info['charset']]
647              [$args['template']][$args['theme']]['footer'];
648
649  // Close boundary
650  $content.= "\n".'-----='.$conf_mail['boundary_key'].'--'."\n";
651
652   // Undo Compute root_path in order have complete path
653  if ($args['email_format'] == 'text/html')
654  {
655    unset_make_full_url();
656  }
657
658  /*Testing block
659  {
660    global $user;
661    @mkdir(PHPWG_ROOT_PATH.'testmail');
662    $filename = PHPWG_ROOT_PATH.'testmail/mail.'.$user['username'];
663    if ($args['content_format'] == 'text/plain')
664    {
665      $filename .= '.txt';
666    }
667    else
668    {
669      $filename .= '.html';
670    }
671    $file = fopen($filename, 'w+');
672    fwrite($file, $content);
673    fclose($file);
674    return true;
675  }*/
676
677  if ($conf_mail['mail_options'])
678  {
679    $options = '-f '.$conf_mail['email_webmaster'];
680   
681    return mail($to, $cvt7b_subject, $content, $headers, $options);
682  }
683  else
684  {
685    return mail($to, $cvt7b_subject, $content, $headers);
686  }
687}
688
689?>
Note: See TracBrowser for help on using the repository browser.