[ Index ]

PHP Cross Reference of phpBB-3.2.11-deutsch

title

Body

[close]

/includes/ -> functions_messenger.php (source)

   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  */
  17  if (!defined('IN_PHPBB'))
  18  {
  19      exit;
  20  }
  21  
  22  /**
  23  * Messenger
  24  */
  25  class 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" . htmlspecialchars_decode($config['board_email_sig'])),
 324              'SITENAME'    => htmlspecialchars_decode($config['sitename']),
 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 = htmlspecialchars_decode($request->server('PHP_SELF'));
 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) . '</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(time())) . '@' . $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 = htmlspecialchars_decode($config['board_contact_name']);
 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          if ($break)
 586          {
 587              return true;
 588          }
 589  
 590          if (empty($this->replyto))
 591          {
 592              $this->replyto = $board_contact;
 593          }
 594  
 595          if (empty($this->from))
 596          {
 597              $this->from = $board_contact;
 598          }
 599  
 600          $encode_eol = ($config['smtp_delivery']) ? "\r\n" : PHP_EOL;
 601  
 602          // Build to, cc and bcc strings
 603          $to = $cc = $bcc = '';
 604          foreach ($this->addresses as $type => $address_ary)
 605          {
 606              if ($type == 'im')
 607              {
 608                  continue;
 609              }
 610  
 611              foreach ($address_ary as $which_ary)
 612              {
 613                  ${$type} .= ((${$type} != '') ? ', ' : '') . (($which_ary['name'] != '') ? mail_encode($which_ary['name'], $encode_eol) . ' <' . $which_ary['email'] . '>' : $which_ary['email']);
 614              }
 615          }
 616  
 617          // Build header
 618          $headers = $this->build_header($to, $cc, $bcc);
 619  
 620          // Send message ...
 621          if (!$use_queue)
 622          {
 623              $mail_to = ($to == '') ? 'undisclosed-recipients:;' : $to;
 624              $err_msg = '';
 625  
 626              if ($config['smtp_delivery'])
 627              {
 628                  $result = smtpmail($this->addresses, mail_encode($this->subject), wordwrap(utf8_wordwrap($this->msg), 997, "\n", true), $err_msg, $headers);
 629              }
 630              else
 631              {
 632                  $result = phpbb_mail($mail_to, $this->subject, $this->msg, $headers, PHP_EOL, $err_msg);
 633              }
 634  
 635              if (!$result)
 636              {
 637                  $this->error('EMAIL', $err_msg);
 638                  return false;
 639              }
 640          }
 641          else
 642          {
 643              $this->queue->put('email', array(
 644                  'to'            => $to,
 645                  'addresses'        => $this->addresses,
 646                  'subject'        => $this->subject,
 647                  'msg'            => $this->msg,
 648                  'headers'        => $headers)
 649              );
 650          }
 651  
 652          return true;
 653      }
 654  
 655      /**
 656      * Send jabber message out
 657      */
 658  	function msg_jabber()
 659      {
 660          global $config, $user, $phpbb_root_path, $phpEx;
 661  
 662          if (empty($config['jab_enable']) || empty($config['jab_host']) || empty($config['jab_username']) || empty($config['jab_password']))
 663          {
 664              return false;
 665          }
 666  
 667          if (empty($this->addresses['im']))
 668          {
 669              // Send was successful. ;)
 670              return true;
 671          }
 672  
 673          $use_queue = false;
 674          if ($config['jab_package_size'] && $this->use_queue)
 675          {
 676              if (empty($this->queue))
 677              {
 678                  $this->queue = new queue();
 679                  $this->queue->init('jabber', $config['jab_package_size']);
 680              }
 681              $use_queue = true;
 682          }
 683  
 684          $addresses = array();
 685          foreach ($this->addresses['im'] as $type => $uid_ary)
 686          {
 687              $addresses[] = $uid_ary['uid'];
 688          }
 689          $addresses = array_unique($addresses);
 690  
 691          if (!$use_queue)
 692          {
 693              include_once($phpbb_root_path . 'includes/functions_jabber.' . $phpEx);
 694              $this->jabber = new jabber($config['jab_host'], $config['jab_port'], $config['jab_username'], htmlspecialchars_decode($config['jab_password']), $config['jab_use_ssl'], $config['jab_verify_peer'], $config['jab_verify_peer_name'], $config['jab_allow_self_signed']);
 695  
 696              if (!$this->jabber->connect())
 697              {
 698                  $this->error('JABBER', $user->lang['ERR_JAB_CONNECT'] . '<br />' . $this->jabber->get_log());
 699                  return false;
 700              }
 701  
 702              if (!$this->jabber->login())
 703              {
 704                  $this->error('JABBER', $user->lang['ERR_JAB_AUTH'] . '<br />' . $this->jabber->get_log());
 705                  return false;
 706              }
 707  
 708              foreach ($addresses as $address)
 709              {
 710                  $this->jabber->send_message($address, $this->msg, $this->subject);
 711              }
 712  
 713              $this->jabber->disconnect();
 714          }
 715          else
 716          {
 717              $this->queue->put('jabber', array(
 718                  'addresses'        => $addresses,
 719                  'subject'        => $this->subject,
 720                  'msg'            => $this->msg)
 721              );
 722          }
 723          unset($addresses);
 724          return true;
 725      }
 726  
 727      /**
 728      * Setup template engine
 729      */
 730  	protected function setup_template()
 731      {
 732          global $phpbb_container, $phpbb_dispatcher;
 733  
 734          if ($this->template instanceof \phpbb\template\template)
 735          {
 736              return;
 737          }
 738  
 739          $template_environment = new \phpbb\template\twig\environment(
 740              $phpbb_container->get('config'),
 741              $phpbb_container->get('filesystem'),
 742              $phpbb_container->get('path_helper'),
 743              $phpbb_container->getParameter('core.template.cache_path'),
 744              $phpbb_container->get('ext.manager'),
 745              new \phpbb\template\twig\loader(
 746                  $phpbb_container->get('filesystem')
 747              ),
 748              $phpbb_dispatcher,
 749              array()
 750          );
 751          $template_environment->setLexer($phpbb_container->get('template.twig.lexer'));
 752  
 753          $this->template = new \phpbb\template\twig\twig(
 754              $phpbb_container->get('path_helper'),
 755              $phpbb_container->get('config'),
 756              new \phpbb\template\context(),
 757              $template_environment,
 758              $phpbb_container->getParameter('core.template.cache_path'),
 759              $phpbb_container->get('user'),
 760              $phpbb_container->get('template.twig.extensions.collection'),
 761              $phpbb_container->get('ext.manager')
 762          );
 763      }
 764  
 765      /**
 766      * Set template paths to load
 767      */
 768  	protected function set_template_paths($path_name, $paths)
 769      {
 770          $this->setup_template();
 771  
 772          $this->template->set_custom_style($path_name, $paths);
 773      }
 774  }
 775  
 776  /**
 777  * handling email and jabber queue
 778  */
 779  class queue
 780  {
 781      var $data = array();
 782      var $queue_data = array();
 783      var $package_size = 0;
 784      var $cache_file = '';
 785      var $eol = "\n";
 786  
 787      /**
 788       * @var \phpbb\filesystem\filesystem_interface
 789       */
 790      protected $filesystem;
 791  
 792      /**
 793      * constructor
 794      */
 795  	function __construct()
 796      {
 797          global $phpEx, $phpbb_root_path, $phpbb_filesystem, $phpbb_container;
 798  
 799          $this->data = array();
 800          $this->cache_file = $phpbb_container->getParameter('core.cache_dir') . "queue.$phpEx";
 801          $this->filesystem = $phpbb_filesystem;
 802      }
 803  
 804      /**
 805      * Init a queue object
 806      */
 807  	function init($object, $package_size)
 808      {
 809          $this->data[$object] = array();
 810          $this->data[$object]['package_size'] = $package_size;
 811          $this->data[$object]['data'] = array();
 812      }
 813  
 814      /**
 815      * Put object in queue
 816      */
 817  	function put($object, $scope)
 818      {
 819          $this->data[$object]['data'][] = $scope;
 820      }
 821  
 822      /**
 823      * Process queue
 824      * Using lock file
 825      */
 826  	function process()
 827      {
 828          global $config, $phpEx, $phpbb_root_path, $user, $phpbb_dispatcher;
 829  
 830          $lock = new \phpbb\lock\flock($this->cache_file);
 831          $lock->acquire();
 832  
 833          // avoid races, check file existence once
 834          $have_cache_file = file_exists($this->cache_file);
 835          if (!$have_cache_file || $config['last_queue_run'] > time() - $config['queue_interval'])
 836          {
 837              if (!$have_cache_file)
 838              {
 839                  $config->set('last_queue_run', time(), false);
 840              }
 841  
 842              $lock->release();
 843              return;
 844          }
 845  
 846          $config->set('last_queue_run', time(), false);
 847  
 848          include($this->cache_file);
 849  
 850          foreach ($this->queue_data as $object => $data_ary)
 851          {
 852              @set_time_limit(0);
 853  
 854              if (!isset($data_ary['package_size']))
 855              {
 856                  $data_ary['package_size'] = 0;
 857              }
 858  
 859              $package_size = $data_ary['package_size'];
 860              $num_items = (!$package_size || count($data_ary['data']) < $package_size) ? count($data_ary['data']) : $package_size;
 861  
 862              /*
 863              * This code is commented out because it causes problems on some web hosts.
 864              * The core problem is rather restrictive email sending limits.
 865              * This code is nly useful if you have no such restrictions from the
 866              * web host and the package size setting is wrong.
 867  
 868              // If the amount of emails to be sent is way more than package_size than we need to increase it to prevent backlogs...
 869              if (count($data_ary['data']) > $package_size * 2.5)
 870              {
 871                  $num_items = count($data_ary['data']);
 872              }
 873              */
 874  
 875              switch ($object)
 876              {
 877                  case 'email':
 878                      // Delete the email queued objects if mailing is disabled
 879                      if (!$config['email_enable'])
 880                      {
 881                          unset($this->queue_data['email']);
 882                          continue 2;
 883                      }
 884                  break;
 885  
 886                  case 'jabber':
 887                      if (!$config['jab_enable'])
 888                      {
 889                          unset($this->queue_data['jabber']);
 890                          continue 2;
 891                      }
 892  
 893                      include_once($phpbb_root_path . 'includes/functions_jabber.' . $phpEx);
 894                      $this->jabber = new jabber($config['jab_host'], $config['jab_port'], $config['jab_username'], htmlspecialchars_decode($config['jab_password']), $config['jab_use_ssl'], $config['jab_verify_peer'], $config['jab_verify_peer_name'], $config['jab_allow_self_signed']);
 895  
 896                      if (!$this->jabber->connect())
 897                      {
 898                          $messenger = new messenger();
 899                          $messenger->error('JABBER', $user->lang['ERR_JAB_CONNECT']);
 900                          continue 2;
 901                      }
 902  
 903                      if (!$this->jabber->login())
 904                      {
 905                          $messenger = new messenger();
 906                          $messenger->error('JABBER', $user->lang['ERR_JAB_AUTH']);
 907                          continue 2;
 908                      }
 909  
 910                  break;
 911  
 912                  default:
 913                      $lock->release();
 914                      return;
 915              }
 916  
 917              for ($i = 0; $i < $num_items; $i++)
 918              {
 919                  // Make variables available...
 920                  extract(array_shift($this->queue_data[$object]['data']));
 921  
 922                  switch ($object)
 923                  {
 924                      case 'email':
 925                          $break = false;
 926                          /**
 927                          * Event to send message via external transport
 928                          *
 929                          * @event core.notification_message_process
 930                          * @var    bool    break        Flag indicating if the function return after hook
 931                          * @var    array    addresses     The message recipients
 932                          * @var    string    subject        The message subject
 933                          * @var    string    msg            The message text
 934                          * @since 3.2.4-RC1
 935                          */
 936                          $vars = array(
 937                              'break',
 938                              'addresses',
 939                              'subject',
 940                              'msg',
 941                          );
 942                          extract($phpbb_dispatcher->trigger_event('core.notification_message_process', compact($vars)));
 943  
 944                          if (!$break)
 945                          {
 946                              $err_msg = '';
 947                              $to = (!$to) ? 'undisclosed-recipients:;' : $to;
 948  
 949                              if ($config['smtp_delivery'])
 950                              {
 951                                  $result = smtpmail($addresses, mail_encode($subject), wordwrap(utf8_wordwrap($msg), 997, "\n", true), $err_msg, $headers);
 952                              }
 953                              else
 954                              {
 955                                  $result = phpbb_mail($to, $subject, $msg, $headers, PHP_EOL, $err_msg);
 956                              }
 957  
 958                              if (!$result)
 959                              {
 960                                  $messenger = new messenger();
 961                                  $messenger->error('EMAIL', $err_msg);
 962                                  continue 2;
 963                              }
 964                          }
 965                      break;
 966  
 967                      case 'jabber':
 968                          foreach ($addresses as $address)
 969                          {
 970                              if ($this->jabber->send_message($address, $msg, $subject) === false)
 971                              {
 972                                  $messenger = new messenger();
 973                                  $messenger->error('JABBER', $this->jabber->get_log());
 974                                  continue 3;
 975                              }
 976                          }
 977                      break;
 978                  }
 979              }
 980  
 981              // No more data for this object? Unset it
 982              if (!count($this->queue_data[$object]['data']))
 983              {
 984                  unset($this->queue_data[$object]);
 985              }
 986  
 987              // Post-object processing
 988              switch ($object)
 989              {
 990                  case 'jabber':
 991                      // Hang about a couple of secs to ensure the messages are
 992                      // handled, then disconnect
 993                      $this->jabber->disconnect();
 994                  break;
 995              }
 996          }
 997  
 998          if (!count($this->queue_data))
 999          {
1000              @unlink($this->cache_file);
1001          }
1002          else
1003          {
1004              if ($fp = @fopen($this->cache_file, 'wb'))
1005              {
1006                  fwrite($fp, "<?php\nif (!defined('IN_PHPBB')) exit;\n\$this->queue_data = unserialize(" . var_export(serialize($this->queue_data), true) . ");\n\n?>");
1007                  fclose($fp);
1008  
1009                  if (function_exists('opcache_invalidate'))
1010                  {
1011                      @opcache_invalidate($this->cache_file);
1012                  }
1013  
1014                  try
1015                  {
1016                      $this->filesystem->phpbb_chmod($this->cache_file, \phpbb\filesystem\filesystem_interface::CHMOD_READ | \phpbb\filesystem\filesystem_interface::CHMOD_WRITE);
1017                  }
1018                  catch (\phpbb\filesystem\exception\filesystem_exception $e)
1019                  {
1020                      // Do nothing
1021                  }
1022              }
1023          }
1024  
1025          $lock->release();
1026      }
1027  
1028      /**
1029      * Save queue
1030      */
1031  	function save()
1032      {
1033          if (!count($this->data))
1034          {
1035              return;
1036          }
1037  
1038          $lock = new \phpbb\lock\flock($this->cache_file);
1039          $lock->acquire();
1040  
1041          if (file_exists($this->cache_file))
1042          {
1043              include($this->cache_file);
1044  
1045              foreach ($this->queue_data as $object => $data_ary)
1046              {
1047                  if (isset($this->data[$object]) && count($this->data[$object]))
1048                  {
1049                      $this->data[$object]['data'] = array_merge($data_ary['data'], $this->data[$object]['data']);
1050                  }
1051                  else
1052                  {
1053                      $this->data[$object]['data'] = $data_ary['data'];
1054                  }
1055              }
1056          }
1057  
1058          if ($fp = @fopen($this->cache_file, 'w'))
1059          {
1060              fwrite($fp, "<?php\nif (!defined('IN_PHPBB')) exit;\n\$this->queue_data = unserialize(" . var_export(serialize($this->data), true) . ");\n\n?>");
1061              fclose($fp);
1062  
1063              if (function_exists('opcache_invalidate'))
1064              {
1065                  @opcache_invalidate($this->cache_file);
1066              }
1067  
1068              try
1069              {
1070                  $this->filesystem->phpbb_chmod($this->cache_file, \phpbb\filesystem\filesystem_interface::CHMOD_READ | \phpbb\filesystem\filesystem_interface::CHMOD_WRITE);
1071              }
1072              catch (\phpbb\filesystem\exception\filesystem_exception $e)
1073              {
1074                  // Do nothing
1075              }
1076  
1077              $this->data = array();
1078          }
1079  
1080          $lock->release();
1081      }
1082  }
1083  
1084  /**
1085  * Replacement or substitute for PHP's mail command
1086  */
1087  function smtpmail($addresses, $subject, $message, &$err_msg, $headers = false)
1088  {
1089      global $config, $user;
1090  
1091      // Fix any bare linefeeds in the message to make it RFC821 Compliant.
1092      $message = preg_replace("#(?<!\r)\n#si", "\r\n", $message);
1093  
1094      if ($headers !== false)
1095      {
1096          if (!is_array($headers))
1097          {
1098              // Make sure there are no bare linefeeds in the headers
1099              $headers = preg_replace('#(?<!\r)\n#si', "\n", $headers);
1100              $headers = explode("\n", $headers);
1101          }
1102  
1103          // Ok this is rather confusing all things considered,
1104          // but we have to grab bcc and cc headers and treat them differently
1105          // Something we really didn't take into consideration originally
1106          $headers_used = array();
1107  
1108          foreach ($headers as $header)
1109          {
1110              if (strpos(strtolower($header), 'cc:') === 0 || strpos(strtolower($header), 'bcc:') === 0)
1111              {
1112                  continue;
1113              }
1114              $headers_used[] = trim($header);
1115          }
1116  
1117          $headers = chop(implode("\r\n", $headers_used));
1118      }
1119  
1120      if (trim($subject) == '')
1121      {
1122          $err_msg = (isset($user->lang['NO_EMAIL_SUBJECT'])) ? $user->lang['NO_EMAIL_SUBJECT'] : 'No email subject specified';
1123          return false;
1124      }
1125  
1126      if (trim($message) == '')
1127      {
1128          $err_msg = (isset($user->lang['NO_EMAIL_MESSAGE'])) ? $user->lang['NO_EMAIL_MESSAGE'] : 'Email message was blank';
1129          return false;
1130      }
1131  
1132      $mail_rcpt = $mail_to = $mail_cc = array();
1133  
1134      // Build correct addresses for RCPT TO command and the client side display (TO, CC)
1135      if (isset($addresses['to']) && count($addresses['to']))
1136      {
1137          foreach ($addresses['to'] as $which_ary)
1138          {
1139              $mail_to[] = ($which_ary['name'] != '') ? mail_encode(trim($which_ary['name'])) . ' <' . trim($which_ary['email']) . '>' : '<' . trim($which_ary['email']) . '>';
1140              $mail_rcpt['to'][] = '<' . trim($which_ary['email']) . '>';
1141          }
1142      }
1143  
1144      if (isset($addresses['bcc']) && count($addresses['bcc']))
1145      {
1146          foreach ($addresses['bcc'] as $which_ary)
1147          {
1148              $mail_rcpt['bcc'][] = '<' . trim($which_ary['email']) . '>';
1149          }
1150      }
1151  
1152      if (isset($addresses['cc']) && count($addresses['cc']))
1153      {
1154          foreach ($addresses['cc'] as $which_ary)
1155          {
1156              $mail_cc[] = ($which_ary['name'] != '') ? mail_encode(trim($which_ary['name'])) . ' <' . trim($which_ary['email']) . '>' : '<' . trim($which_ary['email']) . '>';
1157              $mail_rcpt['cc'][] = '<' . trim($which_ary['email']) . '>';
1158          }
1159      }
1160  
1161      $smtp = new smtp_class();
1162  
1163      $errno = 0;
1164      $errstr = '';
1165  
1166      $smtp->add_backtrace('Connecting to ' . $config['smtp_host'] . ':' . $config['smtp_port']);
1167  
1168      // Ok we have error checked as much as we can to this point let's get on it already.
1169      if (!class_exists('\phpbb\error_collector'))
1170      {
1171          global $phpbb_root_path, $phpEx;
1172          include($phpbb_root_path . 'includes/error_collector.' . $phpEx);
1173      }
1174      $collector = new \phpbb\error_collector;
1175      $collector->install();
1176  
1177      $options = array();
1178      $verify_peer = (bool) $config['smtp_verify_peer'];
1179      $verify_peer_name = (bool) $config['smtp_verify_peer_name'];
1180      $allow_self_signed = (bool) $config['smtp_allow_self_signed'];
1181      $remote_socket = $config['smtp_host'] . ':' . $config['smtp_port'];
1182  
1183      // Set ssl context options, see http://php.net/manual/en/context.ssl.php
1184      $options['ssl'] = array('verify_peer' => $verify_peer, 'verify_peer_name' => $verify_peer_name, 'allow_self_signed' => $allow_self_signed);
1185      $socket_context = stream_context_create($options);
1186  
1187      $smtp->socket = @stream_socket_client($remote_socket, $errno, $errstr, 20, STREAM_CLIENT_CONNECT, $socket_context);
1188      $collector->uninstall();
1189      $error_contents = $collector->format_errors();
1190  
1191      if (!$smtp->socket)
1192      {
1193          if ($errstr)
1194          {
1195              $errstr = utf8_convert_message($errstr);
1196          }
1197  
1198          $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";
1199          $err_msg .= ($error_contents) ? '<br /><br />' . htmlspecialchars($error_contents) : '';
1200          return false;
1201      }
1202  
1203      // Wait for reply
1204      if ($err_msg = $smtp->server_parse('220', __LINE__))
1205      {
1206          $smtp->close_session($err_msg);
1207          return false;
1208      }
1209  
1210      // Let me in. This function handles the complete authentication process
1211      if ($err_msg = $smtp->log_into_server($config['smtp_host'], $config['smtp_username'], htmlspecialchars_decode($config['smtp_password']), $config['smtp_auth_method']))
1212      {
1213          $smtp->close_session($err_msg);
1214          return false;
1215      }
1216  
1217      // From this point onward most server response codes should be 250
1218      // Specify who the mail is from....
1219      $smtp->server_send('MAIL FROM:<' . $config['board_email'] . '>');
1220      if ($err_msg = $smtp->server_parse('250', __LINE__))
1221      {
1222          $smtp->close_session($err_msg);
1223          return false;
1224      }
1225  
1226      // Specify each user to send to and build to header.
1227      $to_header = implode(', ', $mail_to);
1228      $cc_header = implode(', ', $mail_cc);
1229  
1230      // Now tell the MTA to send the Message to the following people... [TO, BCC, CC]
1231      $rcpt = false;
1232      foreach ($mail_rcpt as $type => $mail_to_addresses)
1233      {
1234          foreach ($mail_to_addresses as $mail_to_address)
1235          {
1236              // Add an additional bit of error checking to the To field.
1237              if (preg_match('#[^ ]+\@[^ ]+#', $mail_to_address))
1238              {
1239                  $smtp->server_send("RCPT TO:$mail_to_address");
1240                  if ($err_msg = $smtp->server_parse('250', __LINE__))
1241                  {
1242                      // We continue... if users are not resolved we do not care
1243                      if ($smtp->numeric_response_code != 550)
1244                      {
1245                          $smtp->close_session($err_msg);
1246                          return false;
1247                      }
1248                  }
1249                  else
1250                  {
1251                      $rcpt = true;
1252                  }
1253              }
1254          }
1255      }
1256  
1257      // 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.
1258      if (!$rcpt)
1259      {
1260          $user->session_begin();
1261          $err_msg .= '<br /><br />';
1262          $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?';
1263          $smtp->close_session($err_msg);
1264          return false;
1265      }
1266  
1267      // Ok now we tell the server we are ready to start sending data
1268      $smtp->server_send('DATA');
1269  
1270      // This is the last response code we look for until the end of the message.
1271      if ($err_msg = $smtp->server_parse('354', __LINE__))
1272      {
1273          $smtp->close_session($err_msg);
1274          return false;
1275      }
1276  
1277      // Send the Subject Line...
1278      $smtp->server_send("Subject: $subject");
1279  
1280      // Now the To Header.
1281      $to_header = ($to_header == '') ? 'undisclosed-recipients:;' : $to_header;
1282      $smtp->server_send("To: $to_header");
1283  
1284      // Now the CC Header.
1285      if ($cc_header != '')
1286      {
1287          $smtp->server_send("CC: $cc_header");
1288      }
1289  
1290      // Now any custom headers....
1291      if ($headers !== false)
1292      {
1293          $smtp->server_send("$headers\r\n");
1294      }
1295  
1296      // Ok now we are ready for the message...
1297      $smtp->server_send($message);
1298  
1299      // Ok the all the ingredients are mixed in let's cook this puppy...
1300      $smtp->server_send('.');
1301      if ($err_msg = $smtp->server_parse('250', __LINE__))
1302      {
1303          $smtp->close_session($err_msg);
1304          return false;
1305      }
1306  
1307      // Now tell the server we are done and close the socket...
1308      $smtp->server_send('QUIT');
1309      $smtp->close_session($err_msg);
1310  
1311      return true;
1312  }
1313  
1314  /**
1315  * SMTP Class
1316  * Auth Mechanisms originally taken from the AUTH Modules found within the PHP Extension and Application Repository (PEAR)
1317  * See docs/AUTHORS for more details
1318  */
1319  class smtp_class
1320  {
1321      var $server_response = '';
1322      var $socket = 0;
1323      protected $socket_tls = false;
1324      var $responses = array();
1325      var $commands = array();
1326      var $numeric_response_code = 0;
1327  
1328      var $backtrace = false;
1329      var $backtrace_log = array();
1330  
1331  	function __construct()
1332      {
1333          // Always create a backtrace for admins to identify SMTP problems
1334          $this->backtrace = true;
1335          $this->backtrace_log = array();
1336      }
1337  
1338      /**
1339      * Add backtrace message for debugging
1340      */
1341  	function add_backtrace($message)
1342      {
1343          if ($this->backtrace)
1344          {
1345              $this->backtrace_log[] = utf8_htmlspecialchars($message);
1346          }
1347      }
1348  
1349      /**
1350      * Send command to smtp server
1351      */
1352  	function server_send($command, $private_info = false)
1353      {
1354          fputs($this->socket, $command . "\r\n");
1355  
1356          (!$private_info) ? $this->add_backtrace("# $command") : $this->add_backtrace('# Omitting sensitive information');
1357  
1358          // We could put additional code here
1359      }
1360  
1361      /**
1362      * We use the line to give the support people an indication at which command the error occurred
1363      */
1364  	function server_parse($response, $line)
1365      {
1366          global $user;
1367  
1368          $this->server_response = '';
1369          $this->responses = array();
1370          $this->numeric_response_code = 0;
1371  
1372          while (substr($this->server_response, 3, 1) != ' ')
1373          {
1374              if (!($this->server_response = fgets($this->socket, 256)))
1375              {
1376                  return (isset($user->lang['NO_EMAIL_RESPONSE_CODE'])) ? $user->lang['NO_EMAIL_RESPONSE_CODE'] : 'Could not get mail server response codes';
1377              }
1378              $this->responses[] = substr(rtrim($this->server_response), 4);
1379              $this->numeric_response_code = (int) substr($this->server_response, 0, 3);
1380  
1381              $this->add_backtrace("LINE: $line <- {$this->server_response}");
1382          }
1383  
1384          if (!(substr($this->server_response, 0, 3) == $response))
1385          {
1386              $this->numeric_response_code = (int) substr($this->server_response, 0, 3);
1387              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";
1388          }
1389  
1390          return 0;
1391      }
1392  
1393      /**
1394      * Close session
1395      */
1396  	function close_session(&$err_msg)
1397      {
1398          fclose($this->socket);
1399  
1400          if ($this->backtrace)
1401          {
1402              $message = '<h1>Backtrace</h1><p>' . implode('<br />', $this->backtrace_log) . '</p>';
1403              $err_msg .= $message;
1404          }
1405      }
1406  
1407      /**
1408      * Log into server and get possible auth codes if neccessary
1409      */
1410  	function log_into_server($hostname, $username, $password, $default_auth_method)
1411      {
1412          global $user;
1413  
1414          // Here we try to determine the *real* hostname (reverse DNS entry preferrably)
1415          $local_host = $user->host;
1416  
1417          if (function_exists('php_uname'))
1418          {
1419              $local_host = php_uname('n');
1420  
1421              // Able to resolve name to IP
1422              if (($addr = @gethostbyname($local_host)) !== $local_host)
1423              {
1424                  // Able to resolve IP back to name
1425                  if (($name = @gethostbyaddr($addr)) !== $addr)
1426                  {
1427                      $local_host = $name;
1428                  }
1429              }
1430          }
1431  
1432          // If we are authenticating through pop-before-smtp, we
1433          // have to login ones before we get authenticated
1434          // NOTE: on some configurations the time between an update of the auth database takes so
1435          // long that the first email send does not work. This is not a biggie on a live board (only
1436          // the install mail will most likely fail) - but on a dynamic ip connection this might produce
1437          // severe problems and is not fixable!
1438          if ($default_auth_method == 'POP-BEFORE-SMTP' && $username && $password)
1439          {
1440              global $config;
1441  
1442              $errno = 0;
1443              $errstr = '';
1444  
1445              $this->server_send("QUIT");
1446              fclose($this->socket);
1447  
1448              $this->pop_before_smtp($hostname, $username, $password);
1449              $username = $password = $default_auth_method = '';
1450  
1451              // We need to close the previous session, else the server is not
1452              // able to get our ip for matching...
1453              if (!$this->socket = @fsockopen($config['smtp_host'], $config['smtp_port'], $errno, $errstr, 10))
1454              {
1455                  if ($errstr)
1456                  {
1457                      $errstr = utf8_convert_message($errstr);
1458                  }
1459  
1460                  $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";
1461                  return $err_msg;
1462              }
1463  
1464              // Wait for reply
1465              if ($err_msg = $this->server_parse('220', __LINE__))
1466              {
1467                  $this->close_session($err_msg);
1468                  return $err_msg;
1469              }
1470          }
1471  
1472          $hello_result = $this->hello($local_host);
1473          if (!is_null($hello_result))
1474          {
1475              return $hello_result;
1476          }
1477  
1478          // SMTP STARTTLS (RFC 3207)
1479          if (!$this->socket_tls)
1480          {
1481              $this->socket_tls = $this->starttls();
1482  
1483              if ($this->socket_tls)
1484              {
1485                  // Switched to TLS
1486                  // RFC 3207: "The client MUST discard any knowledge obtained from the server, [...]"
1487                  // So say hello again
1488                  $hello_result = $this->hello($local_host);
1489  
1490                  if (!is_null($hello_result))
1491                  {
1492                      return $hello_result;
1493                  }
1494              }
1495          }
1496  
1497          // If we are not authenticated yet, something might be wrong if no username and passwd passed
1498          if (!$username || !$password)
1499          {
1500              return false;
1501          }
1502  
1503          if (!isset($this->commands['AUTH']))
1504          {
1505              return (isset($user->lang['SMTP_NO_AUTH_SUPPORT'])) ? $user->lang['SMTP_NO_AUTH_SUPPORT'] : 'SMTP server does not support authentication';
1506          }
1507  
1508          // Get best authentication method
1509          $available_methods = explode(' ', $this->commands['AUTH']);
1510  
1511          // Define the auth ordering if the default auth method was not found
1512          $auth_methods = array('PLAIN', 'LOGIN', 'CRAM-MD5', 'DIGEST-MD5');
1513          $method = '';
1514  
1515          if (in_array($default_auth_method, $available_methods))
1516          {
1517              $method = $default_auth_method;
1518          }
1519          else
1520          {
1521              foreach ($auth_methods as $_method)
1522              {
1523                  if (in_array($_method, $available_methods))
1524                  {
1525                      $method = $_method;
1526                      break;
1527                  }
1528              }
1529          }
1530  
1531          if (!$method)
1532          {
1533              return (isset($user->lang['NO_SUPPORTED_AUTH_METHODS'])) ? $user->lang['NO_SUPPORTED_AUTH_METHODS'] : 'No supported authentication methods';
1534          }
1535  
1536          $method = strtolower(str_replace('-', '_', $method));
1537          return $this->$method($username, $password);
1538      }
1539  
1540      /**
1541      * SMTP EHLO/HELO
1542      *
1543      * @return mixed        Null if the authentication process is supposed to continue
1544      *                    False if already authenticated
1545      *                    Error message (string) otherwise
1546      */
1547  	protected function hello($hostname)
1548      {
1549          // Try EHLO first
1550          $this->server_send("EHLO $hostname");
1551          if ($err_msg = $this->server_parse('250', __LINE__))
1552          {
1553              // a 503 response code means that we're already authenticated
1554              if ($this->numeric_response_code == 503)
1555              {
1556                  return false;
1557              }
1558  
1559              // If EHLO fails, we try HELO
1560              $this->server_send("HELO $hostname");
1561              if ($err_msg = $this->server_parse('250', __LINE__))
1562              {
1563                  return ($this->numeric_response_code == 503) ? false : $err_msg;
1564              }
1565          }
1566  
1567          foreach ($this->responses as $response)
1568          {
1569              $response = explode(' ', $response);
1570              $response_code = $response[0];
1571              unset($response[0]);
1572              $this->commands[$response_code] = implode(' ', $response);
1573          }
1574      }
1575  
1576      /**
1577      * SMTP STARTTLS (RFC 3207)
1578      *
1579      * @return bool        Returns true if TLS was started
1580      *                    Otherwise false
1581      */
1582  	protected function starttls()
1583      {
1584          global $config;
1585  
1586          // allow SMTPS (what was used by phpBB 3.0) if hostname is prefixed with tls:// or ssl://
1587          if (strpos($config['smtp_host'], 'tls://') === 0 || strpos($config['smtp_host'], 'ssl://') === 0)
1588          {
1589              return true;
1590          }
1591  
1592          if (!function_exists('stream_socket_enable_crypto'))
1593          {
1594              return false;
1595          }
1596  
1597          if (!isset($this->commands['STARTTLS']))
1598          {
1599              return false;
1600          }
1601  
1602          $this->server_send('STARTTLS');
1603  
1604          if ($err_msg = $this->server_parse('220', __LINE__))
1605          {
1606              return false;
1607          }
1608  
1609          $result = false;
1610          $stream_meta = stream_get_meta_data($this->socket);
1611  
1612          if (socket_set_blocking($this->socket, 1))
1613          {
1614              // https://secure.php.net/manual/en/function.stream-socket-enable-crypto.php#119122
1615              $crypto = (phpbb_version_compare(PHP_VERSION, '5.6.7', '<')) ? STREAM_CRYPTO_METHOD_TLS_CLIENT : STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
1616              $result = stream_socket_enable_crypto($this->socket, true, $crypto);
1617              socket_set_blocking($this->socket, (int) $stream_meta['blocked']);
1618          }
1619  
1620          return $result;
1621      }
1622  
1623      /**
1624      * Pop before smtp authentication
1625      */
1626  	function pop_before_smtp($hostname, $username, $password)
1627      {
1628          global $user;
1629  
1630          if (!$this->socket = @fsockopen($hostname, 110, $errno, $errstr, 10))
1631          {
1632              if ($errstr)
1633              {
1634                  $errstr = utf8_convert_message($errstr);
1635              }
1636  
1637              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";
1638          }
1639  
1640          $this->server_send("USER $username", true);
1641          if ($err_msg = $this->server_parse('+OK', __LINE__))
1642          {
1643              return $err_msg;
1644          }
1645  
1646          $this->server_send("PASS $password", true);
1647          if ($err_msg = $this->server_parse('+OK', __LINE__))
1648          {
1649              return $err_msg;
1650          }
1651  
1652          $this->server_send('QUIT');
1653          fclose($this->socket);
1654  
1655          return false;
1656      }
1657  
1658      /**
1659      * Plain authentication method
1660      */
1661  	function plain($username, $password)
1662      {
1663          $this->server_send('AUTH PLAIN');
1664          if ($err_msg = $this->server_parse('334', __LINE__))
1665          {
1666              return ($this->numeric_response_code == 503) ? false : $err_msg;
1667          }
1668  
1669          $base64_method_plain = base64_encode("\0" . $username . "\0" . $password);
1670          $this->server_send($base64_method_plain, true);
1671          if ($err_msg = $this->server_parse('235', __LINE__))
1672          {
1673              return $err_msg;
1674          }
1675  
1676          return false;
1677      }
1678  
1679      /**
1680      * Login authentication method
1681      */
1682  	function login($username, $password)
1683      {
1684          $this->server_send('AUTH LOGIN');
1685          if ($err_msg = $this->server_parse('334', __LINE__))
1686          {
1687              return ($this->numeric_response_code == 503) ? false : $err_msg;
1688          }
1689  
1690          $this->server_send(base64_encode($username), true);
1691          if ($err_msg = $this->server_parse('334', __LINE__))
1692          {
1693              return $err_msg;
1694          }
1695  
1696          $this->server_send(base64_encode($password), true);
1697          if ($err_msg = $this->server_parse('235', __LINE__))
1698          {
1699              return $err_msg;
1700          }
1701  
1702          return false;
1703      }
1704  
1705      /**
1706      * cram_md5 authentication method
1707      */
1708  	function cram_md5($username, $password)
1709      {
1710          $this->server_send('AUTH CRAM-MD5');
1711          if ($err_msg = $this->server_parse('334', __LINE__))
1712          {
1713              return ($this->numeric_response_code == 503) ? false : $err_msg;
1714          }
1715  
1716          $md5_challenge = base64_decode($this->responses[0]);
1717          $password = (strlen($password) > 64) ? pack('H32', md5($password)) : ((strlen($password) < 64) ? str_pad($password, 64, chr(0)) : $password);
1718          $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))));
1719  
1720          $base64_method_cram_md5 = base64_encode($username . ' ' . $md5_digest);
1721  
1722          $this->server_send($base64_method_cram_md5, true);
1723          if ($err_msg = $this->server_parse('235', __LINE__))
1724          {
1725              return $err_msg;
1726          }
1727  
1728          return false;
1729      }
1730  
1731      /**
1732      * digest_md5 authentication method
1733      * A real pain in the ***
1734      */
1735  	function digest_md5($username, $password)
1736      {
1737          global $config, $user;
1738  
1739          $this->server_send('AUTH DIGEST-MD5');
1740          if ($err_msg = $this->server_parse('334', __LINE__))
1741          {
1742              return ($this->numeric_response_code == 503) ? false : $err_msg;
1743          }
1744  
1745          $md5_challenge = base64_decode($this->responses[0]);
1746  
1747          // Parse the md5 challenge - from AUTH_SASL (PEAR)
1748          $tokens = array();
1749          while (preg_match('/^([a-z-]+)=("[^"]+(?<!\\\)"|[^,]+)/i', $md5_challenge, $matches))
1750          {
1751              // Ignore these as per rfc2831
1752              if ($matches[1] == 'opaque' || $matches[1] == 'domain')
1753              {
1754                  $md5_challenge = substr($md5_challenge, strlen($matches[0]) + 1);
1755                  continue;
1756              }
1757  
1758              // Allowed multiple "realm" and "auth-param"
1759              if (!empty($tokens[$matches[1]]) && ($matches[1] == 'realm' || $matches[1] == 'auth-param'))
1760              {
1761                  if (is_array($tokens[$matches[1]]))
1762                  {
1763                      $tokens[$matches[1]][] = preg_replace('/^"(.*)"$/', '\\1', $matches[2]);
1764                  }
1765                  else
1766                  {
1767                      $tokens[$matches[1]] = array($tokens[$matches[1]], preg_replace('/^"(.*)"$/', '\\1', $matches[2]));
1768                  }
1769              }
1770              else if (!empty($tokens[$matches[1]])) // Any other multiple instance = failure
1771              {
1772                  $tokens = array();
1773                  break;
1774              }
1775              else
1776              {
1777                  $tokens[$matches[1]] = preg_replace('/^"(.*)"$/', '\\1', $matches[2]);
1778              }
1779  
1780              // Remove the just parsed directive from the challenge
1781              $md5_challenge = substr($md5_challenge, strlen($matches[0]) + 1);
1782          }
1783  
1784          // Realm
1785          if (empty($tokens['realm']))
1786          {
1787              $tokens['realm'] = (function_exists('php_uname')) ? php_uname('n') : $user->host;
1788          }
1789  
1790          // Maxbuf
1791          if (empty($tokens['maxbuf']))
1792          {
1793              $tokens['maxbuf'] = 65536;
1794          }
1795  
1796          // Required: nonce, algorithm
1797          if (empty($tokens['nonce']) || empty($tokens['algorithm']))
1798          {
1799              $tokens = array();
1800          }
1801          $md5_challenge = $tokens;
1802  
1803          if (!empty($md5_challenge))
1804          {
1805              $str = '';
1806              for ($i = 0; $i < 32; $i++)
1807              {
1808                  $str .= chr(mt_rand(0, 255));
1809              }
1810              $cnonce = base64_encode($str);
1811  
1812              $digest_uri = 'smtp/' . $config['smtp_host'];
1813  
1814              $auth_1 = sprintf('%s:%s:%s', pack('H32', md5(sprintf('%s:%s:%s', $username, $md5_challenge['realm'], $password))), $md5_challenge['nonce'], $cnonce);
1815              $auth_2 = 'AUTHENTICATE:' . $digest_uri;
1816              $response_value = md5(sprintf('%s:%s:00000001:%s:auth:%s', md5($auth_1), $md5_challenge['nonce'], $cnonce, md5($auth_2)));
1817  
1818              $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']);
1819          }
1820          else
1821          {
1822              return (isset($user->lang['INVALID_DIGEST_CHALLENGE'])) ? $user->lang['INVALID_DIGEST_CHALLENGE'] : 'Invalid digest challenge';
1823          }
1824  
1825          $base64_method_digest_md5 = base64_encode($input_string);
1826          $this->server_send($base64_method_digest_md5, true);
1827          if ($err_msg = $this->server_parse('334', __LINE__))
1828          {
1829              return $err_msg;
1830          }
1831  
1832          $this->server_send(' ');
1833          if ($err_msg = $this->server_parse('235', __LINE__))
1834          {
1835              return $err_msg;
1836          }
1837  
1838          return false;
1839      }
1840  }
1841  
1842  /**
1843  * Encodes the given string for proper display in UTF-8.
1844  *
1845  * This version is using base64 encoded data. The downside of this
1846  * is if the mail client does not understand this encoding the user
1847  * is basically doomed with an unreadable subject.
1848  *
1849  * Please note that this version fully supports RFC 2045 section 6.8.
1850  *
1851  * @param string $eol End of line we are using (optional to be backwards compatible)
1852  */
1853  function mail_encode($str, $eol = "\r\n")
1854  {
1855      // define start delimimter, end delimiter and spacer
1856      $start = "=?UTF-8?B?";
1857      $end = "?=";
1858      $delimiter = "$eol ";
1859  
1860      // Maximum length is 75. $split_length *must* be a multiple of 4, but <= 75 - strlen($start . $delimiter . $end)!!!
1861      $split_length = 60;
1862      $encoded_str = base64_encode($str);
1863  
1864      // If encoded string meets the limits, we just return with the correct data.
1865      if (strlen($encoded_str) <= $split_length)
1866      {
1867          return $start . $encoded_str . $end;
1868      }
1869  
1870      // If there is only ASCII data, we just return what we want, correctly splitting the lines.
1871      if (strlen($str) === utf8_strlen($str))
1872      {
1873          return $start . implode($end . $delimiter . $start, str_split($encoded_str, $split_length)) . $end;
1874      }
1875  
1876      // UTF-8 data, compose encoded lines
1877      $array = utf8_str_split($str);
1878      $str = '';
1879  
1880      while (count($array))
1881      {
1882          $text = '';
1883  
1884          while (count($array) && intval((strlen($text . $array[0]) + 2) / 3) << 2 <= $split_length)
1885          {
1886              $text .= array_shift($array);
1887          }
1888  
1889          $str .= $start . base64_encode($text) . $end . $delimiter;
1890      }
1891  
1892      return substr($str, 0, -strlen($delimiter));
1893  }
1894  
1895  /**
1896   * Wrapper for sending out emails with the PHP's mail function
1897   */
1898  function phpbb_mail($to, $subject, $msg, $headers, $eol, &$err_msg)
1899  {
1900      global $config, $phpbb_root_path, $phpEx;
1901  
1902      // Convert Numeric Character References to UTF-8 chars (ie. Emojis)
1903      $subject = utf8_decode_ncr($subject);
1904      $msg = utf8_decode_ncr($msg);
1905  
1906      /**
1907       * We use the EOL character for the OS here because the PHP mail function does not correctly transform line endings.
1908       * On Windows SMTP is used (SMTP is \r\n), on UNIX a command is used...
1909       * Reference: http://bugs.php.net/bug.php?id=15841
1910       */
1911      $headers = implode($eol, $headers);
1912  
1913      if (!class_exists('\phpbb\error_collector'))
1914      {
1915          include($phpbb_root_path . 'includes/error_collector.' . $phpEx);
1916      }
1917  
1918      $collector = new \phpbb\error_collector;
1919      $collector->install();
1920  
1921      /**
1922       * On some PHP Versions mail() *may* fail if there are newlines within the subject.
1923       * Newlines are used as a delimiter for lines in mail_encode() according to RFC 2045 section 6.8.
1924       * Because PHP can't decide what is wanted we revert back to the non-RFC-compliant way of separating by one space
1925       * (Use '' as parameter to mail_encode() results in SPACE used)
1926       */
1927      $additional_parameters = $config['email_force_sender'] ? '-f' . $config['board_email'] : '';
1928  
1929      $result = mail($to, mail_encode($subject, ''), wordwrap(utf8_wordwrap($msg), 997, "\n", true), $headers, $additional_parameters);
1930  
1931      $collector->uninstall();
1932      $err_msg = $collector->format_errors();
1933  
1934      return $result;
1935  }


Generated: Wed Nov 11 20:33:01 2020 Cross-referenced by PHPXref 0.7.1