[ Index ]

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


Generated: Thu Jan 11 23:14:31 2018 Cross-referenced by PHPXref 0.7.1