[ Index ]

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


Generated: Sun Feb 19 19:52:41 2017 Cross-referenced by PHPXref 0.7.1