1<?php
2// +-----------------------------------------------------------------------+
3// | This file is part of Piwigo.                                          |
4// |                                                                       |
5// | For copyright and license information, please view the COPYING.txt    |
6// | file that was distributed with this source code.                      |
7// +-----------------------------------------------------------------------+
8
9/**
10 * @package functions\mail
11 */
12
13
14/**
15 * Returns the name of the mail sender
16 *
17 * @return string
18 */
19function get_mail_sender_name()
20{
21  global $conf;
22
23  return (empty($conf['mail_sender_name']) ? $conf['gallery_title'] : $conf['mail_sender_name']);
24}
25
26/**
27 * Returns the email of the mail sender
28 *
29 * @since 2.6
30 * @return string
31 */
32function get_mail_sender_email()
33{
34  global $conf;
35
36  return (empty($conf['mail_sender_email']) ? get_webmaster_mail_address() : $conf['mail_sender_email']);
37}
38
39/**
40 * Returns an array of mail configuration parameters.
41 * - send_bcc_mail_webmaster
42 * - mail_allow_html
43 * - use_smtp
44 * - smtp_host
45 * - smtp_user
46 * - smtp_password
47 * - smtp_secure
48 * - email_webmaster
49 * - name_webmaster
50 *
51 * @return array
52 */
53function get_mail_configuration()
54{
55  global $conf;
56
57  $conf_mail = array(
58    'send_bcc_mail_webmaster' => $conf['send_bcc_mail_webmaster'],
59    'mail_allow_html' => $conf['mail_allow_html'],
60    'mail_theme' => $conf['mail_theme'],
61    'use_smtp' => !empty($conf['smtp_host']),
62    'smtp_host' => $conf['smtp_host'],
63    'smtp_user' => $conf['smtp_user'],
64    'smtp_password' => $conf['smtp_password'],
65    'smtp_secure' => $conf['smtp_secure'],
66    'email_webmaster' => get_mail_sender_email(),
67    'name_webmaster' => get_mail_sender_name(),
68    );
69
70  return $conf_mail;
71}
72
73/**
74 * Returns an email address with an associated real name.
75 * Can return either:
76 *    - email@domain.com
77 *    - name <email@domain.com>
78 *
79 * @param string $name
80 * @param string $email
81 * @return string
82 */
83function format_email($name, $email)
84{
85  $cvt_email = trim(preg_replace('#[\n\r]+#s', '', $email));
86  $cvt_name = trim(preg_replace('#[\n\r]+#s', '', $name));
87
88  if ($cvt_name!="")
89  {
90    $cvt_name = '"'.addcslashes($cvt_name,'"').'"'.' ';
91  }
92
93  if (strpos($cvt_email, '<') === false)
94  {
95    return $cvt_name.'<'.$cvt_email.'>';
96  }
97  else
98  {
99    return $cvt_name.$cvt_email;
100  }
101}
102
103/**
104 * Returns the email and the name from a formatted address.
105 * @since 2.6
106 *
107 * @param string|string[] $input - if is an array must contain email[, name]
108 * @return array email, name
109 */
110function unformat_email($input)
111{
112  if (is_array($input))
113  {
114    if (!isset($input['name']))
115    {
116      $input['name'] = '';
117    }
118    return $input;
119  }
120
121  if (preg_match('/(.*)<(.*)>.*/', $input, $matches))
122  {
123    return array(
124      'email' => trim($matches[2]),
125      'name' => trim($matches[1]),
126      );
127  }
128  else
129  {
130    return array(
131      'email' => trim($input),
132      'name' => '',
133      );
134  }
135}
136
137/**
138 * Return a clean array of hashmaps (email, name) removing duplicates.
139 * It accepts various inputs:
140 *    - comma separated list
141 *    - array of emails
142 *    - single hashmap (email[, name])
143 *    - array of incomplete hashmaps
144 * @since 2.6
145 *
146 * @param mixed $data
147 * @return string[][]
148 */
149function get_clean_recipients_list($data)
150{
151  if (empty($data))
152  {
153    return array();
154  }
155  else if (is_array($data))
156  {
157    $values = array_values($data);
158    if (!is_array($values[0]))
159    {
160      $keys = array_keys($data);
161      if (is_int($keys[0]))
162      { // simple array of emails
163        foreach ($data as &$item)
164        {
165          $item = array(
166            'email' => trim($item),
167            'name' => '',
168            );
169        }
170        unset($item);
171      }
172      else
173      { // hashmap of one recipient
174        $data = array(unformat_email($data));
175      }
176    }
177    else
178    { // array of hashmaps
179      $data = array_map('unformat_email', $data);
180    }
181  }
182  else
183  {
184    $data = explode(',', $data);
185    $data = array_map('unformat_email', $data);
186  }
187
188  $existing = array();
189  foreach ($data as $i => $entry)
190  {
191    if (isset($existing[ $entry['email'] ]))
192    {
193      unset($data[$i]);
194    }
195    else
196    {
197      $existing[ $entry['email'] ] = true;
198    }
199  }
200
201  return array_values($data);
202}
203
204/**
205 * Returns an email address list with minimal email string.
206 * @deprecated 2.6
207 *
208 * @param string $email_list - comma separated
209 * @return string
210 */
211function get_strict_email_list($email_list)
212{
213  $result = array();
214  $list = explode(',', $email_list);
215
216  foreach ($list as $email)
217  {
218    if (strpos($email, '<') !== false)
219    {
220       $email = preg_replace('/.*<(.*)>.*/i', '$1', $email);
221    }
222    $result[] = trim($email);
223  }
224
225  return implode(',', array_unique($result));
226}
227
228/**
229 * Return an new mail template.
230 *
231 * @param string $email_format - text/html or text/plain
232 * @return Template
233 */
234function &get_mail_template($email_format)
235{
236  $template = new Template(PHPWG_ROOT_PATH.'themes', 'default', 'template/mail/'.$email_format);
237  return $template;
238}
239
240/**
241 * Return string email format (text/html or text/plain).
242 *
243 * @param bool $is_html
244 * @return string
245 */
246function get_str_email_format($is_html)
247{
248  return ($is_html ? 'text/html' : 'text/plain');
249}
250
251/**
252 * Switch language to specified language.
253 * All entries are push on language stack
254 *
255 * @param string $language
256 */
257function switch_lang_to($language)
258{
259  global $switch_lang, $user, $lang, $lang_info, $language_files;
260
261  // explanation of switch_lang
262  // $switch_lang['language'] contains data of language
263  // $switch_lang['stack'] contains stack LIFO
264  // $switch_lang['initialisation'] allow to know if it's first call
265
266  // Treatment with current user
267  // Language of current user is saved (it's considered OK on firt call)
268  if (!isset($switch_lang['initialisation']) and !isset($switch_lang['language'][$user['language']]))
269  {
270    $switch_lang['initialisation'] = true;
271    $switch_lang['language'][$user['language']]['lang_info'] = $lang_info;
272    $switch_lang['language'][$user['language']]['lang'] = $lang;
273  }
274
275  // Change current infos
276  $switch_lang['stack'][] = $user['language'];
277  $user['language'] = $language;
278
279  // Load new data if necessary
280  if (!isset($switch_lang['language'][$language]))
281  {
282    // Re-Init language arrays
283    $lang_info = array();
284    $lang  = array();
285
286    // language files
287    load_language('common.lang', '', array('language'=>$language) );
288    // No test admin because script is checked admin (user selected no)
289    // Translations are in admin file too
290    load_language('admin.lang', '', array('language'=>$language) );
291
292    // Reload all plugins files (see load_language declaration)
293    if (!empty($language_files))
294    {
295      foreach ($language_files as $dirname => $files)
296      {
297        foreach ($files as $filename => $options)
298        {
299          $options['language'] = $language;
300          load_language($filename, $dirname, $options);
301        }
302      }
303    }
304
305    trigger_notify('loading_lang');
306    load_language('lang', PHPWG_ROOT_PATH.PWG_LOCAL_DIR,
307      array('language'=>$language, 'no_fallback'=>true, 'local'=>true)
308    );
309
310    $switch_lang['language'][$language]['lang_info'] = $lang_info;
311    $switch_lang['language'][$language]['lang'] = $lang;
312  }
313  else
314  {
315    $lang_info = $switch_lang['language'][$language]['lang_info'];
316    $lang = $switch_lang['language'][$language]['lang'];
317  }
318}
319
320/**
321 * Switch back language pushed with switch_lang_to() function.
322 * @see switch_lang_to()
323 * Language files are not reloaded
324 */
325function switch_lang_back()
326{
327  global $switch_lang, $user, $lang, $lang_info;
328
329  if (count($switch_lang['stack']) > 0)
330  {
331    // Get last value
332    $language = array_pop($switch_lang['stack']);
333
334    // Change current infos
335    if (isset($switch_lang['language'][$language]))
336    {
337      $lang_info = $switch_lang['language'][$language]['lang_info'];
338      $lang = $switch_lang['language'][$language]['lang'];
339    }
340    $user['language'] = $language;
341  }
342}
343
344/**
345 * Send a notification email to all administrators.
346 * current user (if admin) is not notified
347 *
348 * @param string|array $subject
349 * @param string|array $content
350 * @param boolean $send_technical_details - send user IP and browser
351 * @return boolean
352 */
353function pwg_mail_notification_admins($subject, $content, $send_technical_details=true)
354{
355  if (empty($subject) or empty($content))
356  {
357    return false;
358  }
359
360  global $conf, $user;
361
362  if (is_array($subject) or is_array($content))
363  {
364    switch_lang_to(get_default_language());
365
366    if (is_array($subject))
367    {
368      $subject = l10n_args($subject);
369    }
370    if (is_array($content))
371    {
372      $content = l10n_args($content);
373    }
374
375    switch_lang_back();
376  }
377
378  $tpl_vars = array();
379  if ($send_technical_details)
380  {
381    $tpl_vars['TECHNICAL'] = array(
382      'username' => stripslashes($user['username']),
383      'ip' => $_SERVER['REMOTE_ADDR'],
384      'user_agent' => $_SERVER['HTTP_USER_AGENT'],
385      );
386  }
387
388  return pwg_mail_admins(
389    array(
390      'subject' => '['. $conf['gallery_title'] .'] '. $subject,
391      'mail_title' => $conf['gallery_title'],
392      'mail_subtitle' => $subject,
393      'content' => $content,
394      'content_format' => 'text/plain',
395      ),
396    array(
397      'filename' => 'notification_admin',
398      'assign' => $tpl_vars,
399      )
400    );
401}
402
403/**
404 * Send a email to all administrators.
405 * current user (if admin) is excluded
406 * @see pwg_mail()
407 * @since 2.6
408 *
409 * @param array $args - as in pwg_mail()
410 * @param array $tpl - as in pwg_mail()
411 * @return boolean
412 */
413function pwg_mail_admins($args=array(), $tpl=array(), $exclude_current_user=true, $only_webmasters=false)
414{
415  if (empty($args['content']) and empty($tpl))
416  {
417    return false;
418  }
419
420  global $conf, $user;
421  $return = true;
422
423  $user_statuses = array('webmaster');
424  if (!$only_webmasters)
425  {
426    $user_statuses[] = 'admin';
427  }
428
429  // get admins (except ourself)
430  $query = '
431SELECT
432    u.'.$conf['user_fields']['username'].' AS name,
433    u.'.$conf['user_fields']['email'].' AS email
434  FROM '.USERS_TABLE.' AS u
435    JOIN '.USER_INFOS_TABLE.' AS i
436    ON i.user_id =  u.'.$conf['user_fields']['id'].'
437  WHERE i.status in (\''.implode("','", $user_statuses).'\')
438    AND u.'.$conf['user_fields']['email'].' IS NOT NULL';
439
440  if ($exclude_current_user)
441  {
442    $query.= '
443    AND i.user_id <> '.$user['id'];
444  }
445
446  $query.= '
447  ORDER BY name
448;';
449  $admins = array_from_query($query);
450
451  if (empty($admins))
452  {
453    return $return;
454  }
455
456  switch_lang_to(get_default_language());
457
458  $return = pwg_mail($admins, $args, $tpl);
459
460  switch_lang_back();
461
462  return $return;
463}
464
465/**
466 * Send an email to a group.
467 * @see pwg_mail()
468 *
469 * @param int $group_id
470 * @param array $args - as in pwg_mail()
471 *       o language_selected: filters users of the group by language [default value empty]
472 * @param array $tpl - as in pwg_mail()
473 * @return boolean
474 */
475function pwg_mail_group($group_id, $args=array(), $tpl=array())
476{
477  if (empty($group_id) or ( empty($args['content']) and empty($tpl) ))
478  {
479    return false;
480  }
481
482  global $conf;
483  $return = true;
484
485  // get distinct languages of targeted users
486  $query = '
487SELECT DISTINCT language
488  FROM '.USER_GROUP_TABLE.' AS ug
489    INNER JOIN '.USERS_TABLE.' AS u
490    ON '.$conf['user_fields']['id'].' = ug.user_id
491    INNER JOIN '.USER_INFOS_TABLE.' AS ui
492    ON ui.user_id = ug.user_id
493  WHERE group_id = '.$group_id.'
494    AND '.$conf['user_fields']['email'].' <> ""';
495  if (!empty($args['language_selected']))
496  {
497    $query .= '
498    AND language = \''.$args['language_selected'].'\'';
499  }
500
501    $query .= '
502;';
503  $languages = array_from_query($query, 'language');
504
505  if (empty($languages))
506  {
507    return $return;
508  }
509
510  foreach ($languages as $language)
511  {
512    // get subset of users in this group for a specific language
513    $query = '
514SELECT
515    ui.user_id,
516    ui.status,
517    u.'.$conf['user_fields']['username'].' AS name,
518    u.'.$conf['user_fields']['email'].' AS email
519  FROM '.USER_GROUP_TABLE.' AS ug
520    INNER JOIN '.USERS_TABLE.' AS u
521    ON '.$conf['user_fields']['id'].' = ug.user_id
522    INNER JOIN '.USER_INFOS_TABLE.' AS ui
523    ON ui.user_id = ug.user_id
524  WHERE group_id = '.$group_id.'
525    AND '.$conf['user_fields']['email'].' <> ""
526    AND language = \''.$language.'\'
527;';
528    $users = array_from_query($query);
529
530    if (empty($users))
531    {
532      continue;
533    }
534
535    switch_lang_to($language);
536
537    foreach ($users as $u)
538    {
539      $authkey = create_user_auth_key($u['user_id'], $u['status']);
540
541      $user_tpl = $tpl;
542
543      if ($authkey !== false)
544      {
545        $user_tpl['assign']['LINK'] = add_url_params($tpl['assign']['LINK'], array('auth' => $authkey['auth_key']));
546
547        if (isset($user_tpl['assign']['IMG']['link']))
548        {
549          $user_tpl['assign']['IMG']['link'] = add_url_params(
550            $user_tpl['assign']['IMG']['link'],
551            array('auth' => $authkey['auth_key'])
552            );
553        }
554      }
555
556      $user_args = $args;
557      if ($authkey !== false)
558      {
559        $user_args['auth_key'] = $authkey['auth_key'];
560      }
561
562      $return &= pwg_mail($u['email'], $user_args, $user_tpl);
563    }
564
565    switch_lang_back();
566  }
567
568  return $return;
569}
570
571/**
572 * Sends an email, using Piwigo specific informations.
573 *
574 * @param string|array $to
575 * @param array $args
576 *       o from: sender [default value webmaster email]
577 *       o Cc: array of carbon copy receivers of the mail. [default value empty]
578 *       o Bcc: array of blind carbon copy receivers of the mail. [default value empty]
579 *       o subject [default value 'Piwigo']
580 *       o content: content of mail [default value '']
581 *       o content_format: format of mail content [default value 'text/plain']
582 *       o email_format: global mail format [default value $conf_mail['default_email_format']]
583 *       o theme: theme to use [default value $conf_mail['mail_theme']]
584 *       o mail_title: main title of the mail [default value $conf['gallery_title']]
585 *       o mail_subtitle: subtitle of the mail [default value subject]
586 *       o auth_key: authentication key to add on footer link [default value null]
587 * @param array $tpl - use these options to define a custom content template file
588 *       o filename
589 *       o dirname (optional)
590 *       o assign (optional)
591 *
592 * @return boolean
593 */
594function pwg_mail($to, $args=array(), $tpl=array())
595{
596  global $conf, $conf_mail, $lang_info, $page;
597
598  if (empty($to) and empty($args['Cc']) and empty($args['Bcc']))
599  {
600    return true;
601  }
602
603  if (!isset($conf_mail))
604  {
605    $conf_mail = get_mail_configuration();
606  }
607
608  // PHPMailer autoloader shows warnings with PHP 7.2. Solution to upgrade to PHPMailer 6
609  // implies requiring PHP 5.5, which is bigger than current requirement for Piwigo.
610  //
611  // include_once(PHPWG_ROOT_PATH.'include/phpmailer/PHPMailerAutoload.php');
612  //
613  // replace by direct include of the classes:
614  include_once(PHPWG_ROOT_PATH.'include/phpmailer/class.smtp.php');
615  include_once(PHPWG_ROOT_PATH.'include/phpmailer/class.phpmailer.php');
616
617  $mail = new PHPMailer;
618
619  foreach (get_clean_recipients_list($to) as $recipient)
620  {
621    $mail->addAddress($recipient['email'], $recipient['name']);
622  }
623
624  $mail->WordWrap = 76;
625  $mail->CharSet = 'UTF-8';
626
627  // Compute root_path in order have complete path
628  set_make_full_url();
629
630  if (empty($args['from']))
631  {
632    $from = array(
633      'email' => $conf_mail['email_webmaster'],
634      'name' => $conf_mail['name_webmaster'],
635      );
636  }
637  else
638  {
639    $from = unformat_email($args['from']);
640  }
641  $mail->setFrom($from['email'], $from['name']);
642  $mail->addReplyTo($from['email'], $from['name']);
643
644  // Subject
645  if (empty($args['subject']))
646  {
647    $args['subject'] = 'Piwigo';
648  }
649  $args['subject'] = trim(preg_replace('#[\n\r]+#s', '', $args['subject']));
650  $mail->Subject = $args['subject'];
651
652  // Cc
653  if (!empty($args['Cc']))
654  {
655    foreach (get_clean_recipients_list($args['Cc']) as $recipient)
656    {
657      $mail->addCC($recipient['email'], $recipient['name']);
658    }
659  }
660
661  // Bcc
662  $Bcc = get_clean_recipients_list(@$args['Bcc']);
663  if ($conf_mail['send_bcc_mail_webmaster'])
664  {
665    $Bcc[] = array(
666      'email' => get_webmaster_mail_address(),
667      'name' => '',
668      );
669  }
670  if (!empty($Bcc))
671  {
672    foreach ($Bcc as $recipient)
673    {
674      $mail->addBCC($recipient['email'], $recipient['name']);
675    }
676  }
677
678  // theme
679  if (empty($args['theme']) or !in_array($args['theme'], array('clear','dark')))
680  {
681    $args['theme'] = $conf_mail['mail_theme'];
682  }
683
684  // content
685  if (!isset($args['content']))
686  {
687    $args['content'] = '';
688  }
689
690  // try to decompose subject like "[....] ...."
691  if (!isset($args['mail_title']) and !isset($args['mail_subtitle']))
692  {
693    if (preg_match('#^\[(.*)\](.*)$#',  $args['subject'], $matches))
694    {
695      $args['mail_title'] = $matches[1];
696      $args['mail_subtitle'] = $matches[2];
697    }
698  }
699  if (!isset($args['mail_title']))
700  {
701    $args['mail_title'] = $conf['gallery_title'];
702  }
703  if (!isset($args['mail_subtitle']))
704  {
705    $args['mail_subtitle'] = $args['subject'];
706  }
707
708  // content type
709  if (empty($args['content_format']))
710  {
711    $args['content_format'] = 'text/plain';
712  }
713
714  $content_type_list = array();
715  if ($conf_mail['mail_allow_html'] and @$args['email_format'] != 'text/plain')
716  {
717    $content_type_list[] = 'text/html';
718  }
719  $content_type_list[] = 'text/plain';
720
721  $contents = array();
722  foreach ($content_type_list as $content_type)
723  {
724    // key compose of indexes witch allow to cache mail data
725    $cache_key = $content_type.'-'.$lang_info['code'];
726    if (!empty($args['auth_key']))
727    {
728      $cache_key.= '-'.$args['auth_key'];
729    }
730
731    if (!isset($conf_mail[$cache_key]))
732    {
733      // instanciate a new Template
734      if (!isset($conf_mail[$cache_key]['theme']))
735      {
736        $conf_mail[$cache_key]['theme'] = get_mail_template($content_type);
737        trigger_notify('before_parse_mail_template', $cache_key, $content_type);
738      }
739      $template = &$conf_mail[$cache_key]['theme'];
740
741      $template->set_filename('mail_header', 'header.tpl');
742      $template->set_filename('mail_footer', 'footer.tpl');
743
744      $add_url_params = array();
745      if (!empty($args['auth_key']))
746      {
747        $add_url_params['auth'] = $args['auth_key'];
748      }
749
750      $template->assign(
751        array(
752          'GALLERY_URL' => add_url_params(get_gallery_home_url(), $add_url_params),
753          'GALLERY_TITLE' => isset($page['gallery_title']) ? $page['gallery_title'] : $conf['gallery_title'],
754          'VERSION' => $conf['show_version'] ? PHPWG_VERSION : '',
755          'PHPWG_URL' => defined('PHPWG_URL') ? PHPWG_URL : '',
756          'CONTENT_ENCODING' => get_pwg_charset(),
757          'CONTACT_MAIL' => $conf_mail['email_webmaster'],
758          )
759        );
760
761      if ($content_type == 'text/html')
762      {
763        if ($template->smarty->templateExists('global-mail-css.tpl'))
764        {
765          $template->set_filename('global-css', 'global-mail-css.tpl');
766          $template->assign_var_from_handle('GLOBAL_MAIL_CSS', 'global-css');
767        }
768
769        if ($template->smarty->templateExists('mail-css-'. $args['theme'] .'.tpl'))
770        {
771          $template->set_filename('css', 'mail-css-'. $args['theme'] .'.tpl');
772          $template->assign_var_from_handle('MAIL_CSS', 'css');
773        }
774      }
775    }
776
777    $template = &$conf_mail[$cache_key]['theme'];
778    $template->assign(
779      array(
780        'MAIL_TITLE' => $args['mail_title'],
781        'MAIL_SUBTITLE' => $args['mail_subtitle'],
782        )
783      );
784
785    // Header
786    $contents[$content_type] = $template->parse('mail_header', true);
787
788    // Content
789    // Stored in a temp variable, if a content template is used it will be assigned
790    // to the $CONTENT template variable, otherwise it will be appened to the mail
791    if ($args['content_format'] == 'text/plain' and $content_type == 'text/html')
792    {
793      // convert plain text to html
794      $mail_content =
795        '<p>'.
796        nl2br(
797          preg_replace(
798            '/(https?:\/\/([-\w\.]+[-\w])+(:\d+)?(\/([\w\/_\.\#-]*(\?\S+)?[^\.\s])?)?)/i',
799            '<a href="$1">$1</a>',
800            htmlspecialchars($args['content'])
801            )
802          ).
803        '</p>';
804    }
805    else if ($args['content_format'] == 'text/html' and $content_type == 'text/plain')
806    {
807      // convert html text to plain text
808      $mail_content = strip_tags($args['content']);
809    }
810    else
811    {
812      $mail_content = $args['content'];
813    }
814
815    // Runtime template
816    if (isset($tpl['filename']))
817    {
818      if (isset($tpl['dirname']))
819      {
820        $template->set_template_dir($tpl['dirname'] .'/'. $content_type);
821      }
822      if ($template->smarty->templateExists($tpl['filename'] .'.tpl'))
823      {
824        $template->set_filename($tpl['filename'], $tpl['filename'] .'.tpl');
825        if (!empty($tpl['assign']))
826        {
827          $template->assign($tpl['assign']);
828        }
829        $template->assign('CONTENT', $mail_content);
830        $contents[$content_type].= $template->parse($tpl['filename'], true);
831      }
832      else
833      {
834        $contents[$content_type].= $mail_content;
835      }
836    }
837    else
838    {
839      $contents[$content_type].= $mail_content;
840    }
841
842    // Footer
843    $contents[$content_type].= $template->parse('mail_footer', true);
844  }
845
846  // Undo Compute root_path in order have complete path
847  unset_make_full_url();
848
849  // Send content to PHPMailer
850  if (isset($contents['text/html']))
851  {
852    $mail->isHTML(true);
853    $mail->Body = move_css_to_body($contents['text/html']);
854
855    if (isset($contents['text/plain']))
856    {
857      $mail->AltBody = $contents['text/plain'];
858    }
859  }
860  else
861  {
862    $mail->isHTML(false);
863    $mail->Body = $contents['text/plain'];
864  }
865
866  if ($conf_mail['use_smtp'])
867  {
868    // now we need to split port number
869    if (strpos($conf_mail['smtp_host'], ':') !== false)
870    {
871      list($smtp_host, $smtp_port) = explode(':', $conf_mail['smtp_host']);
872    }
873    else
874    {
875      $smtp_host = $conf_mail['smtp_host'];
876      $smtp_port = 25;
877    }
878
879    $mail->IsSMTP();
880
881    // enables SMTP debug information (for testing) 2 - debug, 0 - no message
882    $mail->SMTPDebug = 0;
883
884    $mail->Host = $smtp_host;
885    $mail->Port = $smtp_port;
886
887    if (!empty($conf_mail['smtp_secure']) and in_array($conf_mail['smtp_secure'], array('ssl', 'tls')))
888    {
889      $mail->SMTPSecure = $conf_mail['smtp_secure'];
890    }
891
892    if (!empty($conf_mail['smtp_user']))
893    {
894      $mail->SMTPAuth = true;
895      $mail->Username = $conf_mail['smtp_user'];
896      $mail->Password = $conf_mail['smtp_password'];
897    }
898  }
899
900  $ret = true;
901  $pre_result = trigger_change('before_send_mail', true, $to, $args, $mail);
902
903  if ($pre_result)
904  {
905    $ret = $mail->send();
906    if (!$ret and (!ini_get('display_errors') or is_admin()))
907    {
908      trigger_error('Mailer Error: ' . $mail->ErrorInfo, E_USER_WARNING);
909    }
910    if ($conf['debug_mail'])
911    {
912      pwg_send_mail_test($ret, $mail, $args);
913    }
914  }
915
916  return $ret;
917}
918
919/**
920 * @deprecated 2.6
921 */
922function pwg_send_mail($result, $to, $subject, $content, $headers)
923{
924  if (is_admin())
925  {
926    trigger_error('pwg_send_mail function is deprecated', E_USER_NOTICE);
927  }
928
929  if (!$result)
930  {
931    return pwg_mail($to, array(
932        'content' => $content,
933        'subject' => $subject,
934      ));
935  }
936  else
937  {
938    return $result;
939  }
940}
941
942/**
943 * Moves CSS rules contained in the <style> tag to inline CSS.
944 * Used for compatibility with Gmail and such clients
945 * @since 2.6
946 *
947 * @param string $content
948 * @return string
949 */
950function move_css_to_body($content)
951{
952  include_once(PHPWG_ROOT_PATH.'include/emogrifier.class.php');
953
954  $e = new Emogrifier($content);
955  return @$e->emogrify();
956}
957
958/**
959 * Saves a copy of the mail if _data/tmp.
960 *
961 * @param boolean $success
962 * @param PHPMailer $mail
963 * @param array $args
964 */
965function pwg_send_mail_test($success, $mail, $args)
966{
967  global $conf, $user, $lang_info;
968
969  $dir = PHPWG_ROOT_PATH.$conf['data_location'].'tmp';
970  if (mkgetdir($dir, MKGETDIR_DEFAULT&~MKGETDIR_DIE_ON_ERROR))
971  {
972    $filename = $dir.'/mail.'.stripslashes($user['username']).'.'.$lang_info['code'].'-'.date('YmdHis').($success ? '' : '.ERROR');
973    if ($args['content_format'] == 'text/plain')
974    {
975      $filename .= '.txt';
976    }
977    else
978    {
979      $filename .= '.html';
980    }
981
982    $file = fopen($filename, 'w+');
983    if (!$success)
984    {
985      fwrite($file, "ERROR: " . $mail->ErrorInfo . "\n\n");
986    }
987    fwrite($file, $mail->getSentMIMEMessage());
988    fclose($file);
989  }
990}
991
992trigger_notify('functions_mail_included');
993
994?>
995