Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
12.87% covered (danger)
12.87%
99 / 769
10.87% covered (danger)
10.87%
5 / 46
CRAP
0.00% covered (danger)
0.00%
0 / 3
smtpmail
0.00% covered (danger)
0.00%
0 / 102
0.00% covered (danger)
0.00%
0 / 1
1722
mail_encode
100.00% covered (success)
100.00%
39 / 39
100.00% covered (success)
100.00%
1 / 1
11
phpbb_mail
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
12
messenger
20.21% covered (danger)
20.21%
59 / 292
16.00% covered (danger)
16.00%
4 / 25
6716.81
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 reset
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 set_addresses
50.00% covered (danger)
50.00%
2 / 4
0.00% covered (danger)
0.00%
0 / 1
13.12
 to
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
 cc
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 bcc
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 im
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 replyto
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 from
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 subject
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 headers
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 anti_abuse_headers
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 set_mail_priority
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 template
56.82% covered (warning)
56.82%
25 / 44
0.00% covered (danger)
0.00%
0 / 1
23.59
 assign_vars
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 assign_block_vars
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 send
0.00% covered (danger)
0.00%
0 / 39
0.00% covered (danger)
0.00%
0 / 1
132
 error
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
42
 save_queue
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
20
 generate_message_id
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 build_header
0.00% covered (danger)
0.00%
0 / 25
0.00% covered (danger)
0.00%
0 / 1
42
 msg_email
0.00% covered (danger)
0.00%
0 / 59
0.00% covered (danger)
0.00%
0 / 1
600
 msg_jabber
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
210
 setup_template
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
2
 set_template_paths
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
queue
0.00% covered (danger)
0.00%
0 / 111
0.00% covered (danger)
0.00%
0 / 5
1980
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 init
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 put
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 process
0.00% covered (danger)
0.00%
0 / 84
0.00% covered (danger)
0.00%
0 / 1
1056
 save
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
90
smtp_class
0.00% covered (danger)
0.00%
0 / 191
0.00% covered (danger)
0.00%
0 / 13
8742
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 add_backtrace
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 server_send
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 server_parse
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
42
 close_session
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 log_into_server
0.00% covered (danger)
0.00%
0 / 49
0.00% covered (danger)
0.00%
0 / 1
600
 hello
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
42
 starttls
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
72
 pop_before_smtp
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
42
 plain
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 login
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
30
 cram_md5
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
42
 digest_md5
0.00% covered (danger)
0.00%
0 / 45
0.00% covered (danger)
0.00%
0 / 1
462
1<?php
2/**
3*
4* This file is part of the phpBB Forum Software package.
5*
6* @copyright (c) phpBB Limited <https://www.phpbb.com>
7* @license GNU General Public License, version 2 (GPL-2.0)
8*
9* For full copyright and license information, please see
10* the docs/CREDITS.txt file.
11*
12*/
13
14/**
15* @ignore
16*/
17if (!defined('IN_PHPBB'))
18{
19    exit;
20}
21
22/**
23* Messenger
24*/
25class messenger
26{
27    var $msg, $replyto, $from, $subject;
28    var $addresses = array();
29    var $extra_headers = array();
30
31    var $mail_priority = MAIL_NORMAL_PRIORITY;
32    var $use_queue = true;
33
34    /** @var \phpbb\template\template */
35    protected $template;
36
37    /**
38    * Constructor
39    */
40    function __construct($use_queue = true)
41    {
42        global $config;
43
44        $this->use_queue = (!$config['email_package_size']) ? false : $use_queue;
45        $this->subject = '';
46    }
47
48    /**
49    * Resets all the data (address, template file, etc etc) to default
50    */
51    function reset()
52    {
53        $this->addresses = $this->extra_headers = array();
54        $this->msg = $this->replyto = $this->from = '';
55        $this->mail_priority = MAIL_NORMAL_PRIORITY;
56    }
57
58    /**
59    * Set addresses for to/im as available
60    *
61    * @param array $user User row
62    */
63    function set_addresses($user)
64    {
65        if (isset($user['user_email']) && $user['user_email'])
66        {
67            $this->to($user['user_email'], (isset($user['username']) ? $user['username'] : ''));
68        }
69
70        if (isset($user['user_jabber']) && $user['user_jabber'])
71        {
72            $this->im($user['user_jabber'], (isset($user['username']) ? $user['username'] : ''));
73        }
74    }
75
76    /**
77    * Sets an email address to send to
78    */
79    function to($address, $realname = '')
80    {
81        global $config;
82
83        if (!trim($address))
84        {
85            return;
86        }
87
88        $pos = isset($this->addresses['to']) ? count($this->addresses['to']) : 0;
89
90        $this->addresses['to'][$pos]['email'] = trim($address);
91
92        // If empty sendmail_path on windows, PHP changes the to line
93        if (!$config['smtp_delivery'] && DIRECTORY_SEPARATOR == '\\')
94        {
95            $this->addresses['to'][$pos]['name'] = '';
96        }
97        else
98        {
99            $this->addresses['to'][$pos]['name'] = trim($realname);
100        }
101    }
102
103    /**
104    * Sets an cc address to send to
105    */
106    function cc($address, $realname = '')
107    {
108        if (!trim($address))
109        {
110            return;
111        }
112
113        $pos = isset($this->addresses['cc']) ? count($this->addresses['cc']) : 0;
114        $this->addresses['cc'][$pos]['email'] = trim($address);
115        $this->addresses['cc'][$pos]['name'] = trim($realname);
116    }
117
118    /**
119    * Sets an bcc address to send to
120    */
121    function bcc($address, $realname = '')
122    {
123        if (!trim($address))
124        {
125            return;
126        }
127
128        $pos = isset($this->addresses['bcc']) ? count($this->addresses['bcc']) : 0;
129        $this->addresses['bcc'][$pos]['email'] = trim($address);
130        $this->addresses['bcc'][$pos]['name'] = trim($realname);
131    }
132
133    /**
134    * Sets a im contact to send to
135    */
136    function im($address, $realname = '')
137    {
138        // IM-Addresses could be empty
139        if (!trim($address))
140        {
141            return;
142        }
143
144        $pos = isset($this->addresses['im']) ? count($this->addresses['im']) : 0;
145        $this->addresses['im'][$pos]['uid'] = trim($address);
146        $this->addresses['im'][$pos]['name'] = trim($realname);
147    }
148
149    /**
150    * Set the reply to address
151    */
152    function replyto($address)
153    {
154        $this->replyto = trim($address);
155    }
156
157    /**
158    * Set the from address
159    */
160    function from($address)
161    {
162        $this->from = trim($address);
163    }
164
165    /**
166    * set up subject for mail
167    */
168    function subject($subject = '')
169    {
170        $this->subject = trim($subject);
171    }
172
173    /**
174    * set up extra mail headers
175    */
176    function headers($headers)
177    {
178        $this->extra_headers[] = trim($headers);
179    }
180
181    /**
182    * Adds X-AntiAbuse headers
183    *
184    * @param \phpbb\config\config    $config        Config object
185    * @param \phpbb\user            $user        User object
186    * @return void
187    */
188    function anti_abuse_headers($config, $user)
189    {
190        $this->headers('X-AntiAbuse: Board servername - ' . mail_encode($config['server_name']));
191        $this->headers('X-AntiAbuse: User_id - ' . $user->data['user_id']);
192        $this->headers('X-AntiAbuse: Username - ' . mail_encode($user->data['username']));
193        $this->headers('X-AntiAbuse: User IP - ' . $user->ip);
194    }
195
196    /**
197    * Set the email priority
198    */
199    function set_mail_priority($priority = MAIL_NORMAL_PRIORITY)
200    {
201        $this->mail_priority = $priority;
202    }
203
204    /**
205    * Set email template to use
206    */
207    function template($template_file, $template_lang = '', $template_path = '', $template_dir_prefix = '')
208    {
209        global $config, $phpbb_root_path, $user;
210
211        $template_dir_prefix = (!$template_dir_prefix || $template_dir_prefix[0] === '/') ? $template_dir_prefix : '/' . $template_dir_prefix;
212
213        $this->setup_template();
214
215        if (!trim($template_file))
216        {
217            trigger_error('No template file for emailing set.', E_USER_ERROR);
218        }
219
220        if (!trim($template_lang))
221        {
222            // fall back to board default language if the user's language is
223            // missing $template_file.  If this does not exist either,
224            // $this->template->set_filenames will do a trigger_error
225            $template_lang = basename($config['default_lang']);
226        }
227
228        $ext_template_paths = array(
229            array(
230                'name'         => $template_lang . '_email',
231                'ext_path'     => 'language/' . $template_lang . '/email' . $template_dir_prefix,
232            ),
233        );
234
235        if ($template_path)
236        {
237            $template_paths = array(
238                $template_path . $template_dir_prefix,
239            );
240        }
241        else
242        {
243            $template_path = (!empty($user->lang_path)) ? $user->lang_path : $phpbb_root_path . 'language/';
244            $template_path .= $template_lang . '/email';
245
246            $template_paths = array(
247                $template_path . $template_dir_prefix,
248            );
249
250            $board_language = basename($config['default_lang']);
251
252            // we can only specify default language fallback when the path is not a custom one for which we
253            // do not know the default language alternative
254            if ($template_lang !== $board_language)
255            {
256                $fallback_template_path = (!empty($user->lang_path)) ? $user->lang_path : $phpbb_root_path . 'language/';
257                $fallback_template_path .= $board_language . '/email';
258
259                $template_paths[] = $fallback_template_path . $template_dir_prefix;
260
261                $ext_template_paths[] = array(
262                    'name'        => $board_language . '_email',
263                    'ext_path'    => 'language/' . $board_language . '/email' . $template_dir_prefix,
264                );
265            }
266            // If everything fails just fall back to en template
267            if ($template_lang !== 'en' && $board_language !== 'en')
268            {
269                $fallback_template_path = (!empty($user->lang_path)) ? $user->lang_path : $phpbb_root_path . 'language/';
270                $fallback_template_path .= 'en/email';
271
272                $template_paths[] = $fallback_template_path . $template_dir_prefix;
273
274                $ext_template_paths[] = array(
275                    'name'        => 'en_email',
276                    'ext_path'    => 'language/en/email' . $template_dir_prefix,
277                );
278            }
279        }
280
281        $this->set_template_paths($ext_template_paths, $template_paths);
282
283        $this->template->set_filenames(array(
284            'body'        => $template_file . '.txt',
285        ));
286
287        return true;
288    }
289
290    /**
291    * assign variables to email template
292    */
293    function assign_vars($vars)
294    {
295        $this->setup_template();
296
297        $this->template->assign_vars($vars);
298    }
299
300    function assign_block_vars($blockname, $vars)
301    {
302        $this->setup_template();
303
304        $this->template->assign_block_vars($blockname, $vars);
305    }
306
307    /**
308    * Send the mail out to the recipients set previously in var $this->addresses
309    *
310    * @param int    $method    User notification method NOTIFY_EMAIL|NOTIFY_IM|NOTIFY_BOTH
311    * @param bool    $break    Flag indicating if the function only formats the subject
312    *                        and the message without sending it
313    *
314    * @return bool
315    */
316    function send($method = NOTIFY_EMAIL, $break = false)
317    {
318        global $config, $user, $phpbb_dispatcher;
319
320        // We add some standard variables we always use, no need to specify them always
321        $this->assign_vars(array(
322            'U_BOARD'    => generate_board_url(),
323            'EMAIL_SIG'    => str_replace('<br />', "\n", "-- \n" . html_entity_decode($config['board_email_sig'], ENT_COMPAT)),
324            'SITENAME'    => html_entity_decode($config['sitename'], ENT_COMPAT),
325        ));
326
327        $subject = $this->subject;
328        $template = $this->template;
329        /**
330        * Event to modify the template before parsing
331        *
332        * @event core.modify_notification_template
333        * @var    int                        method        User notification method NOTIFY_EMAIL|NOTIFY_IM|NOTIFY_BOTH
334        * @var    bool                    break        Flag indicating if the function only formats the subject
335        *                                            and the message without sending it
336        * @var    string                    subject        The message subject
337        * @var \phpbb\template\template template    The (readonly) template object
338        * @since 3.2.4-RC1
339        */
340        $vars = array('method', 'break', 'subject', 'template');
341        extract($phpbb_dispatcher->trigger_event('core.modify_notification_template', compact($vars)));
342
343        // Parse message through template
344        $message = trim($this->template->assign_display('body'));
345
346        /**
347        * Event to modify notification message text after parsing
348        *
349        * @event core.modify_notification_message
350        * @var    int        method    User notification method NOTIFY_EMAIL|NOTIFY_IM|NOTIFY_BOTH
351        * @var    bool    break    Flag indicating if the function only formats the subject
352        *                        and the message without sending it
353        * @var    string    subject    The message subject
354        * @var    string    message    The message text
355        * @since 3.1.11-RC1
356        */
357        $vars = array('method', 'break', 'subject', 'message');
358        extract($phpbb_dispatcher->trigger_event('core.modify_notification_message', compact($vars)));
359
360        $this->subject = $subject;
361        $this->msg = $message;
362        unset($subject, $message, $template);
363
364        // Because we use \n for newlines in the body message we need to fix line encoding errors for those admins who uploaded email template files in the wrong encoding
365        $this->msg = str_replace("\r\n", "\n", $this->msg);
366
367        // We now try and pull a subject from the email body ... if it exists,
368        // do this here because the subject may contain a variable
369        $drop_header = '';
370        $match = array();
371        if (preg_match('#^(Subject:(.*?))$#m', $this->msg, $match))
372        {
373            $this->subject = (trim($match[2]) != '') ? trim($match[2]) : (($this->subject != '') ? $this->subject : $user->lang['NO_EMAIL_SUBJECT']);
374            $drop_header .= '[\r\n]*?' . preg_quote($match[1], '#');
375        }
376        else
377        {
378            $this->subject = (($this->subject != '') ? $this->subject : $user->lang['NO_EMAIL_SUBJECT']);
379        }
380
381        if (preg_match('#^(List-Unsubscribe:(.*?))$#m', $this->msg, $match))
382        {
383            $this->extra_headers[] = $match[1];
384            $drop_header .= '[\r\n]*?' . preg_quote($match[1], '#');
385        }
386
387        if ($drop_header)
388        {
389            $this->msg = trim(preg_replace('#' . $drop_header . '#s', '', $this->msg));
390        }
391
392        if ($break)
393        {
394            return true;
395        }
396
397        switch ($method)
398        {
399            case NOTIFY_EMAIL:
400                $result = $this->msg_email();
401            break;
402
403            case NOTIFY_IM:
404                $result = $this->msg_jabber();
405            break;
406
407            case NOTIFY_BOTH:
408                $result = $this->msg_email();
409                $this->msg_jabber();
410            break;
411        }
412
413        $this->reset();
414        return $result;
415    }
416
417    /**
418    * Add error message to log
419    */
420    function error($type, $msg)
421    {
422        global $user, $config, $request, $phpbb_log;
423
424        // Session doesn't exist, create it
425        if (!isset($user->session_id) || $user->session_id === '')
426        {
427            $user->session_begin();
428        }
429
430        $calling_page = html_entity_decode($request->server('REQUEST_URI'), ENT_COMPAT);
431
432        switch ($type)
433        {
434            case 'EMAIL':
435                $message = '<strong>EMAIL/' . (($config['smtp_delivery']) ? 'SMTP' : 'PHP/mail()') . '</strong>';
436            break;
437
438            default:
439                $message = "<strong>$type</strong>";
440            break;
441        }
442
443        $message .= '<br /><em>' . htmlspecialchars($calling_page, ENT_COMPAT) . '</em><br /><br />' . $msg . '<br />';
444        $phpbb_log->add('critical', $user->data['user_id'], $user->ip, 'LOG_ERROR_' . $type, false, array($message));
445    }
446
447    /**
448    * Save to queue
449    */
450    function save_queue()
451    {
452        global $config;
453
454        if ($config['email_package_size'] && $this->use_queue && !empty($this->queue))
455        {
456            $this->queue->save();
457            return;
458        }
459    }
460
461    /**
462    * Generates a valid message id to be used in emails
463    *
464    * @return string message id
465    */
466    function generate_message_id()
467    {
468        global $config, $request;
469
470        $domain = ($config['server_name']) ?: $request->server('SERVER_NAME', 'phpbb.generated');
471
472        return md5(unique_id()) . '@' . $domain;
473    }
474
475    /**
476    * Return email header
477    */
478    function build_header($to, $cc, $bcc)
479    {
480        global $config, $phpbb_dispatcher;
481
482        // We could use keys here, but we won't do this for 3.0.x to retain backwards compatibility
483        $headers = array();
484
485        $headers[] = 'From: ' . $this->from;
486
487        if ($cc)
488        {
489            $headers[] = 'Cc: ' . $cc;
490        }
491
492        if ($bcc)
493        {
494            $headers[] = 'Bcc: ' . $bcc;
495        }
496
497        $headers[] = 'Reply-To: ' . $this->replyto;
498        $headers[] = 'Return-Path: <' . $config['board_email'] . '>';
499        $headers[] = 'Sender: <' . $config['board_email'] . '>';
500        $headers[] = 'MIME-Version: 1.0';
501        $headers[] = 'Message-ID: <' . $this->generate_message_id() . '>';
502        $headers[] = 'Date: ' . date('r', time());
503        $headers[] = 'Content-Type: text/plain; charset=UTF-8'; // format=flowed
504        $headers[] = 'Content-Transfer-Encoding: 8bit'; // 7bit
505
506        $headers[] = 'X-Priority: ' . $this->mail_priority;
507        $headers[] = 'X-MSMail-Priority: ' . (($this->mail_priority == MAIL_LOW_PRIORITY) ? 'Low' : (($this->mail_priority == MAIL_NORMAL_PRIORITY) ? 'Normal' : 'High'));
508        $headers[] = 'X-Mailer: phpBB3';
509        $headers[] = 'X-MimeOLE: phpBB3';
510        $headers[] = 'X-phpBB-Origin: phpbb://' . str_replace(array('http://', 'https://'), array('', ''), generate_board_url());
511
512        /**
513        * Event to modify email header entries
514        *
515        * @event core.modify_email_headers
516        * @var    array    headers    Array containing email header entries
517        * @since 3.1.11-RC1
518        */
519        $vars = array('headers');
520        extract($phpbb_dispatcher->trigger_event('core.modify_email_headers', compact($vars)));
521
522        if (count($this->extra_headers))
523        {
524            $headers = array_merge($headers, $this->extra_headers);
525        }
526
527        return $headers;
528    }
529
530    /**
531    * Send out emails
532    */
533    function msg_email()
534    {
535        global $config, $phpbb_dispatcher;
536
537        if (empty($config['email_enable']))
538        {
539            return false;
540        }
541
542        // Addresses to send to?
543        if (empty($this->addresses) || (empty($this->addresses['to']) && empty($this->addresses['cc']) && empty($this->addresses['bcc'])))
544        {
545            // Send was successful. ;)
546            return true;
547        }
548
549        $use_queue = false;
550        if ($config['email_package_size'] && $this->use_queue)
551        {
552            if (empty($this->queue))
553            {
554                $this->queue = new queue();
555                $this->queue->init('email', $config['email_package_size']);
556            }
557            $use_queue = true;
558        }
559
560        $contact_name = html_entity_decode($config['board_contact_name'], ENT_COMPAT);
561        $board_contact = (($contact_name !== '') ? '"' . mail_encode($contact_name) . '" ' : '') . '<' . $config['board_contact'] . '>';
562
563        $break = false;
564        $addresses = $this->addresses;
565        $subject = $this->subject;
566        $msg = $this->msg;
567        /**
568        * Event to send message via external transport
569        *
570        * @event core.notification_message_email
571        * @var    bool    break        Flag indicating if the function return after hook
572        * @var    array    addresses     The message recipients
573        * @var    string    subject        The message subject
574        * @var    string    msg            The message text
575        * @since 3.2.4-RC1
576        */
577        $vars = array(
578            'break',
579            'addresses',
580            'subject',
581            'msg',
582        );
583        extract($phpbb_dispatcher->trigger_event('core.notification_message_email', compact($vars)));
584
585        $this->addresses = $addresses;
586        $this->subject = $subject;
587        $this->msg = $msg;
588        unset($addresses, $subject, $msg);
589
590        if ($break)
591        {
592            return true;
593        }
594
595        if (empty($this->replyto))
596        {
597            $this->replyto = $board_contact;
598        }
599
600        if (empty($this->from))
601        {
602            $this->from = $board_contact;
603        }
604
605        $encode_eol = $config['smtp_delivery'] || PHP_VERSION_ID >= 80000 ? "\r\n" : PHP_EOL;
606
607        // Build to, cc and bcc strings
608        $to = $cc = $bcc = '';
609        foreach ($this->addresses as $type => $address_ary)
610        {
611            if ($type == 'im')
612            {
613                continue;
614            }
615
616            foreach ($address_ary as $which_ary)
617            {
618                ${$type} .= ((${$type} != '') ? ', ' : '') . (($which_ary['name'] != '') ? mail_encode($which_ary['name'], $encode_eol) . ' <' . $which_ary['email'] . '>' : $which_ary['email']);
619            }
620        }
621
622        // Build header
623        $headers = $this->build_header($to, $cc, $bcc);
624
625        // Send message ...
626        if (!$use_queue)
627        {
628            $mail_to = ($to == '') ? 'undisclosed-recipients:;' : $to;
629            $err_msg = '';
630
631            if ($config['smtp_delivery'])
632            {
633                $result = smtpmail($this->addresses, mail_encode($this->subject), wordwrap(utf8_wordwrap($this->msg), 997, "\n", true), $err_msg, $headers);
634            }
635            else
636            {
637                $result = phpbb_mail($mail_to, $this->subject, $this->msg, $headers, $encode_eol, $err_msg);
638            }
639
640            if (!$result)
641            {
642                $this->error('EMAIL', $err_msg);
643                return false;
644            }
645        }
646        else
647        {
648            $this->queue->put('email', array(
649                'to'            => $to,
650                'addresses'        => $this->addresses,
651                'subject'        => $this->subject,
652                'msg'            => $this->msg,
653                'headers'        => $headers)
654            );
655        }
656
657        return true;
658    }
659
660    /**
661    * Send jabber message out
662    */
663    function msg_jabber()
664    {
665        global $config, $user, $phpbb_root_path, $phpEx;
666
667        if (empty($config['jab_enable']) || empty($config['jab_host']) || empty($config['jab_username']) || empty($config['jab_password']))
668        {
669            return false;
670        }
671
672        if (empty($this->addresses['im']))
673        {
674            // Send was successful. ;)
675            return true;
676        }
677
678        $use_queue = false;
679        if ($config['jab_package_size'] && $this->use_queue)
680        {
681            if (empty($this->queue))
682            {
683                $this->queue = new queue();
684                $this->queue->init('jabber', $config['jab_package_size']);
685            }
686            $use_queue = true;
687        }
688
689        $addresses = array();
690        foreach ($this->addresses['im'] as $type => $uid_ary)
691        {
692            $addresses[] = $uid_ary['uid'];
693        }
694        $addresses = array_unique($addresses);
695
696        if (!$use_queue)
697        {
698            include_once($phpbb_root_path . 'includes/functions_jabber.' . $phpEx);
699            $this->jabber = new jabber($config['jab_host'], $config['jab_port'], $config['jab_username'], html_entity_decode($config['jab_password'], ENT_COMPAT), $config['jab_use_ssl'], $config['jab_verify_peer'], $config['jab_verify_peer_name'], $config['jab_allow_self_signed']);
700
701            if (!$this->jabber->connect())
702            {
703                $this->error('JABBER', $user->lang['ERR_JAB_CONNECT'] . '<br />' . $this->jabber->get_log());
704                return false;
705            }
706
707            if (!$this->jabber->login())
708            {
709                $this->error('JABBER', $user->lang['ERR_JAB_AUTH'] . '<br />' . $this->jabber->get_log());
710                return false;
711            }
712
713            foreach ($addresses as $address)
714            {
715                $this->jabber->send_message($address, $this->msg, $this->subject);
716            }
717
718            $this->jabber->disconnect();
719        }
720        else
721        {
722            $this->queue->put('jabber', array(
723                'addresses'        => $addresses,
724                'subject'        => $this->subject,
725                'msg'            => $this->msg)
726            );
727        }
728        unset($addresses);
729        return true;
730    }
731
732    /**
733    * Setup template engine
734    */
735    protected function setup_template()
736    {
737        global $phpbb_container, $phpbb_dispatcher;
738
739        if ($this->template instanceof \phpbb\template\template)
740        {
741            return;
742        }
743
744        $template_environment = new \phpbb\template\twig\environment(
745            $phpbb_container->get('assets.bag'),
746            $phpbb_container->get('config'),
747            $phpbb_container->get('filesystem'),
748            $phpbb_container->get('path_helper'),
749            $phpbb_container->getParameter('core.template.cache_path'),
750            $phpbb_container->get('ext.manager'),
751            new \phpbb\template\twig\loader(),
752            $phpbb_dispatcher,
753            array()
754        );
755        $template_environment->setLexer($phpbb_container->get('template.twig.lexer'));
756
757        $this->template = new \phpbb\template\twig\twig(
758            $phpbb_container->get('path_helper'),
759            $phpbb_container->get('config'),
760            new \phpbb\template\context(),
761            $template_environment,
762            $phpbb_container->getParameter('core.template.cache_path'),
763            $phpbb_container->get('user'),
764            $phpbb_container->get('template.twig.extensions.collection'),
765            $phpbb_container->get('ext.manager')
766        );
767    }
768
769    /**
770    * Set template paths to load
771    */
772    protected function set_template_paths($path_name, $paths)
773    {
774        $this->setup_template();
775
776        $this->template->set_custom_style($path_name, $paths);
777    }
778}
779
780/**
781* handling email and jabber queue
782*/
783class queue
784{
785    var $data = array();
786    var $queue_data = array();
787    var $package_size = 0;
788    var $cache_file = '';
789    var $eol = "\n";
790
791    /**
792     * @var \phpbb\filesystem\filesystem_interface
793     */
794    protected $filesystem;
795
796    /**
797    * constructor
798    */
799    function __construct()
800    {
801        global $phpEx, $phpbb_root_path, $phpbb_filesystem, $phpbb_container;
802
803        $this->data = array();
804        $this->cache_file = $phpbb_container->getParameter('core.cache_dir') . "queue.$phpEx";
805        $this->filesystem = $phpbb_filesystem;
806    }
807
808    /**
809    * Init a queue object
810    */
811    function init($object, $package_size)
812    {
813        $this->data[$object] = array();
814        $this->data[$object]['package_size'] = $package_size;
815        $this->data[$object]['data'] = array();
816    }
817
818    /**
819    * Put object in queue
820    */
821    function put($object, $scope)
822    {
823        $this->data[$object]['data'][] = $scope;
824    }
825
826    /**
827    * Process queue
828    * Using lock file
829    */
830    function process()
831    {
832        global $config, $phpEx, $phpbb_root_path, $user, $phpbb_dispatcher;
833
834        $lock = new \phpbb\lock\flock($this->cache_file);
835        $lock->acquire();
836
837        // avoid races, check file existence once
838        $have_cache_file = file_exists($this->cache_file);
839        if (!$have_cache_file || $config['last_queue_run'] > time() - $config['queue_interval'])
840        {
841            if (!$have_cache_file)
842            {
843                $config->set('last_queue_run', time(), false);
844            }
845
846            $lock->release();
847            return;
848        }
849
850        $config->set('last_queue_run', time(), false);
851
852        include($this->cache_file);
853
854        foreach ($this->queue_data as $object => $data_ary)
855        {
856            @set_time_limit(0);
857
858            if (!isset($data_ary['package_size']))
859            {
860                $data_ary['package_size'] = 0;
861            }
862
863            $package_size = $data_ary['package_size'];
864            $num_items = (!$package_size || count($data_ary['data']) < $package_size) ? count($data_ary['data']) : $package_size;
865
866            /*
867            * This code is commented out because it causes problems on some web hosts.
868            * The core problem is rather restrictive email sending limits.
869            * This code is nly useful if you have no such restrictions from the
870            * web host and the package size setting is wrong.
871
872            // If the amount of emails to be sent is way more than package_size than we need to increase it to prevent backlogs...
873            if (count($data_ary['data']) > $package_size * 2.5)
874            {
875                $num_items = count($data_ary['data']);
876            }
877            */
878
879            switch ($object)
880            {
881                case 'email':
882                    // Delete the email queued objects if mailing is disabled
883                    if (!$config['email_enable'])
884                    {
885                        unset($this->queue_data['email']);
886                        continue 2;
887                    }
888                break;
889
890                case 'jabber':
891                    if (!$config['jab_enable'])
892                    {
893                        unset($this->queue_data['jabber']);
894                        continue 2;
895                    }
896
897                    include_once($phpbb_root_path . 'includes/functions_jabber.' . $phpEx);
898                    $this->jabber = new jabber($config['jab_host'], $config['jab_port'], $config['jab_username'], html_entity_decode($config['jab_password'], ENT_COMPAT), $config['jab_use_ssl'], $config['jab_verify_peer'], $config['jab_verify_peer_name'], $config['jab_allow_self_signed']);
899
900                    if (!$this->jabber->connect())
901                    {
902                        $messenger = new messenger();
903                        $messenger->error('JABBER', $user->lang['ERR_JAB_CONNECT']);
904                        continue 2;
905                    }
906
907                    if (!$this->jabber->login())
908                    {
909                        $messenger = new messenger();
910                        $messenger->error('JABBER', $user->lang['ERR_JAB_AUTH']);
911                        continue 2;
912                    }
913
914                break;
915
916                default:
917                    $lock->release();
918                    return;
919            }
920
921            for ($i = 0; $i < $num_items; $i++)
922            {
923                // Make variables available...
924                extract(array_shift($this->queue_data[$object]['data']));
925
926                switch ($object)
927                {
928                    case 'email':
929                        $break = false;
930                        /**
931                        * Event to send message via external transport
932                        *
933                        * @event core.notification_message_process
934                        * @var    bool    break        Flag indicating if the function return after hook
935                        * @var    array    addresses     The message recipients
936                        * @var    string    subject        The message subject
937                        * @var    string    msg            The message text
938                        * @since 3.2.4-RC1
939                        */
940                        $vars = array(
941                            'break',
942                            'addresses',
943                            'subject',
944                            'msg',
945                        );
946                        extract($phpbb_dispatcher->trigger_event('core.notification_message_process', compact($vars)));
947
948                        if (!$break)
949                        {
950                            $err_msg = '';
951                            $to = (!$to) ? 'undisclosed-recipients:;' : $to;
952
953                            if ($config['smtp_delivery'])
954                            {
955                                $result = smtpmail($addresses, mail_encode($subject), wordwrap(utf8_wordwrap($msg), 997, "\n", true), $err_msg, $headers);
956                            }
957                            else
958                            {
959                                $encode_eol = $config['smtp_delivery'] || PHP_VERSION_ID >= 80000 ? "\r\n" : PHP_EOL;
960                                $result = phpbb_mail($to, $subject, $msg, $headers, $encode_eol, $err_msg);
961                            }
962
963                            if (!$result)
964                            {
965                                $messenger = new messenger();
966                                $messenger->error('EMAIL', $err_msg);
967                                continue 2;
968                            }
969                        }
970                    break;
971
972                    case 'jabber':
973                        foreach ($addresses as $address)
974                        {
975                            if ($this->jabber->send_message($address, $msg, $subject) === false)
976                            {
977                                $messenger = new messenger();
978                                $messenger->error('JABBER', $this->jabber->get_log());
979                                continue 3;
980                            }
981                        }
982                    break;
983                }
984            }
985
986            // No more data for this object? Unset it
987            if (!count($this->queue_data[$object]['data']))
988            {
989                unset($this->queue_data[$object]);
990            }
991
992            // Post-object processing
993            switch ($object)
994            {
995                case 'jabber':
996                    // Hang about a couple of secs to ensure the messages are
997                    // handled, then disconnect
998                    $this->jabber->disconnect();
999                break;
1000            }
1001        }
1002
1003        if (!count($this->queue_data))
1004        {
1005            @unlink($this->cache_file);
1006        }
1007        else
1008        {
1009            if ($fp = @fopen($this->cache_file, 'wb'))
1010            {
1011                fwrite($fp, "<?php\nif (!defined('IN_PHPBB')) exit;\n\$this->queue_data = unserialize(" . var_export(serialize($this->queue_data), true) . ");\n\n?>");
1012                fclose($fp);
1013
1014                if (function_exists('opcache_invalidate'))
1015                {
1016                    @opcache_invalidate($this->cache_file);
1017                }
1018
1019                try
1020                {
1021                    $this->filesystem->phpbb_chmod($this->cache_file, \phpbb\filesystem\filesystem_interface::CHMOD_READ | \phpbb\filesystem\filesystem_interface::CHMOD_WRITE);
1022                }
1023                catch (\phpbb\filesystem\exception\filesystem_exception $e)
1024                {
1025                    // Do nothing
1026                }
1027            }
1028        }
1029
1030        $lock->release();
1031    }
1032
1033    /**
1034    * Save queue
1035    */
1036    function save()
1037    {
1038        if (!count($this->data))
1039        {
1040            return;
1041        }
1042
1043        $lock = new \phpbb\lock\flock($this->cache_file);
1044        $lock->acquire();
1045
1046        if (file_exists($this->cache_file))
1047        {
1048            include($this->cache_file);
1049
1050            foreach ($this->queue_data as $object => $data_ary)
1051            {
1052                if (isset($this->data[$object]) && count($this->data[$object]))
1053                {
1054                    $this->data[$object]['data'] = array_merge($data_ary['data'], $this->data[$object]['data']);
1055                }
1056                else
1057                {
1058                    $this->data[$object]['data'] = $data_ary['data'];
1059                }
1060            }
1061        }
1062
1063        if ($fp = @fopen($this->cache_file, 'w'))
1064        {
1065            fwrite($fp, "<?php\nif (!defined('IN_PHPBB')) exit;\n\$this->queue_data = unserialize(" . var_export(serialize($this->data), true) . ");\n\n?>");
1066            fclose($fp);
1067
1068            if (function_exists('opcache_invalidate'))
1069            {
1070                @opcache_invalidate($this->cache_file);
1071            }
1072
1073            try
1074            {
1075                $this->filesystem->phpbb_chmod($this->cache_file, \phpbb\filesystem\filesystem_interface::CHMOD_READ | \phpbb\filesystem\filesystem_interface::CHMOD_WRITE);
1076            }
1077            catch (\phpbb\filesystem\exception\filesystem_exception $e)
1078            {
1079                // Do nothing
1080            }
1081
1082            $this->data = array();
1083        }
1084
1085        $lock->release();
1086    }
1087}
1088
1089/**
1090* Replacement or substitute for PHP's mail command
1091*/
1092function smtpmail($addresses, $subject, $message, &$err_msg, $headers = false)
1093{
1094    global $config, $user;
1095
1096    // Fix any bare linefeeds in the message to make it RFC821 Compliant.
1097    $message = preg_replace("#(?<!\r)\n#si", "\r\n", $message);
1098
1099    if ($headers !== false)
1100    {
1101        if (!is_array($headers))
1102        {
1103            // Make sure there are no bare linefeeds in the headers
1104            $headers = preg_replace('#(?<!\r)\n#si', "\n", $headers);
1105            $headers = explode("\n", $headers);
1106        }
1107
1108        // Ok this is rather confusing all things considered,
1109        // but we have to grab bcc and cc headers and treat them differently
1110        // Something we really didn't take into consideration originally
1111        $headers_used = array();
1112
1113        foreach ($headers as $header)
1114        {
1115            if (strpos(strtolower($header), 'cc:') === 0 || strpos(strtolower($header), 'bcc:') === 0)
1116            {
1117                continue;
1118            }
1119            $headers_used[] = trim($header);
1120        }
1121
1122        $headers = chop(implode("\r\n", $headers_used));
1123    }
1124
1125    if (trim($subject) == '')
1126    {
1127        $err_msg = (isset($user->lang['NO_EMAIL_SUBJECT'])) ? $user->lang['NO_EMAIL_SUBJECT'] : 'No email subject specified';
1128        return false;
1129    }
1130
1131    if (trim($message) == '')
1132    {
1133        $err_msg = (isset($user->lang['NO_EMAIL_MESSAGE'])) ? $user->lang['NO_EMAIL_MESSAGE'] : 'Email message was blank';
1134        return false;
1135    }
1136
1137    $mail_rcpt = $mail_to = $mail_cc = array();
1138
1139    // Build correct addresses for RCPT TO command and the client side display (TO, CC)
1140    if (isset($addresses['to']) && count($addresses['to']))
1141    {
1142        foreach ($addresses['to'] as $which_ary)
1143        {
1144            $mail_to[] = ($which_ary['name'] != '') ? mail_encode(trim($which_ary['name'])) . ' <' . trim($which_ary['email']) . '>' : '<' . trim($which_ary['email']) . '>';
1145            $mail_rcpt['to'][] = '<' . trim($which_ary['email']) . '>';
1146        }
1147    }
1148
1149    if (isset($addresses['bcc']) && count($addresses['bcc']))
1150    {
1151        foreach ($addresses['bcc'] as $which_ary)
1152        {
1153            $mail_rcpt['bcc'][] = '<' . trim($which_ary['email']) . '>';
1154        }
1155    }
1156
1157    if (isset($addresses['cc']) && count($addresses['cc']))
1158    {
1159        foreach ($addresses['cc'] as $which_ary)
1160        {
1161            $mail_cc[] = ($which_ary['name'] != '') ? mail_encode(trim($which_ary['name'])) . ' <' . trim($which_ary['email']) . '>' : '<' . trim($which_ary['email']) . '>';
1162            $mail_rcpt['cc'][] = '<' . trim($which_ary['email']) . '>';
1163        }
1164    }
1165
1166    $smtp = new smtp_class();
1167
1168    $errno = 0;
1169    $errstr = '';
1170
1171    $smtp->add_backtrace('Connecting to ' . $config['smtp_host'] . ':' . $config['smtp_port']);
1172
1173    // Ok we have error checked as much as we can to this point let's get on it already.
1174    if (!class_exists('\phpbb\error_collector'))
1175    {
1176        global $phpbb_root_path, $phpEx;
1177        include($phpbb_root_path . 'includes/error_collector.' . $phpEx);
1178    }
1179    $collector = new \phpbb\error_collector;
1180    $collector->install();
1181
1182    $options = array();
1183    $verify_peer = (bool) $config['smtp_verify_peer'];
1184    $verify_peer_name = (bool) $config['smtp_verify_peer_name'];
1185    $allow_self_signed = (bool) $config['smtp_allow_self_signed'];
1186    $remote_socket = $config['smtp_host'] . ':' . $config['smtp_port'];
1187
1188    // Set ssl context options, see http://php.net/manual/en/context.ssl.php
1189    $options['ssl'] = array('verify_peer' => $verify_peer, 'verify_peer_name' => $verify_peer_name, 'allow_self_signed' => $allow_self_signed);
1190    $socket_context = stream_context_create($options);
1191
1192    $smtp->socket = @stream_socket_client($remote_socket, $errno, $errstr, 20, STREAM_CLIENT_CONNECT, $socket_context);
1193    $collector->uninstall();
1194    $error_contents = $collector->format_errors();
1195
1196    if (!$smtp->socket)
1197    {
1198        if ($errstr)
1199        {
1200            $errstr = utf8_convert_message($errstr);
1201        }
1202
1203        $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";
1204        $err_msg .= ($error_contents) ? '<br /><br />' . htmlspecialchars($error_contents, ENT_COMPAT) : '';
1205        return false;
1206    }
1207
1208    // Wait for reply
1209    if ($err_msg = $smtp->server_parse('220', __LINE__))
1210    {
1211        $smtp->close_session($err_msg);
1212        return false;
1213    }
1214
1215    // Let me in. This function handles the complete authentication process
1216    if ($err_msg = $smtp->log_into_server($config['smtp_host'], $config['smtp_username'], html_entity_decode($config['smtp_password'], ENT_COMPAT), $config['smtp_auth_method']))
1217    {
1218        $smtp->close_session($err_msg);
1219        return false;
1220    }
1221
1222    // From this point onward most server response codes should be 250
1223    // Specify who the mail is from....
1224    $smtp->server_send('MAIL FROM:<' . $config['board_email'] . '>');
1225    if ($err_msg = $smtp->server_parse('250', __LINE__))
1226    {
1227        $smtp->close_session($err_msg);
1228        return false;
1229    }
1230
1231    // Specify each user to send to and build to header.
1232    $to_header = implode(', ', $mail_to);
1233    $cc_header = implode(', ', $mail_cc);
1234
1235    // Now tell the MTA to send the Message to the following people... [TO, BCC, CC]
1236    $rcpt = false;
1237    foreach ($mail_rcpt as $type => $mail_to_addresses)
1238    {
1239        foreach ($mail_to_addresses as $mail_to_address)
1240        {
1241            // Add an additional bit of error checking to the To field.
1242            if (preg_match('#[^ ]+\@[^ ]+#', $mail_to_address))
1243            {
1244                $smtp->server_send("RCPT TO:$mail_to_address");
1245                if ($err_msg = $smtp->server_parse('250', __LINE__))
1246                {
1247                    // We continue... if users are not resolved we do not care
1248                    if ($smtp->numeric_response_code != 550)
1249                    {
1250                        $smtp->close_session($err_msg);
1251                        return false;
1252                    }
1253                }
1254                else
1255                {
1256                    $rcpt = true;
1257                }
1258            }
1259        }
1260    }
1261
1262    // 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.
1263    if (!$rcpt)
1264    {
1265        $user->session_begin();
1266        $err_msg .= '<br /><br />';
1267        $err_msg .= (isset($user->lang['INVALID_EMAIL_LOG'])) ? sprintf($user->lang['INVALID_EMAIL_LOG'], htmlspecialchars($mail_to_address, ENT_COMPAT)) : '<strong>' . htmlspecialchars($mail_to_address, ENT_COMPAT) . '</strong> possibly an invalid email address?';
1268        $smtp->close_session($err_msg);
1269        return false;
1270    }
1271
1272    // Ok now we tell the server we are ready to start sending data
1273    $smtp->server_send('DATA');
1274
1275    // This is the last response code we look for until the end of the message.
1276    if ($err_msg = $smtp->server_parse('354', __LINE__))
1277    {
1278        $smtp->close_session($err_msg);
1279        return false;
1280    }
1281
1282    // Send the Subject Line...
1283    $smtp->server_send("Subject: $subject");
1284
1285    // Now the To Header.
1286    $to_header = ($to_header == '') ? 'undisclosed-recipients:;' : $to_header;
1287    $smtp->server_send("To: $to_header");
1288
1289    // Now the CC Header.
1290    if ($cc_header != '')
1291    {
1292        $smtp->server_send("CC: $cc_header");
1293    }
1294
1295    // Now any custom headers....
1296    if ($headers !== false)
1297    {
1298        $smtp->server_send("$headers\r\n");
1299    }
1300
1301    // Ok now we are ready for the message...
1302    $smtp->server_send($message);
1303
1304    // Ok the all the ingredients are mixed in let's cook this puppy...
1305    $smtp->server_send('.');
1306    if ($err_msg = $smtp->server_parse('250', __LINE__))
1307    {
1308        $smtp->close_session($err_msg);
1309        return false;
1310    }
1311
1312    // Now tell the server we are done and close the socket...
1313    $smtp->server_send('QUIT');
1314    $smtp->close_session($err_msg);
1315
1316    return true;
1317}
1318
1319/**
1320* SMTP Class
1321* Auth Mechanisms originally taken from the AUTH Modules found within the PHP Extension and Application Repository (PEAR)
1322* See docs/AUTHORS for more details
1323*/
1324class smtp_class
1325{
1326    var $server_response = '';
1327    var $socket = 0;
1328    protected $socket_tls = false;
1329    var $responses = array();
1330    var $commands = array();
1331    var $numeric_response_code = 0;
1332
1333    var $backtrace = false;
1334    var $backtrace_log = array();
1335
1336    function __construct()
1337    {
1338        // Always create a backtrace for admins to identify SMTP problems
1339        $this->backtrace = true;
1340        $this->backtrace_log = array();
1341    }
1342
1343    /**
1344    * Add backtrace message for debugging
1345    */
1346    function add_backtrace($message)
1347    {
1348        if ($this->backtrace)
1349        {
1350            $this->backtrace_log[] = utf8_htmlspecialchars($message, ENT_COMPAT);
1351        }
1352    }
1353
1354    /**
1355    * Send command to smtp server
1356    */
1357    function server_send($command, $private_info = false)
1358    {
1359        fputs($this->socket, $command . "\r\n");
1360
1361        (!$private_info) ? $this->add_backtrace("$command") : $this->add_backtrace('# Omitting sensitive information');
1362
1363        // We could put additional code here
1364    }
1365
1366    /**
1367    * We use the line to give the support people an indication at which command the error occurred
1368    */
1369    function server_parse($response, $line)
1370    {
1371        global $user;
1372
1373        $this->server_response = '';
1374        $this->responses = array();
1375        $this->numeric_response_code = 0;
1376
1377        while (substr($this->server_response, 3, 1) != ' ')
1378        {
1379            if (!($this->server_response = fgets($this->socket, 256)))
1380            {
1381                return (isset($user->lang['NO_EMAIL_RESPONSE_CODE'])) ? $user->lang['NO_EMAIL_RESPONSE_CODE'] : 'Could not get mail server response codes';
1382            }
1383            $this->responses[] = substr(rtrim($this->server_response), 4);
1384            $this->numeric_response_code = (int) substr($this->server_response, 0, 3);
1385
1386            $this->add_backtrace("LINE: $line <- {$this->server_response}");
1387        }
1388
1389        if (!(substr($this->server_response, 0, 3) == $response))
1390        {
1391            $this->numeric_response_code = (int) substr($this->server_response, 0, 3);
1392            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";
1393        }
1394
1395        return 0;
1396    }
1397
1398    /**
1399    * Close session
1400    */
1401    function close_session(&$err_msg)
1402    {
1403        fclose($this->socket);
1404
1405        if ($this->backtrace)
1406        {
1407            $message = '<h1>Backtrace</h1><p>' . implode('<br />', $this->backtrace_log) . '</p>';
1408            $err_msg .= $message;
1409        }
1410    }
1411
1412    /**
1413    * Log into server and get possible auth codes if neccessary
1414    */
1415    function log_into_server($hostname, $username, $password, $default_auth_method)
1416    {
1417        global $user;
1418
1419        // Here we try to determine the *real* hostname (reverse DNS entry preferrably)
1420        $local_host = $user->host;
1421
1422        if (function_exists('php_uname'))
1423        {
1424            $local_host = php_uname('n');
1425
1426            // Able to resolve name to IP
1427            if (($addr = @gethostbyname($local_host)) !== $local_host)
1428            {
1429                // Able to resolve IP back to name
1430                if (($name = @gethostbyaddr($addr)) !== $addr)
1431                {
1432                    $local_host = $name;
1433                }
1434            }
1435        }
1436
1437        // If we are authenticating through pop-before-smtp, we
1438        // have to login ones before we get authenticated
1439        // NOTE: on some configurations the time between an update of the auth database takes so
1440        // long that the first email send does not work. This is not a biggie on a live board (only
1441        // the install mail will most likely fail) - but on a dynamic ip connection this might produce
1442        // severe problems and is not fixable!
1443        if ($default_auth_method == 'POP-BEFORE-SMTP' && $username && $password)
1444        {
1445            global $config;
1446
1447            $errno = 0;
1448            $errstr = '';
1449
1450            $this->server_send("QUIT");
1451            fclose($this->socket);
1452
1453            $this->pop_before_smtp($hostname, $username, $password);
1454            $username = $password = $default_auth_method = '';
1455
1456            // We need to close the previous session, else the server is not
1457            // able to get our ip for matching...
1458            if (!$this->socket = @fsockopen($config['smtp_host'], $config['smtp_port'], $errno, $errstr, 10))
1459            {
1460                if ($errstr)
1461                {
1462                    $errstr = utf8_convert_message($errstr);
1463                }
1464
1465                $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";
1466                return $err_msg;
1467            }
1468
1469            // Wait for reply
1470            if ($err_msg = $this->server_parse('220', __LINE__))
1471            {
1472                $this->close_session($err_msg);
1473                return $err_msg;
1474            }
1475        }
1476
1477        $hello_result = $this->hello($local_host);
1478        if (!is_null($hello_result))
1479        {
1480            return $hello_result;
1481        }
1482
1483        // SMTP STARTTLS (RFC 3207)
1484        if (!$this->socket_tls)
1485        {
1486            $this->socket_tls = $this->starttls();
1487
1488            if ($this->socket_tls)
1489            {
1490                // Switched to TLS
1491                // RFC 3207: "The client MUST discard any knowledge obtained from the server, [...]"
1492                // So say hello again
1493                $hello_result = $this->hello($local_host);
1494
1495                if (!is_null($hello_result))
1496                {
1497                    return $hello_result;
1498                }
1499            }
1500        }
1501
1502        // If we are not authenticated yet, something might be wrong if no username and passwd passed
1503        if (!$username || !$password)
1504        {
1505            return false;
1506        }
1507
1508        if (!isset($this->commands['AUTH']))
1509        {
1510            return (isset($user->lang['SMTP_NO_AUTH_SUPPORT'])) ? $user->lang['SMTP_NO_AUTH_SUPPORT'] : 'SMTP server does not support authentication';
1511        }
1512
1513        // Get best authentication method
1514        $available_methods = explode(' ', $this->commands['AUTH']);
1515
1516        // Define the auth ordering if the default auth method was not found
1517        $auth_methods = array('PLAIN', 'LOGIN', 'CRAM-MD5', 'DIGEST-MD5');
1518        $method = '';
1519
1520        if (in_array($default_auth_method, $available_methods))
1521        {
1522            $method = $default_auth_method;
1523        }
1524        else
1525        {
1526            foreach ($auth_methods as $_method)
1527            {
1528                if (in_array($_method, $available_methods))
1529                {
1530                    $method = $_method;
1531                    break;
1532                }
1533            }
1534        }
1535
1536        if (!$method)
1537        {
1538            return (isset($user->lang['NO_SUPPORTED_AUTH_METHODS'])) ? $user->lang['NO_SUPPORTED_AUTH_METHODS'] : 'No supported authentication methods';
1539        }
1540
1541        $method = strtolower(str_replace('-', '_', $method));
1542        return $this->$method($username, $password);
1543    }
1544
1545    /**
1546    * SMTP EHLO/HELO
1547    *
1548    * @return mixed        Null if the authentication process is supposed to continue
1549    *                    False if already authenticated
1550    *                    Error message (string) otherwise
1551    */
1552    protected function hello($hostname)
1553    {
1554        // Try EHLO first
1555        $this->server_send("EHLO $hostname");
1556        if ($err_msg = $this->server_parse('250', __LINE__))
1557        {
1558            // a 503 response code means that we're already authenticated
1559            if ($this->numeric_response_code == 503)
1560            {
1561                return false;
1562            }
1563
1564            // If EHLO fails, we try HELO
1565            $this->server_send("HELO $hostname");
1566            if ($err_msg = $this->server_parse('250', __LINE__))
1567            {
1568                return ($this->numeric_response_code == 503) ? false : $err_msg;
1569            }
1570        }
1571
1572        foreach ($this->responses as $response)
1573        {
1574            $response = explode(' ', $response);
1575            $response_code = $response[0];
1576            unset($response[0]);
1577            $this->commands[$response_code] = implode(' ', $response);
1578        }
1579
1580        return null;
1581    }
1582
1583    /**
1584    * SMTP STARTTLS (RFC 3207)
1585    *
1586    * @return bool        Returns true if TLS was started
1587    *                    Otherwise false
1588    */
1589    protected function starttls()
1590    {
1591        global $config;
1592
1593        // allow SMTPS (what was used by phpBB 3.0) if hostname is prefixed with tls:// or ssl://
1594        if (strpos($config['smtp_host'], 'tls://') === 0 || strpos($config['smtp_host'], 'ssl://') === 0)
1595        {
1596            return true;
1597        }
1598
1599        if (!function_exists('stream_socket_enable_crypto'))
1600        {
1601            return false;
1602        }
1603
1604        if (!isset($this->commands['STARTTLS']))
1605        {
1606            return false;
1607        }
1608
1609        $this->server_send('STARTTLS');
1610
1611        if ($err_msg = $this->server_parse('220', __LINE__))
1612        {
1613            return false;
1614        }
1615
1616        $result = false;
1617        $stream_meta = stream_get_meta_data($this->socket);
1618
1619        if (socket_set_blocking($this->socket, 1))
1620        {
1621            // https://secure.php.net/manual/en/function.stream-socket-enable-crypto.php#119122
1622            $crypto = (phpbb_version_compare(PHP_VERSION, '5.6.7', '<')) ? STREAM_CRYPTO_METHOD_TLS_CLIENT : STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
1623            $result = stream_socket_enable_crypto($this->socket, true, $crypto);
1624            socket_set_blocking($this->socket, (int) $stream_meta['blocked']);
1625        }
1626
1627        return $result;
1628    }
1629
1630    /**
1631    * Pop before smtp authentication
1632    */
1633    function pop_before_smtp($hostname, $username, $password)
1634    {
1635        global $user;
1636
1637        if (!$this->socket = @fsockopen($hostname, 110, $errno, $errstr, 10))
1638        {
1639            if ($errstr)
1640            {
1641                $errstr = utf8_convert_message($errstr);
1642            }
1643
1644            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";
1645        }
1646
1647        $this->server_send("USER $username", true);
1648        if ($err_msg = $this->server_parse('+OK', __LINE__))
1649        {
1650            return $err_msg;
1651        }
1652
1653        $this->server_send("PASS $password", true);
1654        if ($err_msg = $this->server_parse('+OK', __LINE__))
1655        {
1656            return $err_msg;
1657        }
1658
1659        $this->server_send('QUIT');
1660        fclose($this->socket);
1661
1662        return false;
1663    }
1664
1665    /**
1666    * Plain authentication method
1667    */
1668    function plain($username, $password)
1669    {
1670        $this->server_send('AUTH PLAIN');
1671        if ($err_msg = $this->server_parse('334', __LINE__))
1672        {
1673            return ($this->numeric_response_code == 503) ? false : $err_msg;
1674        }
1675
1676        $base64_method_plain = base64_encode("\0" . $username . "\0" . $password);
1677        $this->server_send($base64_method_plain, true);
1678        if ($err_msg = $this->server_parse('235', __LINE__))
1679        {
1680            return $err_msg;
1681        }
1682
1683        return false;
1684    }
1685
1686    /**
1687    * Login authentication method
1688    */
1689    function login($username, $password)
1690    {
1691        $this->server_send('AUTH LOGIN');
1692        if ($err_msg = $this->server_parse('334', __LINE__))
1693        {
1694            return ($this->numeric_response_code == 503) ? false : $err_msg;
1695        }
1696
1697        $this->server_send(base64_encode($username), true);
1698        if ($err_msg = $this->server_parse('334', __LINE__))
1699        {
1700            return $err_msg;
1701        }
1702
1703        $this->server_send(base64_encode($password), true);
1704        if ($err_msg = $this->server_parse('235', __LINE__))
1705        {
1706            return $err_msg;
1707        }
1708
1709        return false;
1710    }
1711
1712    /**
1713    * cram_md5 authentication method
1714    */
1715    function cram_md5($username, $password)
1716    {
1717        $this->server_send('AUTH CRAM-MD5');
1718        if ($err_msg = $this->server_parse('334', __LINE__))
1719        {
1720            return ($this->numeric_response_code == 503) ? false : $err_msg;
1721        }
1722
1723        $md5_challenge = base64_decode($this->responses[0]);
1724        $password = (strlen($password) > 64) ? pack('H32', md5($password)) : ((strlen($password) < 64) ? str_pad($password, 64, chr(0)) : $password);
1725        $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))));
1726
1727        $base64_method_cram_md5 = base64_encode($username . ' ' . $md5_digest);
1728
1729        $this->server_send($base64_method_cram_md5, true);
1730        if ($err_msg = $this->server_parse('235', __LINE__))
1731        {
1732            return $err_msg;
1733        }
1734
1735        return false;
1736    }
1737
1738    /**
1739    * digest_md5 authentication method
1740    * A real pain in the ***
1741    */
1742    function digest_md5($username, $password)
1743    {
1744        global $config, $user;
1745
1746        $this->server_send('AUTH DIGEST-MD5');
1747        if ($err_msg = $this->server_parse('334', __LINE__))
1748        {
1749            return ($this->numeric_response_code == 503) ? false : $err_msg;
1750        }
1751
1752        $md5_challenge = base64_decode($this->responses[0]);
1753
1754        // Parse the md5 challenge - from AUTH_SASL (PEAR)
1755        $tokens = array();
1756        while (preg_match('/^([a-z-]+)=("[^"]+(?<!\\\)"|[^,]+)/i', $md5_challenge, $matches))
1757        {
1758            // Ignore these as per rfc2831
1759            if ($matches[1] == 'opaque' || $matches[1] == 'domain')
1760            {
1761                $md5_challenge = substr($md5_challenge, strlen($matches[0]) + 1);
1762                continue;
1763            }
1764
1765            // Allowed multiple "realm" and "auth-param"
1766            if (!empty($tokens[$matches[1]]) && ($matches[1] == 'realm' || $matches[1] == 'auth-param'))
1767            {
1768                if (is_array($tokens[$matches[1]]))
1769                {
1770                    $tokens[$matches[1]][] = preg_replace('/^"(.*)"$/', '\\1', $matches[2]);
1771                }
1772                else
1773                {
1774                    $tokens[$matches[1]] = array($tokens[$matches[1]], preg_replace('/^"(.*)"$/', '\\1', $matches[2]));
1775                }
1776            }
1777            else if (!empty($tokens[$matches[1]])) // Any other multiple instance = failure
1778            {
1779                $tokens = array();
1780                break;
1781            }
1782            else
1783            {
1784                $tokens[$matches[1]] = preg_replace('/^"(.*)"$/', '\\1', $matches[2]);
1785            }
1786
1787            // Remove the just parsed directive from the challenge
1788            $md5_challenge = substr($md5_challenge, strlen($matches[0]) + 1);
1789        }
1790
1791        // Realm
1792        if (empty($tokens['realm']))
1793        {
1794            $tokens['realm'] = (function_exists('php_uname')) ? php_uname('n') : $user->host;
1795        }
1796
1797        // Maxbuf
1798        if (empty($tokens['maxbuf']))
1799        {
1800            $tokens['maxbuf'] = 65536;
1801        }
1802
1803        // Required: nonce, algorithm
1804        if (empty($tokens['nonce']) || empty($tokens['algorithm']))
1805        {
1806            $tokens = array();
1807        }
1808        $md5_challenge = $tokens;
1809
1810        if (!empty($md5_challenge))
1811        {
1812            $str = '';
1813            for ($i = 0; $i < 32; $i++)
1814            {
1815                $str .= chr(mt_rand(0, 255));
1816            }
1817            $cnonce = base64_encode($str);
1818
1819            $digest_uri = 'smtp/' . $config['smtp_host'];
1820
1821            $auth_1 = sprintf('%s:%s:%s', pack('H32', md5(sprintf('%s:%s:%s', $username, $md5_challenge['realm'], $password))), $md5_challenge['nonce'], $cnonce);
1822            $auth_2 = 'AUTHENTICATE:' . $digest_uri;
1823            $response_value = md5(sprintf('%s:%s:00000001:%s:auth:%s', md5($auth_1), $md5_challenge['nonce'], $cnonce, md5($auth_2)));
1824
1825            $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']);
1826        }
1827        else
1828        {
1829            return (isset($user->lang['INVALID_DIGEST_CHALLENGE'])) ? $user->lang['INVALID_DIGEST_CHALLENGE'] : 'Invalid digest challenge';
1830        }
1831
1832        $base64_method_digest_md5 = base64_encode($input_string);
1833        $this->server_send($base64_method_digest_md5, true);
1834        if ($err_msg = $this->server_parse('334', __LINE__))
1835        {
1836            return $err_msg;
1837        }
1838
1839        $this->server_send(' ');
1840        if ($err_msg = $this->server_parse('235', __LINE__))
1841        {
1842            return $err_msg;
1843        }
1844
1845        return false;
1846    }
1847}
1848
1849/**
1850 * Encodes the given string for proper display in UTF-8 or US-ASCII.
1851 *
1852 * This version is based on iconv_mime_encode() implementation
1853 * from symfomy/polyfill-iconv
1854 * https://github.com/symfony/polyfill-iconv/blob/fd324208ec59a39ebe776e6e9ec5540ad4f40aaa/Iconv.php#L355
1855 *
1856 * @param string $str
1857 * @param string $eol Lines delimiter (optional to be backwards compatible)
1858 *
1859 * @return string
1860 */
1861function mail_encode($str, $eol = "\r\n")
1862{
1863    // Check if string contains ASCII only characters
1864    $is_ascii = strlen($str) === utf8_strlen($str);
1865
1866    $scheme = $is_ascii ? 'Q' : 'B';
1867
1868    // Define start delimiter, end delimiter
1869    // Use the Quoted-Printable encoding for ASCII strings to avoid unnecessary encoding in Base64
1870    $start = '=?' . ($is_ascii ? 'US-ASCII' : 'UTF-8') . '?' . $scheme . '?';
1871    $end = '?=';
1872
1873    // Maximum encoded-word length is 75 as per RFC 2047 section 2.
1874    // $split_length *must* be a multiple of 4, but <= 75 - strlen($start . $eol . $end)!!!
1875    $split_length = 75 - strlen($start . $eol . $end);
1876    $split_length = $split_length - $split_length % 4;
1877
1878    $line_length = strlen($start) + strlen($end);
1879    $line_offset = strlen($start) + 1;
1880    $line_data = '';
1881
1882    $is_quoted_printable = 'Q' === $scheme;
1883
1884    preg_match_all('/./us', $str, $chars);
1885    $chars = $chars[0] ?? [];
1886
1887    $str = [];
1888    foreach ($chars as $char)
1889    {
1890        $encoded_char = $is_quoted_printable
1891            ? $char = preg_replace_callback(
1892                '/[()<>@,;:\\\\".\[\]=_?\x20\x00-\x1F\x80-\xFF]/',
1893                function ($matches)
1894                {
1895                    $hex = dechex(ord($matches[0]));
1896                    $hex = strlen($hex) == 1 ? "0$hex" : $hex;
1897                    return '=' . strtoupper($hex);
1898                },
1899                $char
1900            )
1901            : base64_encode($line_data . $char);
1902
1903        if (isset($encoded_char[$split_length - $line_length]))
1904        {
1905            if (!$is_quoted_printable)
1906            {
1907                $line_data = base64_encode($line_data);
1908            }
1909            $str[] = $start . $line_data . $end;
1910            $line_length = $line_offset;
1911            $line_data = '';
1912        }
1913
1914        $line_data .= $char;
1915        $is_quoted_printable && $line_length += strlen($char);
1916    }
1917
1918    if ($line_data !== '')
1919    {
1920        if (!$is_quoted_printable)
1921        {
1922            $line_data = base64_encode($line_data);
1923        }
1924        $str[] = $start . $line_data . $end;
1925    }
1926
1927    return implode($eol . ' ', $str);
1928}
1929
1930/**
1931 * Wrapper for sending out emails with the PHP's mail function
1932 */
1933function phpbb_mail($to, $subject, $msg, $headers, $eol, &$err_msg)
1934{
1935    global $config, $phpbb_root_path, $phpEx, $phpbb_dispatcher;
1936
1937    // Convert Numeric Character References to UTF-8 chars (ie. Emojis)
1938    $subject = utf8_decode_ncr($subject);
1939    $msg = utf8_decode_ncr($msg);
1940
1941    /**
1942     * We use the EOL character for the OS here because the PHP mail function does not correctly transform line endings.
1943     * On Windows SMTP is used (SMTP is \r\n), on UNIX a command is used...
1944     * Reference: http://bugs.php.net/bug.php?id=15841
1945     */
1946    $headers = implode($eol, $headers);
1947
1948    if (!class_exists('\phpbb\error_collector'))
1949    {
1950        include($phpbb_root_path . 'includes/error_collector.' . $phpEx);
1951    }
1952
1953    $collector = new \phpbb\error_collector;
1954    $collector->install();
1955
1956    /**
1957     * On some PHP Versions mail() *may* fail if there are newlines within the subject.
1958     * Newlines are used as a delimiter for lines in mail_encode() according to RFC 2045 section 6.8.
1959     * Because PHP can't decide what is wanted we revert back to the non-RFC-compliant way of separating by one space
1960     * (Use '' as parameter to mail_encode() results in SPACE used)
1961     */
1962    $additional_parameters = $config['email_force_sender'] ? '-f' . $config['board_email'] : '';
1963
1964    /**
1965     * Modify data before sending out emails with PHP's mail function
1966     *
1967     * @event core.phpbb_mail_before
1968     * @var    string    to                        The message recipient
1969     * @var    string    subject                    The message subject
1970     * @var    string    msg                        The message text
1971     * @var string    headers                    The email headers
1972     * @var string    eol                        The endline character
1973     * @var string    additional_parameters    The additional parameters
1974     * @since 3.3.6-RC1
1975     */
1976    $vars = [
1977        'to',
1978        'subject',
1979        'msg',
1980        'headers',
1981        'eol',
1982        'additional_parameters',
1983    ];
1984    extract($phpbb_dispatcher->trigger_event('core.phpbb_mail_before', compact($vars)));
1985
1986    $result = mail($to, mail_encode($subject, ''), wordwrap(utf8_wordwrap($msg), 997, "\n", true), $headers, $additional_parameters);
1987
1988    /**
1989     * Execute code after sending out emails with PHP's mail function
1990     *
1991     * @event core.phpbb_mail_after
1992     * @var    string    to                        The message recipient
1993     * @var    string    subject                    The message subject
1994     * @var    string    msg                        The message text
1995     * @var string    headers                    The email headers
1996     * @var string    eol                        The endline character
1997     * @var string    additional_parameters    The additional parameters
1998     * @var bool    result                    True if the email was sent, false otherwise
1999     * @since 3.3.6-RC1
2000     */
2001    $vars = [
2002        'to',
2003        'subject',
2004        'msg',
2005        'headers',
2006        'eol',
2007        'additional_parameters',
2008        'result',
2009    ];
2010    extract($phpbb_dispatcher->trigger_event('core.phpbb_mail_after', compact($vars)));
2011
2012    $collector->uninstall();
2013    $err_msg = $collector->format_errors();
2014
2015    return $result;
2016}