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

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

Change headers with team email

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