[ Index ]

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


Generated: Sun Feb 19 19:47:08 2017 Cross-referenced by PHPXref 0.7.1