PageRenderTime 57ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/phpBB/includes/functions_messenger.php

http://github.com/phpbb/phpbb3
PHP | 1933 lines | 1328 code | 282 blank | 323 comment | 205 complexity | c92039f7e67b29b9e6ba4b3c59d0ec1f MD5 | raw file
Possible License(s): AGPL-1.0

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file