Do not try to send jabber notifications if no jid entered (Bug #36775)
[phpbb.git] / phpBB / includes / functions_messenger.php
blob9dbb85235eb933731f9051d495071935fe4f8851
1 <?php
2 /**
4 * @package phpBB3
5 * @version $Id$
6 * @copyright (c) 2005 phpBB Group
7 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
9 */
11 /**
12 * @ignore
14 if (!defined('IN_PHPBB'))
16 exit;
19 /**
20 * Messenger
21 * @package phpBB3
23 class messenger
25 private $vars, $msg, $extra_headers, $replyto, $from, $subject;
26 private $addresses = array();
28 private $mail_priority = MAIL_NORMAL_PRIORITY;
29 private $use_queue = true;
30 private $tpl_msg = array();
32 /**
33 * Constructor
35 function __construct($use_queue = true)
37 global $config;
39 $this->use_queue = (!$config['email_package_size']) ? false : $use_queue;
40 $this->subject = '';
43 /**
44 * Resets all the data (address, template file, etc etc) to default
46 private function reset()
48 $this->addresses = $this->extra_headers = array();
49 $this->vars = $this->msg = $this->replyto = $this->from = '';
50 $this->mail_priority = MAIL_NORMAL_PRIORITY;
53 /**
54 * Sets an email address to send to
56 function to($address, $realname = '')
58 global $config;
60 $pos = isset($this->addresses['to']) ? sizeof($this->addresses['to']) : 0;
62 $this->addresses['to'][$pos]['email'] = trim($address);
64 // If empty sendmail_path on windows, PHP changes the to line
65 if (!$config['smtp_delivery'] && DIRECTORY_SEPARATOR == '\\')
67 $this->addresses['to'][$pos]['name'] = '';
69 else
71 $this->addresses['to'][$pos]['name'] = trim($realname);
75 /**
76 * Sets an cc address to send to
78 function cc($address, $realname = '')
80 $pos = isset($this->addresses['cc']) ? sizeof($this->addresses['cc']) : 0;
81 $this->addresses['cc'][$pos]['email'] = trim($address);
82 $this->addresses['cc'][$pos]['name'] = trim($realname);
85 /**
86 * Sets an bcc address to send to
88 function bcc($address, $realname = '')
90 $pos = isset($this->addresses['bcc']) ? sizeof($this->addresses['bcc']) : 0;
91 $this->addresses['bcc'][$pos]['email'] = trim($address);
92 $this->addresses['bcc'][$pos]['name'] = trim($realname);
95 /**
96 * Sets a im contact to send to
98 function im($address, $realname = '')
100 // IM-Addresses could be empty
101 if (!$address)
103 return;
106 $pos = isset($this->addresses['im']) ? sizeof($this->addresses['im']) : 0;
107 $this->addresses['im'][$pos]['uid'] = trim($address);
108 $this->addresses['im'][$pos]['name'] = trim($realname);
112 * Set the reply to address
114 function replyto($address)
116 $this->replyto = trim($address);
120 * Set the from address
122 function from($address)
124 $this->from = trim($address);
128 * set up subject for mail
130 function subject($subject = '')
132 $this->subject = trim($subject);
136 * set up extra mail headers
138 function headers($headers)
140 $this->extra_headers[] = trim($headers);
144 * Set the email priority
146 function set_mail_priority($priority = MAIL_NORMAL_PRIORITY)
148 $this->mail_priority = $priority;
152 * Set email template to use
154 function template($template_file, $template_lang = '')
156 global $config;
158 if (!trim($template_file))
160 trigger_error('No template file set', E_USER_ERROR);
163 if (!trim($template_lang))
165 $template_lang = basename($config['default_lang']);
168 if (empty($this->tpl_msg[$template_lang . $template_file]))
170 $tpl_file = PHPBB_ROOT_PATH . "language/$template_lang/email/$template_file.txt";
172 if (!file_exists($tpl_file))
174 trigger_error("Could not find email template file [ $tpl_file ]", E_USER_ERROR);
177 if (($data = @file_get_contents($tpl_file)) === false)
179 trigger_error("Failed opening template file [ $tpl_file ]", E_USER_ERROR);
182 $this->tpl_msg[$template_lang . $template_file] = $data;
185 $this->msg = $this->tpl_msg[$template_lang . $template_file];
187 return true;
191 * assign variables to email template
193 function assign_vars($vars)
195 $this->vars = (empty($this->vars)) ? $vars : $this->vars + $vars;
199 * Send the mail out to the recipients set previously in var $this->addresses
201 function send($method = NOTIFY_EMAIL, $break = false)
203 global $config, $user;
205 // We add some standard variables we always use, no need to specify them always
206 $this->vars['U_BOARD'] = (!isset($this->vars['U_BOARD'])) ? generate_board_url() : $this->vars['U_BOARD'];
207 $this->vars['EMAIL_SIG'] = (!isset($this->vars['EMAIL_SIG'])) ? str_replace('<br />', "\n", "-- \n" . htmlspecialchars_decode($config['board_email_sig'])) : $this->vars['EMAIL_SIG'];
208 $this->vars['SITENAME'] = (!isset($this->vars['SITENAME'])) ? htmlspecialchars_decode($config['sitename']) : $this->vars['SITENAME'];
210 // Escape all quotes, else the eval will fail.
211 $this->msg = str_replace ("'", "\'", $this->msg);
212 $this->msg = preg_replace('#\{([a-z0-9\-_]*?)\}#is', "' . ((isset(\$this->vars['\\1'])) ? \$this->vars['\\1'] : '') . '", $this->msg);
214 eval("\$this->msg = '$this->msg';");
216 // We now try and pull a subject from the email body ... if it exists,
217 // do this here because the subject may contain a variable
218 $drop_header = '';
219 $match = array();
220 if (preg_match('#^(Subject:(.*?))$#m', $this->msg, $match))
222 $this->subject = (trim($match[2]) != '') ? trim($match[2]) : (($this->subject != '') ? $this->subject : $user->lang['NO_EMAIL_SUBJECT']);
223 $drop_header .= '[\r\n]*?' . preg_quote($match[1], '#');
225 else
227 $this->subject = (($this->subject != '') ? $this->subject : $user->lang['NO_EMAIL_SUBJECT']);
230 if ($drop_header)
232 $this->msg = trim(preg_replace('#' . $drop_header . '#s', '', $this->msg));
235 if ($break)
237 return true;
240 switch ($method)
242 case NOTIFY_EMAIL:
243 $result = $this->msg_email();
244 break;
246 case NOTIFY_IM:
247 $result = $this->msg_jabber();
248 break;
250 case NOTIFY_BOTH:
251 $result = $this->msg_email();
252 $this->msg_jabber();
253 break;
256 $this->reset();
257 return $result;
261 * Add error message to log
263 public static function error($type, $msg)
265 global $user, $config;
267 // Session doesn't exist, create it
268 if (!isset($user->session_id) || $user->session_id === '')
270 $user->session_begin();
273 $calling_page = (!empty($_SERVER['PHP_SELF'])) ? $_SERVER['PHP_SELF'] : $_ENV['PHP_SELF'];
275 $message = '';
276 switch ($type)
278 case 'EMAIL':
279 $message = '<strong>EMAIL/' . (($config['smtp_delivery']) ? 'SMTP' : 'PHP/' . $config['email_function_name'] . '()') . '</strong>';
280 break;
282 default:
283 $message = "<strong>$type</strong>";
284 break;
287 $message .= '<br /><em>' . htmlspecialchars($calling_page) . '</em><br /><br />' . $msg . '<br />';
288 add_log('critical', 'LOG_ERROR_' . $type, $message);
292 * Save to queue
294 function save_queue()
296 global $config;
298 if ($config['email_package_size'] && $this->use_queue && !empty($this->queue))
300 $this->queue->save();
301 return;
306 * Return email header
308 private function build_header($to, $cc, $bcc)
310 global $config;
312 $headers = array();
314 $headers[] = 'From: ' . $this->from;
316 if ($cc)
318 $headers[] = 'Cc: ' . $cc;
321 if ($bcc)
323 $headers[] = 'Bcc: ' . $bcc;
326 $headers[] = 'Reply-To: ' . $this->replyto;
327 $headers[] = 'Return-Path: <' . $config['board_email'] . '>';
328 $headers[] = 'Sender: <' . $config['board_email'] . '>';
329 $headers[] = 'MIME-Version: 1.0';
330 $headers[] = 'Message-ID: <' . md5(unique_id(time())) . '@' . $config['server_name'] . '>';
331 $headers[] = 'Date: ' . date('r', time());
332 $headers[] = 'Content-Type: text/plain; charset=UTF-8'; // format=flowed
333 $headers[] = 'Content-Transfer-Encoding: 8bit'; // 7bit
335 $headers[] = 'X-Priority: ' . $this->mail_priority;
336 $headers[] = 'X-MSMail-Priority: ' . (($this->mail_priority == MAIL_LOW_PRIORITY) ? 'Low' : (($this->mail_priority == MAIL_NORMAL_PRIORITY) ? 'Normal' : 'High'));
337 $headers[] = 'X-Mailer: PhpBB3';
338 $headers[] = 'X-MimeOLE: phpBB3';
339 $headers[] = 'X-phpBB-Origin: phpbb://' . str_replace(array('http://', 'https://'), array('', ''), generate_board_url());
341 // We use \n here instead of \r\n because our smtp mailer is adjusting it to \r\n automatically, whereby the php mail function only works
342 // if using \n.
344 if (sizeof($this->extra_headers))
346 $headers[] = implode("\n", $this->extra_headers);
349 return implode("\n", $headers);
353 * Send out emails
355 private function msg_email()
357 global $config, $user;
359 if (empty($config['email_enable']))
361 return false;
364 $use_queue = false;
365 if ($config['email_package_size'] && $this->use_queue)
367 if (empty($this->queue))
369 $this->queue = new queue();
370 $this->queue->init('email', $config['email_package_size']);
372 $use_queue = true;
375 if (empty($this->replyto))
377 $this->replyto = '<' . $config['board_contact'] . '>';
380 if (empty($this->from))
382 $this->from = '<' . $config['board_contact'] . '>';
385 // Build to, cc and bcc strings
386 $to = $cc = $bcc = '';
387 foreach ($this->addresses as $type => $address_ary)
389 if ($type == 'im')
391 continue;
394 foreach ($address_ary as $which_ary)
396 $$type .= (($$type != '') ? ', ' : '') . (($which_ary['name'] != '') ? '"' . mail_encode($which_ary['name']) . '" <' . $which_ary['email'] . '>' : $which_ary['email']);
400 // Build header
401 $headers = $this->build_header($to, $cc, $bcc);
403 // Send message ...
404 if (!$use_queue)
406 $mail_to = ($to == '') ? 'undisclosed-recipients:;' : $to;
407 $err_msg = '';
409 if ($config['smtp_delivery'])
411 $result = smtpmail($this->addresses, mail_encode($this->subject), wordwrap(utf8_wordwrap($this->msg), 997, "\n", true), $err_msg, $headers);
413 else
415 ob_start();
416 $result = $config['email_function_name']($mail_to, mail_encode($this->subject), wordwrap(utf8_wordwrap($this->msg), 997, "\n", true), $headers);
417 $err_msg = ob_get_clean();
420 if (!$result)
422 self::error('EMAIL', $err_msg);
423 return false;
426 else
428 $this->queue->put('email', array(
429 'to' => $to,
430 'addresses' => $this->addresses,
431 'subject' => $this->subject,
432 'msg' => $this->msg,
433 'headers' => $headers)
437 return true;
441 * Send jabber message out
443 private function msg_jabber()
445 global $config, $db, $user;
447 if (empty($config['jab_enable']) || empty($config['jab_host']) || empty($config['jab_username']) || empty($config['jab_password']))
449 return false;
452 if (empty($this->addresses['im']))
454 return false;
457 $use_queue = false;
458 if ($config['jab_package_size'] && $this->use_queue)
460 if (empty($this->queue))
462 $this->queue = new queue();
463 $this->queue->init('jabber', $config['jab_package_size']);
465 $use_queue = true;
468 $addresses = array();
469 foreach ($this->addresses['im'] as $type => $uid_ary)
471 $addresses[] = $uid_ary['uid'];
473 $addresses = array_unique($addresses);
475 if (!$use_queue)
477 include_once(PHPBB_ROOT_PATH . 'includes/functions_jabber.' . PHP_EXT);
478 $this->jabber = new jabber($config['jab_host'], $config['jab_port'], $config['jab_username'], $config['jab_password'], $config['jab_use_ssl']);
480 if (!$this->jabber->connect())
482 self::error('JABBER', $user->lang['ERR_JAB_CONNECT'] . '<br />' . $this->jabber->get_log());
483 return false;
486 if (!$this->jabber->login())
488 self::error('JABBER', $user->lang['ERR_JAB_AUTH'] . '<br />' . $this->jabber->get_log());
489 return false;
492 foreach ($addresses as $address)
494 $this->jabber->send_message($address, $this->msg, $this->subject);
497 $this->jabber->disconnect();
499 else
501 $this->queue->put('jabber', array(
502 'addresses' => $addresses,
503 'subject' => $this->subject,
504 'msg' => $this->msg)
507 unset($addresses);
508 return true;
513 * handling email and jabber queue
514 * @package phpBB3
516 class queue
518 private $data = array();
519 private $queue_data = array();
520 private $package_size = 0;
521 private $cache_file = '';
524 * constructor
526 function __construct()
528 $this->data = array();
529 $this->cache_file = PHPBB_ROOT_PATH . 'cache/queue.' . PHP_EXT;
533 * Init a queue object
535 public function init($object, $package_size)
537 $this->data[$object] = array();
538 $this->data[$object]['package_size'] = $package_size;
539 $this->data[$object]['data'] = array();
543 * Put object in queue
545 public function put($object, $scope)
547 $this->data[$object]['data'][] = $scope;
551 * Process queue
552 * Using lock file
554 public function process()
556 global $db, $config, $user;
558 set_config('last_queue_run', time(), true);
560 // Delete stale lock file
561 if (file_exists($this->cache_file . '.lock') && !file_exists($this->cache_file))
563 @unlink($this->cache_file . '.lock');
564 return;
567 if (!file_exists($this->cache_file) || (file_exists($this->cache_file . '.lock') && filemtime($this->cache_file) > time() - $config['queue_interval']))
569 return;
572 $fp = @fopen($this->cache_file . '.lock', 'wb');
573 fclose($fp);
574 @chmod($this->cache_file . '.lock', 0666);
576 include($this->cache_file);
578 foreach ($this->queue_data as $object => $data_ary)
580 @set_time_limit(0);
582 if (!isset($data_ary['package_size']))
584 $data_ary['package_size'] = 0;
587 $package_size = $data_ary['package_size'];
588 $num_items = (!$package_size || sizeof($data_ary['data']) < $package_size) ? sizeof($data_ary['data']) : $package_size;
590 // If the amount of emails to be sent is way more than package_size than we need to increase it to prevent backlogs...
591 if (sizeof($data_ary['data']) > $package_size * 2.5)
593 $num_items = sizeof($data_ary['data']);
596 switch ($object)
598 case 'email':
599 // Delete the email queued objects if mailing is disabled
600 if (!$config['email_enable'])
602 unset($this->queue_data['email']);
603 continue 2;
605 break;
607 case 'jabber':
608 if (!$config['jab_enable'])
610 unset($this->queue_data['jabber']);
611 continue 2;
614 include_once(PHPBB_ROOT_PATH . 'includes/functions_jabber.' . PHP_EXT);
615 $this->jabber = new jabber($config['jab_host'], $config['jab_port'], $config['jab_username'], $config['jab_password'], $config['jab_use_ssl']);
617 if (!$this->jabber->connect())
619 messenger::error('JABBER', $user->lang['ERR_JAB_CONNECT']);
620 continue 2;
623 if (!$this->jabber->login())
625 messenger::error('JABBER', $user->lang['ERR_JAB_AUTH']);
626 continue 2;
629 break;
631 default:
632 return;
635 for ($i = 0; $i < $num_items; $i++)
637 // Make variables available...
638 extract(array_shift($this->queue_data[$object]['data']));
640 switch ($object)
642 case 'email':
643 $err_msg = '';
644 $to = (!$to) ? 'undisclosed-recipients:;' : $to;
646 if ($config['smtp_delivery'])
648 $result = smtpmail($addresses, mail_encode($subject), wordwrap(utf8_wordwrap($msg), 997, "\n", true), $err_msg, $headers);
650 else
652 ob_start();
653 $result = $config['email_function_name']($to, mail_encode($subject), wordwrap(utf8_wordwrap($msg), 997, "\n", true), $headers);
654 $err_msg = ob_get_clean();
657 if (!$result)
659 @unlink($this->cache_file . '.lock');
661 messenger::error('EMAIL', $err_msg);
662 continue 2;
664 break;
666 case 'jabber':
667 foreach ($addresses as $address)
669 if ($this->jabber->send_message($address, $msg, $subject) === false)
671 messenger::error('JABBER', $this->jabber->get_log());
672 continue 3;
675 break;
679 // No more data for this object? Unset it
680 if (!sizeof($this->queue_data[$object]['data']))
682 unset($this->queue_data[$object]);
685 // Post-object processing
686 switch ($object)
688 case 'jabber':
689 // Hang about a couple of secs to ensure the messages are
690 // handled, then disconnect
691 $this->jabber->disconnect();
692 break;
696 if (!sizeof($this->queue_data))
698 @unlink($this->cache_file);
700 else
702 if ($fp = @fopen($this->cache_file, 'wb'))
704 @flock($fp, LOCK_EX);
705 fwrite($fp, "<?php\n\$this->queue_data = unserialize(" . var_export(serialize($this->queue_data), true) . ");\n\n?>");
706 @flock($fp, LOCK_UN);
707 fclose($fp);
709 phpbb_chmod($this->cache_file, CHMOD_WRITE);
713 @unlink($this->cache_file . '.lock');
717 * Save queue
719 public function save()
721 if (!sizeof($this->data))
723 return;
726 if (file_exists($this->cache_file))
728 include($this->cache_file);
730 foreach ($this->queue_data as $object => $data_ary)
732 if (isset($this->data[$object]) && sizeof($this->data[$object]))
734 $this->data[$object]['data'] = array_merge($data_ary['data'], $this->data[$object]['data']);
736 else
738 $this->data[$object]['data'] = $data_ary['data'];
743 if ($fp = @fopen($this->cache_file, 'w'))
745 @flock($fp, LOCK_EX);
746 fwrite($fp, "<?php\n\$this->queue_data = unserialize(" . var_export(serialize($this->data), true) . ");\n\n?>");
747 @flock($fp, LOCK_UN);
748 fclose($fp);
750 phpbb_chmod($this->cache_file, CHMOD_WRITE);
756 * Replacement or substitute for PHP's mail command
758 function smtpmail($addresses, $subject, $message, &$err_msg, $headers = '')
760 global $config, $user;
762 // Fix any bare linefeeds in the message to make it RFC821 Compliant.
763 $message = preg_replace("#(?<!\r)\n#si", "\r\n", $message);
765 if ($headers != '')
767 if (is_array($headers))
769 $headers = (sizeof($headers) > 1) ? join("\n", $headers) : $headers[0];
771 $headers = chop($headers);
773 // Make sure there are no bare linefeeds in the headers
774 $headers = preg_replace('#(?<!\r)\n#si', "\r\n", $headers);
776 // Ok this is rather confusing all things considered,
777 // but we have to grab bcc and cc headers and treat them differently
778 // Something we really didn't take into consideration originally
779 $header_array = explode("\r\n", $headers);
780 $headers = '';
782 foreach ($header_array as $header)
784 if (strpos(strtolower($header), 'cc:') === 0 || strpos(strtolower($header), 'bcc:') === 0)
786 $header = '';
788 $headers .= ($header != '') ? $header . "\r\n" : '';
791 $headers = chop($headers);
794 if (trim($subject) == '')
796 $err_msg = (isset($user->lang['NO_EMAIL_SUBJECT'])) ? $user->lang['NO_EMAIL_SUBJECT'] : 'No email subject specified';
797 return false;
800 if (trim($message) == '')
802 $err_msg = (isset($user->lang['NO_EMAIL_MESSAGE'])) ? $user->lang['NO_EMAIL_MESSAGE'] : 'Email message was blank';
803 return false;
806 $mail_rcpt = $mail_to = $mail_cc = array();
808 // Build correct addresses for RCPT TO command and the client side display (TO, CC)
809 if (isset($addresses['to']) && sizeof($addresses['to']))
811 foreach ($addresses['to'] as $which_ary)
813 $mail_to[] = ($which_ary['name'] != '') ? mail_encode(trim($which_ary['name'])) . ' <' . trim($which_ary['email']) . '>' : '<' . trim($which_ary['email']) . '>';
814 $mail_rcpt['to'][] = '<' . trim($which_ary['email']) . '>';
818 if (isset($addresses['bcc']) && sizeof($addresses['bcc']))
820 foreach ($addresses['bcc'] as $which_ary)
822 $mail_rcpt['bcc'][] = '<' . trim($which_ary['email']) . '>';
826 if (isset($addresses['cc']) && sizeof($addresses['cc']))
828 foreach ($addresses['cc'] as $which_ary)
830 $mail_cc[] = ($which_ary['name'] != '') ? mail_encode(trim($which_ary['name'])) . ' <' . trim($which_ary['email']) . '>' : '<' . trim($which_ary['email']) . '>';
831 $mail_rcpt['cc'][] = '<' . trim($which_ary['email']) . '>';
835 $smtp = new smtp_class();
837 $errno = 0;
838 $errstr = '';
840 $smtp->add_backtrace('Connecting to ' . $config['smtp_host'] . ':' . $config['smtp_port']);
842 // Ok we have error checked as much as we can to this point let's get on it already.
843 ob_start();
844 $smtp->socket = fsockopen($config['smtp_host'], $config['smtp_port'], $errno, $errstr, 20);
845 $error_contents = ob_get_clean();
847 if (!$smtp->socket)
849 if ($errstr)
851 $errstr = utf8_convert_message($errstr);
854 $err_msg = (isset($user->lang['NO_CONNECT_TO_SMTP_HOST'])) ? sprintf($user->lang['NO_CONNECT_TO_SMTP_HOST'], $errno, $errstr) : "Could not connect to smtp host : $errno : $errstr";
855 $err_msg .= ($error_contents) ? '<br /><br />' . htmlspecialchars($error_contents) : '';
856 return false;
859 // Wait for reply
860 if ($err_msg = $smtp->server_parse('220', __LINE__))
862 $smtp->close_session($err_msg);
863 return false;
866 // Let me in. This function handles the complete authentication process
867 if ($err_msg = $smtp->log_into_server($config['smtp_host'], $config['smtp_username'], $config['smtp_password'], $config['smtp_auth_method']))
869 $smtp->close_session($err_msg);
870 return false;
873 // From this point onward most server response codes should be 250
874 // Specify who the mail is from....
875 $smtp->server_send('MAIL FROM:<' . $config['board_email'] . '>');
876 if ($err_msg = $smtp->server_parse('250', __LINE__))
878 $smtp->close_session($err_msg);
879 return false;
882 // Specify each user to send to and build to header.
883 $to_header = implode(', ', $mail_to);
884 $cc_header = implode(', ', $mail_cc);
886 // Now tell the MTA to send the Message to the following people... [TO, BCC, CC]
887 $rcpt = false;
888 foreach ($mail_rcpt as $type => $mail_to_addresses)
890 foreach ($mail_to_addresses as $mail_to_address)
892 // Add an additional bit of error checking to the To field.
893 if (preg_match('#[^ ]+\@[^ ]+#', $mail_to_address))
895 $smtp->server_send("RCPT TO:$mail_to_address");
896 if ($err_msg = $smtp->server_parse('250', __LINE__))
898 // We continue... if users are not resolved we do not care
899 if ($smtp->numeric_response_code != 550)
901 $smtp->close_session($err_msg);
902 return false;
905 else
907 $rcpt = true;
913 // We try to send messages even if a few people do not seem to have valid email addresses, but if no one has, we have to exit here.
914 if (!$rcpt)
916 $user->session_begin();
917 $err_msg .= '<br /><br />';
918 $err_msg .= (isset($user->lang['INVALID_EMAIL_LOG'])) ? sprintf($user->lang['INVALID_EMAIL_LOG'], htmlspecialchars($mail_to_address)) : '<strong>' . htmlspecialchars($mail_to_address) . '</strong> possibly an invalid email address?';
919 $smtp->close_session($err_msg);
920 return false;
923 // Ok now we tell the server we are ready to start sending data
924 $smtp->server_send('DATA');
926 // This is the last response code we look for until the end of the message.
927 if ($err_msg = $smtp->server_parse('354', __LINE__))
929 $smtp->close_session($err_msg);
930 return false;
933 // Send the Subject Line...
934 $smtp->server_send("Subject: $subject");
936 // Now the To Header.
937 $to_header = ($to_header == '') ? 'undisclosed-recipients:;' : $to_header;
938 $smtp->server_send("To: $to_header");
940 // Now the CC Header.
941 if ($cc_header != '')
943 $smtp->server_send("CC: $cc_header");
946 // Now any custom headers....
947 $smtp->server_send("$headers\r\n");
949 // Ok now we are ready for the message...
950 $smtp->server_send($message);
952 // Ok the all the ingredients are mixed in let's cook this puppy...
953 $smtp->server_send('.');
954 if ($err_msg = $smtp->server_parse('250', __LINE__))
956 $smtp->close_session($err_msg);
957 return false;
960 // Now tell the server we are done and close the socket...
961 $smtp->server_send('QUIT');
962 $smtp->close_session($err_msg);
964 return true;
968 * SMTP Class
969 * Auth Mechanisms originally taken from the AUTH Modules found within the PHP Extension and Application Repository (PEAR)
970 * See docs/AUTHORS for more details
971 * @package phpBB3
973 class smtp_class
975 private $server_response = '';
976 public $socket = 0;
977 private $responses = array();
978 private $commands = array();
979 public $numeric_response_code = 0;
981 private $backtrace = false;
982 private $backtrace_log = array();
984 function __construct()
986 // Always create a backtrace for admins to identify SMTP problems
987 $this->backtrace = true;
988 $this->backtrace_log = array();
992 * Add backtrace message for debugging
994 public function add_backtrace($message)
996 if ($this->backtrace)
998 $this->backtrace_log[] = utf8_htmlspecialchars($message);
1003 * Send command to smtp server
1005 public function server_send($command, $private_info = false)
1007 fputs($this->socket, $command . "\r\n");
1009 (!$private_info) ? $this->add_backtrace("# $command") : $this->add_backtrace('# Omitting sensitive information');
1011 // We could put additional code here
1015 * We use the line to give the support people an indication at which command the error occurred
1017 public function server_parse($response, $line)
1019 global $user;
1021 $this->server_response = '';
1022 $this->responses = array();
1023 $this->numeric_response_code = 0;
1025 while (substr($this->server_response, 3, 1) != ' ')
1027 if (!($this->server_response = fgets($this->socket, 256)))
1029 return (isset($user->lang['NO_EMAIL_RESPONSE_CODE'])) ? $user->lang['NO_EMAIL_RESPONSE_CODE'] : 'Could not get mail server response codes';
1031 $this->responses[] = substr(rtrim($this->server_response), 4);
1032 $this->numeric_response_code = (int) substr($this->server_response, 0, 3);
1034 $this->add_backtrace("LINE: $line <- {$this->server_response}");
1037 if (!(substr($this->server_response, 0, 3) == $response))
1039 $this->numeric_response_code = (int) substr($this->server_response, 0, 3);
1040 return (isset($user->lang['EMAIL_SMTP_ERROR_RESPONSE'])) ? sprintf($user->lang['EMAIL_SMTP_ERROR_RESPONSE'], $line, $this->server_response) : "Ran into problems sending Mail at <strong>Line $line</strong>. Response: $this->server_response";
1043 return 0;
1047 * Close session
1049 public function close_session(&$err_msg)
1051 fclose($this->socket);
1053 if ($this->backtrace)
1055 $message = '<h1>Backtrace</h1><p>' . implode('<br />', $this->backtrace_log) . '</p>';
1056 $err_msg .= $message;
1061 * Log into server and get possible auth codes if neccessary
1063 public function log_into_server($hostname, $username, $password, $default_auth_method)
1065 global $user;
1067 $err_msg = '';
1068 $local_host = (function_exists('php_uname')) ? php_uname('n') : $user->host;
1070 // If we are authenticating through pop-before-smtp, we
1071 // have to login ones before we get authenticated
1072 // NOTE: on some configurations the time between an update of the auth database takes so
1073 // long that the first email send does not work. This is not a biggie on a live board (only
1074 // the install mail will most likely fail) - but on a dynamic ip connection this might produce
1075 // severe problems and is not fixable!
1076 if ($default_auth_method == 'POP-BEFORE-SMTP' && $username && $password)
1078 global $config;
1080 $errno = 0;
1081 $errstr = '';
1083 $this->server_send("QUIT");
1084 fclose($this->socket);
1086 $result = $this->pop_before_smtp($hostname, $username, $password);
1087 $username = $password = $default_auth_method = '';
1089 // We need to close the previous session, else the server is not
1090 // able to get our ip for matching...
1091 if (!$this->socket = @fsockopen($config['smtp_host'], $config['smtp_port'], $errno, $errstr, 10))
1093 if ($errstr)
1095 $errstr = utf8_convert_message($errstr);
1098 $err_msg = (isset($user->lang['NO_CONNECT_TO_SMTP_HOST'])) ? sprintf($user->lang['NO_CONNECT_TO_SMTP_HOST'], $errno, $errstr) : "Could not connect to smtp host : $errno : $errstr";
1099 return $err_msg;
1102 // Wait for reply
1103 if ($err_msg = $this->server_parse('220', __LINE__))
1105 $this->close_session($err_msg);
1106 return $err_msg;
1110 // Try EHLO first
1111 $this->server_send("EHLO {$local_host}");
1112 if ($err_msg = $this->server_parse('250', __LINE__))
1114 // a 503 response code means that we're already authenticated
1115 if ($this->numeric_response_code == 503)
1117 return false;
1120 // If EHLO fails, we try HELO
1121 $this->server_send("HELO {$local_host}");
1122 if ($err_msg = $this->server_parse('250', __LINE__))
1124 return ($this->numeric_response_code == 503) ? false : $err_msg;
1128 foreach ($this->responses as $response)
1130 $response = explode(' ', $response);
1131 $response_code = $response[0];
1132 unset($response[0]);
1133 $this->commands[$response_code] = implode(' ', $response);
1136 // If we are not authenticated yet, something might be wrong if no username and passwd passed
1137 if (!$username || !$password)
1139 return false;
1142 if (!isset($this->commands['AUTH']))
1144 return (isset($user->lang['SMTP_NO_AUTH_SUPPORT'])) ? $user->lang['SMTP_NO_AUTH_SUPPORT'] : 'SMTP server does not support authentication';
1147 // Get best authentication method
1148 $available_methods = explode(' ', $this->commands['AUTH']);
1150 // Define the auth ordering if the default auth method was not found
1151 $auth_methods = array('PLAIN', 'LOGIN', 'CRAM-MD5', 'DIGEST-MD5');
1152 $method = '';
1154 if (in_array($default_auth_method, $available_methods))
1156 $method = $default_auth_method;
1158 else
1160 foreach ($auth_methods as $_method)
1162 if (in_array($_method, $available_methods))
1164 $method = $_method;
1165 break;
1170 if (!$method)
1172 return (isset($user->lang['NO_SUPPORTED_AUTH_METHODS'])) ? $user->lang['NO_SUPPORTED_AUTH_METHODS'] : 'No supported authentication methods';
1175 $method = strtolower(str_replace('-', '_', $method));
1176 return $this->$method($username, $password);
1180 * Pop before smtp authentication
1182 private function pop_before_smtp($hostname, $username, $password)
1184 global $user;
1186 if (!$this->socket = @fsockopen($hostname, 110, $errno, $errstr, 10))
1188 if ($errstr)
1190 $errstr = utf8_convert_message($errstr);
1193 return (isset($user->lang['NO_CONNECT_TO_SMTP_HOST'])) ? sprintf($user->lang['NO_CONNECT_TO_SMTP_HOST'], $errno, $errstr) : "Could not connect to smtp host : $errno : $errstr";
1196 $this->server_send("USER $username", true);
1197 if ($err_msg = $this->server_parse('+OK', __LINE__))
1199 return $err_msg;
1202 $this->server_send("PASS $password", true);
1203 if ($err_msg = $this->server_parse('+OK', __LINE__))
1205 return $err_msg;
1208 $this->server_send('QUIT');
1209 fclose($this->socket);
1211 return false;
1215 * Plain authentication method
1217 private function plain($username, $password)
1219 $this->server_send('AUTH PLAIN');
1220 if ($err_msg = $this->server_parse('334', __LINE__))
1222 return ($this->numeric_response_code == 503) ? false : $err_msg;
1225 $base64_method_plain = base64_encode("\0" . $username . "\0" . $password);
1226 $this->server_send($base64_method_plain, true);
1227 if ($err_msg = $this->server_parse('235', __LINE__))
1229 return $err_msg;
1232 return false;
1236 * Login authentication method
1238 private function login($username, $password)
1240 $this->server_send('AUTH LOGIN');
1241 if ($err_msg = $this->server_parse('334', __LINE__))
1243 return ($this->numeric_response_code == 503) ? false : $err_msg;
1246 $this->server_send(base64_encode($username), true);
1247 if ($err_msg = $this->server_parse('334', __LINE__))
1249 return $err_msg;
1252 $this->server_send(base64_encode($password), true);
1253 if ($err_msg = $this->server_parse('235', __LINE__))
1255 return $err_msg;
1258 return false;
1262 * cram_md5 authentication method
1264 private function cram_md5($username, $password)
1266 $this->server_send('AUTH CRAM-MD5');
1267 if ($err_msg = $this->server_parse('334', __LINE__))
1269 return ($this->numeric_response_code == 503) ? false : $err_msg;
1272 $md5_challenge = base64_decode($this->responses[0]);
1273 $password = (strlen($password) > 64) ? pack('H32', md5($password)) : ((strlen($password) < 64) ? str_pad($password, 64, chr(0)) : $password);
1274 $md5_digest = md5((substr($password, 0, 64) ^ str_repeat(chr(0x5C), 64)) . (pack('H32', md5((substr($password, 0, 64) ^ str_repeat(chr(0x36), 64)) . $md5_challenge))));
1276 $base64_method_cram_md5 = base64_encode($username . ' ' . $md5_digest);
1278 $this->server_send($base64_method_cram_md5, true);
1279 if ($err_msg = $this->server_parse('235', __LINE__))
1281 return $err_msg;
1284 return false;
1288 * digest_md5 authentication method
1289 * A real pain in the ***
1291 private function digest_md5($username, $password)
1293 global $config, $user;
1295 $this->server_send('AUTH DIGEST-MD5');
1296 if ($err_msg = $this->server_parse('334', __LINE__))
1298 return ($this->numeric_response_code == 503) ? false : $err_msg;
1301 $md5_challenge = base64_decode($this->responses[0]);
1303 // Parse the md5 challenge - from AUTH_SASL (PEAR)
1304 $tokens = array();
1305 while (preg_match('/^([a-z-]+)=("[^"]+(?<!\\\)"|[^,]+)/i', $md5_challenge, $matches))
1307 // Ignore these as per rfc2831
1308 if ($matches[1] == 'opaque' || $matches[1] == 'domain')
1310 $md5_challenge = substr($md5_challenge, strlen($matches[0]) + 1);
1311 continue;
1314 // Allowed multiple "realm" and "auth-param"
1315 if (!empty($tokens[$matches[1]]) && ($matches[1] == 'realm' || $matches[1] == 'auth-param'))
1317 if (is_array($tokens[$matches[1]]))
1319 $tokens[$matches[1]][] = preg_replace('/^"(.*)"$/', '\\1', $matches[2]);
1321 else
1323 $tokens[$matches[1]] = array($tokens[$matches[1]], preg_replace('/^"(.*)"$/', '\\1', $matches[2]));
1326 else if (!empty($tokens[$matches[1]])) // Any other multiple instance = failure
1328 $tokens = array();
1329 break;
1331 else
1333 $tokens[$matches[1]] = preg_replace('/^"(.*)"$/', '\\1', $matches[2]);
1336 // Remove the just parsed directive from the challenge
1337 $md5_challenge = substr($md5_challenge, strlen($matches[0]) + 1);
1340 // Realm
1341 if (empty($tokens['realm']))
1343 $tokens['realm'] = (function_exists('php_uname')) ? php_uname('n') : $user->host;
1346 // Maxbuf
1347 if (empty($tokens['maxbuf']))
1349 $tokens['maxbuf'] = 65536;
1352 // Required: nonce, algorithm
1353 if (empty($tokens['nonce']) || empty($tokens['algorithm']))
1355 $tokens = array();
1357 $md5_challenge = $tokens;
1359 if (!empty($md5_challenge))
1361 $str = '';
1362 for ($i = 0; $i < 32; $i++)
1364 $str .= chr(mt_rand(0, 255));
1366 $cnonce = base64_encode($str);
1368 $digest_uri = 'smtp/' . $config['smtp_host'];
1370 $auth_1 = sprintf('%s:%s:%s', pack('H32', md5(sprintf('%s:%s:%s', $username, $md5_challenge['realm'], $password))), $md5_challenge['nonce'], $cnonce);
1371 $auth_2 = 'AUTHENTICATE:' . $digest_uri;
1372 $response_value = md5(sprintf('%s:%s:00000001:%s:auth:%s', md5($auth_1), $md5_challenge['nonce'], $cnonce, md5($auth_2)));
1374 $input_string = sprintf('username="%s",realm="%s",nonce="%s",cnonce="%s",nc="00000001",qop=auth,digest-uri="%s",response=%s,%d', $username, $md5_challenge['realm'], $md5_challenge['nonce'], $cnonce, $digest_uri, $response_value, $md5_challenge['maxbuf']);
1376 else
1378 return (isset($user->lang['INVALID_DIGEST_CHALLENGE'])) ? $user->lang['INVALID_DIGEST_CHALLENGE'] : 'Invalid digest challenge';
1381 $base64_method_digest_md5 = base64_encode($input_string);
1382 $this->server_send($base64_method_digest_md5, true);
1383 if ($err_msg = $this->server_parse('334', __LINE__))
1385 return $err_msg;
1388 $this->server_send(' ');
1389 if ($err_msg = $this->server_parse('235', __LINE__))
1391 return $err_msg;
1394 return false;
1399 * Encodes the given string for proper display in UTF-8.
1401 * This version is using base64 encoded data. The downside of this
1402 * is if the mail client does not understand this encoding the user
1403 * is basically doomed with an unreadable subject.
1405 * Please note that this version fully supports RFC 2045 section 6.8.
1407 function mail_encode($str)
1409 // define start delimimter, end delimiter and spacer
1410 $start = "=?UTF-8?B?";
1411 $end = "?=";
1412 $spacer = $end . ' ' . $start;
1413 $split_length = 64;
1415 $encoded_str = base64_encode($str);
1417 // If encoded string meets the limits, we just return with the correct data.
1418 if (strlen($encoded_str) <= $split_length)
1420 return $start . $encoded_str . $end;
1423 // If there is only ASCII data, we just return what we want, correctly splitting the lines.
1424 if (strlen($str) === utf8_strlen($str))
1426 return $start . implode($spacer, str_split($encoded_str, $split_length)) . $end;
1429 // UTF-8 data, compose encoded lines
1430 $array = utf8_str_split($str);
1431 $str = '';
1433 while (sizeof($array))
1435 $text = '';
1437 while (sizeof($array) && intval((strlen($text . $array[0]) + 2) / 3) << 2 <= $split_length)
1439 $text .= array_shift($array);
1442 $str .= $start . base64_encode($text) . $end . ' ';
1445 return substr($str, 0, -1);