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

Last change on this file since 25018 was 25018, checked in by mistic100, 11 years ago

remove all array_push (50% slower than []) + some changes missing for feature:2978

  • Property svn:eol-style set to LF
File size: 24.2 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2013 Piwigo Team                  http://piwigo.org |
6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
23
24// +-----------------------------------------------------------------------+
25// |                               functions                               |
26// +-----------------------------------------------------------------------+
27
28/*
29 * Returns the name of the mail sender :
30 *
31 * @return string
32 */
33function get_mail_sender_name()
34{
35  global $conf;
36
37  return (empty($conf['mail_sender_name']) ? $conf['gallery_title'] : $conf['mail_sender_name']);
38}
39
40/*
41 * Returns an array of mail configuration parameters :
42 *
43 * - mail_options
44 * - send_bcc_mail_webmaster
45 * - default_email_format
46 * - alternative_email_format
47 * - use_smtp
48 * - smtp_host
49 * - smtp_user
50 * - smtp_password
51 * - boundary_key
52 * - email_webmaster
53 * - formated_email_webmaster
54 *
55 * @return array
56 */
57function get_mail_configuration()
58{
59  global $conf;
60
61  $conf_mail = array(
62    'mail_options' => $conf['mail_options'],
63    'send_bcc_mail_webmaster' => $conf['send_bcc_mail_webmaster'],
64    'default_email_format' => $conf['default_email_format'],
65    'alternative_email_format' => $conf['alternative_email_format'],
66    'use_smtp' => !empty($conf['smtp_host']),
67    'smtp_host' => $conf['smtp_host'],
68    'smtp_user' => $conf['smtp_user'],
69    'smtp_password' => $conf['smtp_password'],
70    'smtp_secure' => $conf['smtp_secure'],
71    );
72
73  // we have webmaster id among user list, what's his email address ?
74  $conf_mail['email_webmaster'] = get_webmaster_mail_address();
75
76  // name of the webmaster is the title of the gallery
77  $conf_mail['formated_email_webmaster'] = format_email(get_mail_sender_name(), $conf_mail['email_webmaster']);
78
79  return $conf_mail;
80}
81
82/**
83 * Returns an email address with an associated real name
84 *
85 * @param string name
86 * @param string email
87 */
88function format_email($name, $email)
89{
90  // Spring cleaning
91  $cvt_email = trim(preg_replace('#[\n\r]+#s', '', $email));
92  $cvt_name = trim(preg_replace('#[\n\r]+#s', '', $name));
93
94  if ($cvt_name!="")
95  {
96    $cvt_name = '"'.addcslashes($cvt_name,'"').'"'.' ';
97  }
98
99  if (strpos($cvt_email, '<') === false)
100  {
101    return $cvt_name.'<'.$cvt_email.'>';
102  }
103  else
104  {
105    return $cvt_name.$cvt_email;
106  }
107}
108
109/**
110 * Returns an email address list with minimal email string
111 *
112 * @param string with email list (email separated by comma)
113 */
114function get_strict_email_list($email_list)
115{
116  $result = array();
117  $list = explode(',', $email_list);
118  foreach ($list as $email)
119  {
120    if (strpos($email, '<') !== false)
121    {
122       $email = preg_replace('/.*<(.*)>.*/i', '$1', $email);
123    }
124    $result[] = trim($email);
125  }
126
127  return implode(',', array_unique($result));
128}
129
130
131/**
132 * Return an new mail template
133 *
134 * @param string email_format: mail format, text/html or text/plain
135 * @param string theme: theme to use [default get_default_theme()]
136 */
137function & get_mail_template($email_format, $theme='')
138{
139  if (empty($theme))
140  {
141    $theme = get_default_theme();
142  }
143
144  $mail_template = new Template(PHPWG_ROOT_PATH.'themes', $theme, 'template/mail/'.$email_format);
145
146  return $mail_template;
147}
148
149/**
150 * Return string email format (text/html or text/plain)
151 *
152 * @param string format
153 */
154function get_str_email_format($is_html)
155{
156  return ($is_html ? 'text/html' : 'text/plain');
157}
158
159/*
160 * Switch language to param language
161 * All entries are push on language stack
162 *
163 * @param string language
164 */
165function switch_lang_to($language)
166{
167  global $switch_lang, $user, $lang, $lang_info, $language_files;
168
169  // explanation of switch_lang
170  // $switch_lang['language'] contains data of language
171  // $switch_lang['stack'] contains stack LIFO
172  // $switch_lang['initialisation'] allow to know if it's first call
173
174  // Treatment with current user
175  // Language of current user is saved (it's considered OK on firt call)
176  if (!isset($switch_lang['initialisation']) and !isset($switch_lang['language'][$user['language']]))
177  {
178    $switch_lang['initialisation'] = true;
179    $switch_lang['language'][$user['language']]['lang_info'] = $lang_info;
180    $switch_lang['language'][$user['language']]['lang'] = $lang;
181  }
182
183  // Change current infos
184  $switch_lang['stack'][] = $user['language'];
185  $user['language'] = $language;
186
187  // Load new data if necessary
188  if (!isset($switch_lang['language'][$language]))
189  {
190    // Re-Init language arrays
191    $lang_info = array();
192    $lang  = array();
193
194    // language files
195    load_language('common.lang', '', array('language'=>$language) );
196    // No test admin because script is checked admin (user selected no)
197    // Translations are in admin file too
198    load_language('admin.lang', '', array('language'=>$language) );
199   
200    if (!empty($language_files))
201    {
202      foreach ($language_files as $dirname => $files)
203        foreach ($files as $filename)
204          load_language($filename, $dirname, array('language'=>$language) );
205    }
206   
207    trigger_action('loading_lang');
208    load_language('lang', PHPWG_ROOT_PATH.PWG_LOCAL_DIR,
209      array('language'=>$language, 'no_fallback'=>true, 'local'=>true)
210    );
211
212    $switch_lang['language'][$language]['lang_info'] = $lang_info;
213    $switch_lang['language'][$language]['lang'] = $lang;
214  }
215  else
216  {
217    $lang_info = $switch_lang['language'][$language]['lang_info'];
218    $lang = $switch_lang['language'][$language]['lang'];
219  }
220}
221
222/*
223 * Switch back language pushed with switch_lang_to function
224 *
225 * @param: none
226 */
227function switch_lang_back()
228{
229  global $switch_lang, $user, $lang, $lang_info;
230
231  if (count($switch_lang['stack']) > 0)
232  {
233    // Get last value
234    $language = array_pop($switch_lang['stack']);
235
236    // Change current infos
237    if (isset($switch_lang['language'][$language]))
238    {
239      $lang_info = $switch_lang['language'][$language]['lang_info'];
240      $lang = $switch_lang['language'][$language]['lang'];
241    }
242    $user['language'] = $language;
243  }
244}
245
246/**
247 * Returns email of all administrator
248 *
249 * @return string
250 */
251/*
252 * send en notification email to all administrators
253 * if a administrator is doing action,
254 * he's be removed to email list
255 *
256 * @param:
257 *   - keyargs_subject: mail subject on l10n_args format
258 *   - keyargs_content: mail content on l10n_args format
259 *   - send_technical_details: send user IP and browser
260 *
261 * @return boolean (Ok or not)
262 */
263function pwg_mail_notification_admins($keyargs_subject, $keyargs_content, $send_technical_details=true)
264{
265  global $conf, $user;
266 
267  // Check arguments
268  if (empty($keyargs_subject) or empty($keyargs_content))
269  {
270    return false;
271  }
272
273  $return = true;
274
275  $admins = array();
276
277  $query = '
278SELECT
279    u.'.$conf['user_fields']['username'].' AS username,
280    u.'.$conf['user_fields']['email'].' AS mail_address
281  FROM '.USERS_TABLE.' AS u
282    JOIN '.USER_INFOS_TABLE.' AS i ON i.user_id =  u.'.$conf['user_fields']['id'].'
283  WHERE i.status in (\'webmaster\',  \'admin\')
284    AND '.$conf['user_fields']['email'].' IS NOT NULL
285    AND i.user_id <> '.$user['id'].'
286  ORDER BY username
287;';
288
289  $datas = pwg_query($query);
290  if (!empty($datas))
291  {
292    while ($admin = pwg_db_fetch_assoc($datas))
293    {
294      if (!empty($admin['mail_address']))
295      {
296        $admins[] = format_email($admin['username'], $admin['mail_address']);
297      }
298    }
299  }
300
301  if (count($admins) > 0)
302  {
303    switch_lang_to(get_default_language());
304
305    $content = l10n_args($keyargs_content)."\n";
306    if ($send_technical_details)
307    {
308      $keyargs_content_admin_info = array(
309        get_l10n_args('Connected user: %s', stripslashes($user['username'])),
310        get_l10n_args('IP: %s', $_SERVER['REMOTE_ADDR']),
311        get_l10n_args('Browser: %s', $_SERVER['HTTP_USER_AGENT'])
312        );
313     
314      $content.= "\n".l10n_args($keyargs_content_admin_info)."\n";
315    }
316
317    $return = pwg_mail(
318      implode(', ', $admins),
319      array(
320        'subject' => '['.$conf['gallery_title'].'] '.l10n_args($keyargs_subject),
321        'content' => $content,
322        'content_format' => 'text/plain',
323        'email_format' => 'text/html',
324        )
325      );
326   
327    switch_lang_back();
328  }
329
330  return $return;
331}
332
333/*
334 * send en email to user's group
335 *
336 * @param:
337 *   - group_id: mail are sent to group with this Id
338 *   - email_format: mail format
339 *   - keyargs_subject: mail subject on l10n_args format
340 *   - tpl_shortname: short template name without extension
341 *   - assign_vars: array used to assign_vars to mail template
342 *   - language_selected: send mail only to user with this selected language
343 *
344 * @return boolean (Ok or not)
345 */
346function pwg_mail_group(
347  $group_id, $email_format, $keyargs_subject,
348  $tpl_shortname,
349  $assign_vars = array(), $language_selected = '')
350{
351  // Check arguments
352  if
353    (
354      empty($group_id) or
355      empty($email_format) or
356      empty($keyargs_subject) or
357      empty($tpl_shortname)
358    )
359  {
360    return false;
361  }
362
363  global $conf;
364  $return = true;
365
366  $query = '
367SELECT
368  distinct language, theme
369FROM
370  '.USER_GROUP_TABLE.' as ug
371  INNER JOIN '.USERS_TABLE.' as u  ON '.$conf['user_fields']['id'].' = ug.user_id
372  INNER JOIN '.USER_INFOS_TABLE.' as ui  ON ui.user_id = ug.user_id
373WHERE
374        '.$conf['user_fields']['email'].' IS NOT NULL
375    AND group_id = '.$group_id;
376
377  if (!empty($language_selected))
378  {
379    $query .= '
380    AND language = \''.$language_selected.'\'';
381  }
382
383    $query .= '
384;';
385
386  $result = pwg_query($query);
387
388  if (pwg_db_num_rows($result) > 0)
389  {
390    $list = array();
391    while ($row = pwg_db_fetch_assoc($result))
392    {
393      $list[] = $row;
394    }
395
396    foreach ($list as $elem)
397    {
398      $query = '
399SELECT
400  u.'.$conf['user_fields']['username'].' as username,
401  u.'.$conf['user_fields']['email'].' as mail_address
402FROM
403  '.USER_GROUP_TABLE.' as ug
404  INNER JOIN '.USERS_TABLE.' as u  ON '.$conf['user_fields']['id'].' = ug.user_id
405  INNER JOIN '.USER_INFOS_TABLE.' as ui  ON ui.user_id = ug.user_id
406WHERE
407        '.$conf['user_fields']['email'].' IS NOT NULL
408    AND group_id = '.$group_id.'
409    AND language = \''.$elem['language'].'\'
410    AND theme = \''.$elem['theme'].'\'
411;';
412
413      $result = pwg_query($query);
414
415      if (pwg_db_num_rows($result) > 0)
416      {
417        $Bcc = array();
418        while ($row = pwg_db_fetch_assoc($result))
419        {
420          if (!empty($row['mail_address']))
421          {
422            $Bcc[] = format_email(stripslashes($row['username']), $row['mail_address']);
423          }
424        }
425
426        if (count($Bcc) > 0)
427        {
428          switch_lang_to($elem['language']);
429
430          $mail_template = get_mail_template($email_format, $elem['theme']);
431          $mail_template->set_filename($tpl_shortname, $tpl_shortname.'.tpl');
432
433          $mail_template->assign(
434            trigger_event('mail_group_assign_vars', $assign_vars));
435
436          $return = pwg_mail
437          (
438            '',
439            array
440            (
441              'Bcc' => $Bcc,
442              'subject' => l10n_args($keyargs_subject),
443              'email_format' => $email_format,
444              'content' => $mail_template->parse($tpl_shortname, true),
445              'content_format' => $email_format,
446              'theme' => $elem['theme']
447            )
448          ) and $return;
449
450          switch_lang_back();
451        }
452      }
453    }
454  }
455
456  return $return;
457}
458
459/*
460 * sends an email, using Piwigo specific informations
461 *
462 * @param:
463 *   - to: receiver(s) of the mail (list separated by comma).
464 *   - args: function params of mail function:
465 *       o from: sender [default value webmaster email]
466 *       o Cc: array of carbon copy receivers of the mail. [default value empty]
467 *       o Bcc: array of blind carbon copy receivers of the mail. [default value empty]
468 *       o subject  [default value 'Piwigo']
469 *       o content: content of mail    [default value '']
470 *       o content_format: format of mail content  [default value 'text/plain']
471 *       o email_format: global mail format  [default value $conf_mail['default_email_format']]
472 *       o theme: template to use [default get_default_theme()]
473 *
474 * @return boolean (Ok or not)
475 */
476function pwg_mail($to, $args = array())
477{
478  global $conf, $conf_mail, $lang_info, $page;
479
480  if (empty($to) and empty($args['Cc']) and empty($args['Bcc']))
481  {
482    return true;
483  }
484
485  if (!isset($conf_mail))
486  {
487    $conf_mail = get_mail_configuration();
488  }
489
490  include_once(PHPWG_ROOT_PATH.'include/phpmailer/class.phpmailer.php');
491
492  $mail = new PHPMailer;
493
494  foreach (explode(',', get_strict_email_list($to)) as $recipient)
495  {
496    $mail->addAddress($recipient);
497  }
498 
499  $mail->WordWrap = 76;
500  $mail->CharSet = 'UTF-8';
501 
502  // Compute root_path in order have complete path
503  set_make_full_url();
504
505  if (empty($args['from']))
506  {
507    $mail->From = get_webmaster_mail_address();
508    $mail->FromName = get_mail_sender_name();
509
510    $mail->addReplyTo(get_webmaster_mail_address(), get_mail_sender_name());
511  }
512  else
513  {
514    $mail->From = $args['from'];
515    $mail->addReplyTo($args['from']);
516  }
517
518  // Subject
519  if (empty($args['subject']))
520  {
521    $args['subject'] = 'Piwigo';
522  }
523 
524  $args['subject'] = trim(preg_replace('#[\n\r]+#s', '', $args['subject']));
525
526  $mail->Subject = $args['subject'];
527
528  // Cc
529  if (!empty($args['Cc']))
530  {
531    $mail->addCC($args['Cc']);
532  }
533
534  // Bcc
535  if ($conf_mail['send_bcc_mail_webmaster'])
536  {
537    $args['Bcc'][] = get_webmaster_mail_address();;
538  }
539
540  if (!empty($args['Bcc']))
541  {
542    foreach ($args['Bcc'] as $bcc)
543    {
544      $mail->addBCC($bcc);
545    }
546  }
547
548  // content
549  if (empty($args['email_format']))
550  {
551    $args['email_format'] = $conf_mail['default_email_format'];
552  }
553
554  if (!isset($args['content']))
555  {
556    $args['content'] = '';
557  }
558
559  if (empty($args['content_format']))
560  {
561    $args['content_format'] = 'text/plain';
562  }
563
564  if (empty($args['theme']))
565  {
566    $args['theme'] = get_default_theme();
567  }
568
569  $content_type_list[] = $args['email_format'];
570  if (!empty($conf_mail['alternative_email_format']))
571  {
572    $content_type_list[] = $conf_mail['alternative_email_format'];
573  }
574
575  $contents = array();
576
577  foreach (array_unique($content_type_list) as $content_type)
578  {
579    // key compose of indexes witch allow ti cache mail data
580    $cache_key = $content_type.'-'.$lang_info['code'].'-'.$args['theme'];
581
582    if (!isset($conf_mail[$cache_key]))
583    {
584      if (!isset($conf_mail[$cache_key]['theme']))
585      {
586        $conf_mail[$cache_key]['theme'] = get_mail_template($content_type, $args['theme']);
587      }
588
589      $conf_mail[$cache_key]['theme']->set_filename('mail_header', 'header.tpl');
590      $conf_mail[$cache_key]['theme']->set_filename('mail_footer', 'footer.tpl');
591
592      $conf_mail[$cache_key]['theme']->assign(
593        array(
594          'GALLERY_URL' => get_gallery_home_url(),
595          'GALLERY_TITLE' => isset($page['gallery_title']) ? $page['gallery_title'] : $conf['gallery_title'],
596          'VERSION' => $conf['show_version'] ? PHPWG_VERSION : '',
597          'PHPWG_URL' => PHPWG_URL,
598          'TITLE_MAIL' => urlencode(l10n('A comment on your site')),
599          'MAIL' => get_webmaster_mail_address()
600          )
601        );
602
603      if ($content_type == 'text/html')
604      {
605        if ($conf_mail[$cache_key]['theme']->smarty->template_exists('global-mail-css.tpl'))
606        {
607          $conf_mail[$cache_key]['theme']->set_filename('css', 'global-mail-css.tpl');
608          $conf_mail[$cache_key]['theme']->assign_var_from_handle('GLOBAL_MAIL_CSS', 'css');
609        }
610
611        $file = PHPWG_ROOT_PATH.'themes/'.$args['theme'].'/mail-css.tpl';
612        if (is_file($file))
613        {
614          $conf_mail[$cache_key]['theme']->set_filename('css', realpath($file));
615          $conf_mail[$cache_key]['theme']->assign_var_from_handle('MAIL_CSS', 'css');
616        }
617      }
618
619      // what are displayed on the header of each mail ?
620      $conf_mail[$cache_key]['header'] = $conf_mail[$cache_key]['theme']->parse('mail_header', true);
621
622      // what are displayed on the footer of each mail ?
623      $conf_mail[$cache_key]['footer'] = $conf_mail[$cache_key]['theme']->parse('mail_footer', true);
624    }
625
626    // Header
627    $contents[$content_type] = $conf_mail[$cache_key]['header'];
628
629    // Content
630    if (($args['content_format'] == 'text/plain') and ($content_type == 'text/html'))
631    {
632      $contents[$content_type].= '<p>'.
633                  nl2br(
634                    preg_replace("/(http:\/\/)([^\s,]*)/i",
635                                 "<a href='$1$2' class='thumblnk'>$1$2</a>",
636                                 htmlspecialchars($args['content']))).
637                  '</p>';
638    }
639    else if (($args['content_format'] == 'text/html') and ($content_type == 'text/plain'))
640    {
641      // convert html text to plain text
642      $contents[$content_type].= strip_tags($args['content']);
643    }
644    else
645    {
646      $contents[$content_type].= $args['content'];
647    }
648
649    // Footer
650    $contents[$content_type].= $conf_mail[$cache_key]['footer'];
651  }
652
653  // Undo Compute root_path in order have complete path
654  unset_make_full_url();
655
656  if (isset($contents['text/html']))
657  {
658    $mail->isHTML(true); // Set email format to HTML
659    $mail->Body = $contents['text/html'];
660   
661    if (isset($contents['text/plain']))
662    {
663      $mail->AltBody = $contents['text/plain'];
664    }
665  }
666  else
667  {
668    $mail->isHTML(false);
669    $mail->Body = $contents['text/plain'];
670  }
671
672  if ($conf_mail['use_smtp'])
673  {
674    // now we need to split port number
675    if (strpos($conf_mail['smtp_host'], ':') !== false)
676    {
677      list($smtp_host, $smtp_port) = explode(':', $conf_mail['smtp_host']);
678    }
679    else
680    {
681      $smtp_host = $conf_mail['smtp_host'];
682      $smtp_port = 25;
683    }
684
685    $mail->IsSMTP();
686
687    // enables SMTP debug information (for testing) 2 - debug, 0 - no message
688    $mail->SMTPDebug = 0;
689   
690    $mail->Host = $smtp_host;
691    $mail->Port = $smtp_port;
692
693    if (!empty($conf_mail['smtp_secure']) and in_array($conf_mail['smtp_secure'], array('ssl', 'tls')))
694    {
695      $mail->SMTPSecure = $conf_mail['smtp_secure'];
696    }
697   
698    if (!empty($conf_mail['smtp_user']))
699    {
700      $mail->SMTPAuth = true;
701      $mail->Username = $conf_mail['smtp_user'];
702      $mail->Password = $conf_mail['smtp_password'];
703    }
704  }
705
706  $ret = $mail->send();
707  if(!$ret)
708  {
709    trigger_error( 'Mailer Error: ' . $mail->ErrorInfo, E_USER_WARNING);
710  }
711  return $ret;
712}
713
714/* DEPRECATED
715 * pwg sendmail
716 *
717 * @param:
718 *   - result of other sendmail
719 *   - to: Receiver or receiver(s) of the mail.
720 *   - subject  [default value 'Piwigo']
721 *   - content: content of mail
722 *   - headers: headers of mail
723 *
724 * @return boolean (Ok or not)
725 */
726function pwg_send_mail($result, $to, $subject, $contents, $headers)
727{
728  if (!$result)
729  {
730    include_once(PHPWG_ROOT_PATH.'include/class.phpmailer.php');
731   
732    global $conf_mail;
733
734    if ($conf_mail['use_smtp'])
735    {
736      include_once( PHPWG_ROOT_PATH.'include/class_smtp_mail.inc.php' );
737      $smtp_mail = new smtp_mail(
738        $conf_mail['smtp_host'], $conf_mail['smtp_user'], $conf_mail['smtp_password'],
739        $conf_mail['email_webmaster']);
740      return $smtp_mail->mail($to, $subject, $content, $headers);
741    }
742    else
743    {
744      $mail = new PHPMailer;
745
746      $mail->From = 'plg@pigolabs.com';
747      $mail->FromName = 'Pierrick en local';
748      foreach (explode(',', $to) as $recipient)
749      {
750        $mail->addAddress($recipient);  // Add a recipient
751      }
752      // $mail->addReplyTo('plg@piwigo.org', 'Pierrick de Piwigo.org');
753      // $mail->addCC('cc@example.com');
754      // $mail->addBCC('bcc@example.com');
755
756      $mail->WordWrap = 76;                                // Set word wrap to 50 characters
757
758      if (isset($contents['text/html']))
759      {
760        $mail->isHTML(true);                                 // Set email format to HTML
761        $mail->Body = $contents['text/html'];
762
763        if (isset($contents['text/plain']))
764        {
765          $mail->AltBody = $contents['text/plain'];
766        }
767      }
768      else
769      {
770        $mail->isHTML(false);
771        $mail->Body = $contents['text/plain'];
772      }
773
774      $mail->CharSet = 'UTF-8';
775      $mail->Subject = $subject;
776
777      if(!$mail->send()) {
778        echo 'Message could not be sent.';
779        echo 'Mailer Error: ' . $mail->ErrorInfo;
780        exit;
781      }
782
783      // if ($conf_mail['mail_options'])
784      // {
785      //   $options = '-f '.$conf_mail['email_webmaster'];
786      //   return mail($to, $subject, $content, $headers, $options);
787      // }
788      // else
789      // {
790      //   return mail($to, $subject, $content, $headers);
791      // }
792    }
793  }
794  else
795  {
796    return $result;
797  }
798}
799
800function move_ccs_rules_to_body($content)
801{
802  return $content;
803  // We search all css rules in style tags
804  preg_match('#<style>(.*?)</style>#s', $content, $matches);
805
806  if (!empty($matches[1]))
807  {
808    preg_match_all('#([^\n]*?)\{(.*?)\}#s', $matches[1], $matches);
809
810    $selectors = array();
811    $unknow_selectors = '';
812
813    foreach ($matches[1] as $key => $value)
814    {
815      $selects = explode(',', $value);
816      $style = trim($matches[2][$key], ' ;');
817
818      foreach($selects as $select)
819      {
820        $select = trim($select);
821        $selectors[$select][] = $style;
822      }
823    }
824
825    foreach ($selectors as $selector => $style)
826    {
827      if (!preg_match('/^(#|\.|)([A-Za-z0-9_-]*)$/', $selector, $matches))
828      {
829        $unknow_selectors .= $selector.' {'.implode(";\n", $style).";}\n";
830      }
831      else switch ($matches[1])
832      {
833        case '#':
834          $content = preg_replace('|id="'.$matches[2].'"|', 'id="'.$matches[2].'" style="'.implode(";\n", $style).";\"\n", $content);
835          break;
836        case '.':
837          $content = preg_replace('|class="'.$matches[2].'"|', 'class="'.$matches[2].'" style="'.implode(";\n", $style).";\"\n", $content);
838          break;
839        default:
840          $content = preg_replace('#<'.$matches[2].'( |>)#', '<'.$matches[2].' style="'.implode(";\n", $style).";\"\n$1", $content);
841          break;
842      }
843    }
844
845    // Keep unknow tags in page head
846    if (!empty($unknow_selectors))
847    {
848      $content = preg_replace('#<style>.*?</style>#s', "<style type=\"text/css\">\n$unknow_selectors</style>", $content);
849    }
850    else
851    {
852      $content = preg_replace('#<style>.*?</style>#s', '', $content);
853    }
854  }
855  return $content;
856}
857
858/*Testing block*/
859function pwg_send_mail_test($result, $to, $subject, $content, $headers, $args)
860{
861    global $conf, $user, $lang_info;
862    $dir = PHPWG_ROOT_PATH.$conf['data_location'].'tmp';
863    if ( mkgetdir( $dir,  MKGETDIR_DEFAULT&~MKGETDIR_DIE_ON_ERROR) )
864    {
865      $filename = $dir.'/mail.'.stripslashes($user['username']).'.'.$lang_info['code'].'.'.$args['theme'].'-'.date('YmdHis');
866      if ($args['content_format'] == 'text/plain')
867      {
868        $filename .= '.txt';
869      }
870      else
871      {
872        $filename .= '.html';
873      }
874      $file = fopen($filename, 'w+');
875      fwrite($file, $to ."\n");
876      fwrite($file, $subject ."\n");
877      fwrite($file, $headers);
878      fwrite($file, $content);
879      fclose($file);
880    }
881    return $result;
882}
883if ($conf['debug_mail'])
884  add_event_handler('send_mail', 'pwg_send_mail_test', EVENT_HANDLER_PRIORITY_NEUTRAL+10, 6);
885
886
887add_event_handler('send_mail', 'pwg_send_mail', EVENT_HANDLER_PRIORITY_NEUTRAL, 5);
888add_event_handler('send_mail_content', 'move_ccs_rules_to_body');
889trigger_action('functions_mail_included');
890
891?>
Note: See TracBrowser for help on using the repository browser.