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

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