[ Index ]

PHP Cross Reference of Unnamed Project

title

Body

[close]

/includes/ -> functions_messenger.php (source)

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


Generated: Wed Oct 2 15:03:47 2013 Cross-referenced by PHPXref 0.7.1