simplenews.mail.inc 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. <?php
  2. /**
  3. * @file
  4. * Simplenews email send and spool handling
  5. *
  6. * @ingroup mail
  7. */
  8. /**
  9. * Add the newsletter node to the mail spool.
  10. *
  11. * @param $node
  12. * The newsletter node to be sent.
  13. *
  14. * @ingroup issue
  15. */
  16. function simplenews_add_node_to_spool($node) {
  17. // To send the newsletter, the node id and target email addresses
  18. // are stored in the spool.
  19. // Only subscribed recipients are stored in the spool (status = 1).
  20. $select = db_select('simplenews_subscriber', 's');
  21. $select->innerJoin('simplenews_subscription', 't', 's.snid = t.snid');
  22. $select->addField('s', 'mail');
  23. $select->addField('s', 'snid');
  24. $select->addField('t', 'tid');
  25. $select->addExpression($node->nid, 'nid');
  26. $select->addExpression(SIMPLENEWS_SUBSCRIPTION_STATUS_SUBSCRIBED, 'status');
  27. $select->addExpression(REQUEST_TIME, 'timestamp');
  28. $select->condition('t.tid', $node->simplenews->tid);
  29. $select->condition('t.status', SIMPLENEWS_SUBSCRIPTION_STATUS_SUBSCRIBED);
  30. $select->condition('s.activated', SIMPLENEWS_SUBSCRIPTION_ACTIVE);
  31. db_insert('simplenews_mail_spool')
  32. ->from($select)
  33. ->execute();
  34. // Update simplenews newsletter status to send pending.
  35. simplenews_newsletter_update_sent_status($node);
  36. }
  37. /**
  38. * Send mail spool immediatly if cron should not be used.
  39. *
  40. * @param $conditions
  41. * (Optional) Array of spool conditions which are applied to the query.
  42. */
  43. function simplenews_mail_attempt_immediate_send(array $conditions = array(), $use_batch = TRUE) {
  44. if (variable_get('simplenews_use_cron', TRUE)) {
  45. return FALSE;
  46. }
  47. if ($use_batch) {
  48. // Set up as many send operations as necessary to send all mails with the
  49. // defined throttle amount.
  50. $throttle = variable_get('simplenews_throttle', 20);
  51. $spool_count = simplenews_count_spool($conditions);
  52. $num_operations = ceil($spool_count / $throttle);
  53. $operations = array();
  54. for ($i = 0; $i < $num_operations; $i++) {
  55. $operations[] = array('simplenews_mail_spool', array($throttle, $conditions));
  56. }
  57. // Add separate operations to clear the spool and updat the send status.
  58. $operations[] = array('simplenews_clear_spool', array());
  59. $operations[] = array('simplenews_send_status_update', array());
  60. $batch = array(
  61. 'operations' => $operations,
  62. 'title' => t('Sending mails'),
  63. 'file' => drupal_get_path('module', 'simplenews') . '/includes/simplenews.mail.inc',
  64. );
  65. batch_set($batch);
  66. }
  67. else {
  68. // Send everything that matches the conditions immediatly.
  69. simplenews_mail_spool(SIMPLENEWS_UNLIMITED, $conditions);
  70. simplenews_clear_spool();
  71. simplenews_send_status_update();
  72. }
  73. return TRUE;
  74. }
  75. /**
  76. * Send test version of newsletter.
  77. *
  78. * @param mixed $node
  79. * The newsletter node to be sent.
  80. *
  81. * @ingroup issue
  82. */
  83. function simplenews_send_test($node, $test_addresses) {
  84. // Prevent session information from being saved while sending.
  85. if ($original_session = drupal_save_session()) {
  86. drupal_save_session(FALSE);
  87. }
  88. // Force the current user to anonymous to ensure consistent permissions.
  89. $original_user = $GLOBALS['user'];
  90. $GLOBALS['user'] = drupal_anonymous_user();
  91. // Send the test newsletter to the test address(es) specified in the node.
  92. // Build array of test email addresses
  93. // Send newsletter to test addresses.
  94. // Emails are send direct, not using the spool.
  95. $recipients = array('anonymous' => array(), 'user' => array());
  96. foreach ($test_addresses as $mail) {
  97. $mail = trim($mail);
  98. if (!empty($mail)) {
  99. $subscriber = simplenews_subscriber_load_by_mail($mail);
  100. if (!$subscriber) {
  101. // The source expects a subscriber object with mail and language set.
  102. // @todo: Find a cleaner way to do this.
  103. $subscriber = new stdClass();
  104. $subscriber->uid = 0;
  105. $subscriber->mail = $mail;
  106. $subscriber->language = $GLOBALS['language']->language;
  107. }
  108. if (!empty($account->uid)) {
  109. $recipients['user'][] = $account->name . ' <' . $mail . '>';
  110. }
  111. else {
  112. $recipients['anonymous'][] = $mail;
  113. }
  114. $source = new SimplenewsSourceNode($node, $subscriber);
  115. $source->setKey('test');
  116. $result = simplenews_send_source($source);
  117. }
  118. }
  119. if (count($recipients['user'])) {
  120. $recipients_txt = implode(', ', $recipients['user']);
  121. drupal_set_message(t('Test newsletter sent to user %recipient.', array('%recipient' => $recipients_txt)));
  122. }
  123. if (count($recipients['anonymous'])) {
  124. $recipients_txt = implode(', ', $recipients['anonymous']);
  125. drupal_set_message(t('Test newsletter sent to anonymous %recipient.', array('%recipient' => $recipients_txt)));
  126. }
  127. $GLOBALS['user'] = $original_user;
  128. if ($original_session) {
  129. drupal_save_session(TRUE);
  130. }
  131. }
  132. /**
  133. * Send a node to an email address.
  134. *
  135. * @param $source
  136. * The source object.s
  137. *
  138. * @return boolean
  139. * TRUE if the email was successfully delivered; otherwise FALSE.
  140. *
  141. * @ingroup source
  142. */
  143. function simplenews_send_source(SimplenewsSourceInterface $source) {
  144. $params['simplenews_source'] = $source;
  145. // Send mail.
  146. $message = drupal_mail('simplenews', $source->getKey(), $source->getRecipient(), $source->getLanguage(), $params, $source->getFromFormatted());
  147. // Log sent result in watchdog.
  148. if (variable_get('simplenews_debug', FALSE)) {
  149. if ($message['result']) {
  150. watchdog('simplenews', 'Outgoing email. Message type: %type<br />Subject: %subject<br />Recipient: %to', array('%type' => $source->getKey(), '%to' => $message['to'], '%subject' => $message['subject']), WATCHDOG_DEBUG);
  151. }
  152. else {
  153. watchdog('simplenews', 'Outgoing email failed. Message type: %type<br />Subject: %subject<br />Recipient: %to', array('%type' => $source->getKey(), '%to' => $message['to'], '%subject' => $message['subject']), WATCHDOG_ERROR);
  154. }
  155. }
  156. // Build array of sent results for spool table and reporting.
  157. if ($message['result']) {
  158. $result = array(
  159. 'status' => SIMPLENEWS_SPOOL_DONE,
  160. 'error' => FALSE,
  161. );
  162. }
  163. else {
  164. // This error may be caused by faulty mailserver configuration or overload.
  165. // Mark "pending" to keep trying.
  166. $result = array(
  167. 'status' => SIMPLENEWS_SPOOL_PENDING,
  168. 'error' => TRUE,
  169. );
  170. }
  171. return $result;
  172. }
  173. /**
  174. * Send simplenews newsletters from the spool.
  175. *
  176. * Individual newsletter emails are stored in database spool.
  177. * Sending is triggered by cron or immediately when the node is saved.
  178. * Mail data is retrieved from the spool, rendered and send one by one
  179. * If sending is successful the message is marked as send in the spool.
  180. *
  181. * @todo: Redesign API to allow language counter in multilingual sends.
  182. *
  183. * @param $limit
  184. * (Optional) The maximum number of mails to send. Defaults to
  185. * unlimited.
  186. * @param $conditions
  187. * (Optional) Array of spool conditions which are applied to the query.
  188. *
  189. * @return
  190. * Returns the amount of sent mails.
  191. *
  192. * @ingroup spool
  193. */
  194. function simplenews_mail_spool($limit = SIMPLENEWS_UNLIMITED, array $conditions = array()) {
  195. $check_counter = 0;
  196. // Send pending messages from database cache.
  197. $spool_list = simplenews_get_spool($limit, $conditions);
  198. if ($spool_list) {
  199. // Switch to the anonymous user.
  200. simplenews_impersonate_user(drupal_anonymous_user());
  201. $count_fail = $count_success = 0;
  202. _simplenews_measure_usec(TRUE);
  203. $spool = new SimplenewsSpool($spool_list);
  204. while ($source = $spool->nextSource()) {
  205. $source->setKey('node');
  206. $result = simplenews_send_source($source);
  207. // Update spool status.
  208. // This is not optimal for performance but prevents duplicate emails
  209. // in case of PHP execution time overrun.
  210. foreach ($spool->getProcessed() as $msid => $row) {
  211. $row_result = isset($row->result) ? $row->result : $result;
  212. simplenews_update_spool(array($msid), $row_result);
  213. if ($row_result['status'] == SIMPLENEWS_SPOOL_DONE) {
  214. $count_success++;
  215. }
  216. if ($row_result['error']) {
  217. $count_fail++;
  218. }
  219. }
  220. // Check every n emails if we exceed the limit.
  221. // When PHP maximum execution time is almost elapsed we interrupt
  222. // sending. The remainder will be sent during the next cron run.
  223. if (++$check_counter >= SIMPLENEWS_SEND_CHECK_INTERVAL && ini_get('max_execution_time') > 0) {
  224. $check_counter = 0;
  225. // Break the sending if a percentage of max execution time was exceeded.
  226. $elapsed = _simplenews_measure_usec();
  227. if ($elapsed > SIMPLENEWS_SEND_TIME_LIMIT * ini_get('max_execution_time')) {
  228. watchdog('simplenews', 'Sending interrupted: PHP maximum execution time almost exceeded. Remaining newsletters will be sent during the next cron run. If this warning occurs regularly you should reduce the !cron_throttle_setting.', array('!cron_throttle_setting' => l(t('Cron throttle setting'), 'admin/config/simplenews/mail')), WATCHDOG_WARNING);
  229. break;
  230. }
  231. }
  232. // It is possible that all or at the end some results failed to get
  233. // prepared, report them separately.
  234. foreach ($spool->getProcessed() as $msid => $row) {
  235. $row_result = isset($row->result) ? $row->result : $result;
  236. simplenews_update_spool(array($msid), $row_result);
  237. if ($row_result['status'] == SIMPLENEWS_SPOOL_DONE) {
  238. $count_success++;
  239. }
  240. if ($row_result['error']) {
  241. $count_fail++;
  242. }
  243. }
  244. }
  245. // Report sent result and elapsed time. On Windows systems getrusage() is
  246. // not implemented and hence no elapsed time is available.
  247. if (function_exists('getrusage')) {
  248. watchdog('simplenews', '%success emails sent in %sec seconds, %fail failed sending.', array('%success' => $count_success, '%sec' => round(_simplenews_measure_usec(), 1), '%fail' => $count_fail));
  249. }
  250. else {
  251. watchdog('simplenews', '%success emails sent, %fail failed.', array('%success' => $count_success, '%fail' => $count_fail));
  252. }
  253. variable_set('simplenews_last_cron', REQUEST_TIME);
  254. variable_set('simplenews_last_sent', $count_success);
  255. simplenews_revert_user();
  256. return $count_success;
  257. }
  258. }
  259. /**
  260. * Save mail message in mail cache table.
  261. *
  262. * @param array $spool
  263. * The message to be stored in the spool table, as an array containing the
  264. * following keys:
  265. * - mail
  266. * - nid
  267. * - tid
  268. * - status: (optional) Defaults to SIMPLENEWS_SPOOL_PENDING
  269. * - time: (optional) Defaults to REQUEST_TIME.
  270. *
  271. * @ingroup spool
  272. */
  273. function simplenews_save_spool($spool) {
  274. $status = isset($spool['status']) ? $spool['status'] : SIMPLENEWS_SPOOL_PENDING;
  275. $time = isset($spool['time']) ? $spool['time'] : REQUEST_TIME;
  276. db_insert('simplenews_mail_spool')
  277. ->fields(array(
  278. 'mail' => $spool['mail'],
  279. 'nid' => $spool['nid'],
  280. 'tid' => $spool['tid'],
  281. 'snid' => $spool['snid'],
  282. 'status' => $status,
  283. 'timestamp' => $time,
  284. 'data' => serialize($spool['data']),
  285. ))
  286. ->execute();
  287. }
  288. /*
  289. * Returns the expiration time for IN_PROGRESS status.
  290. *
  291. * @return int
  292. * A unix timestamp. Any IN_PROGRESS messages with a timestamp older than
  293. * this will be re-allocated and re-sent.
  294. */
  295. function simplenews_get_expiration_time() {
  296. $timeout = variable_get('simplenews_spool_progress_expiration', 3600);
  297. $expiration_time = REQUEST_TIME - $timeout;
  298. return $expiration_time;
  299. }
  300. /**
  301. * This function allocates messages to be sent in current run.
  302. *
  303. * Drupal acquire_lock guarantees that no concurrency issue happened.
  304. * If the message status is SIMPLENEWS_SPOOL_IN_PROGRESS but the maximum send
  305. * time has expired, the message id will be returned as a message which is not
  306. * allocated to another process.
  307. *
  308. * @param $limit
  309. * (Optional) The maximum number of mails to load from the spool. Defaults to
  310. * unlimited.
  311. * @param $conditions
  312. * (Optional) Array of conditions which are applied to the query. If not set,
  313. * status defaults to SIMPLENEWS_SPOOL_PENDING, SIMPLENEWS_SPOOL_IN_PROGRESS.
  314. *
  315. * @return
  316. * An array of message ids to be sent in the current run.
  317. *
  318. * @ingroup spool
  319. */
  320. function simplenews_get_spool($limit = SIMPLENEWS_UNLIMITED, $conditions = array()) {
  321. $messages = array();
  322. // Add default status condition if not set.
  323. if (!isset($conditions['status'])) {
  324. $conditions['status'] = array(SIMPLENEWS_SPOOL_PENDING, SIMPLENEWS_SPOOL_IN_PROGRESS);
  325. }
  326. // Special case for the status condition, the in progress actually only
  327. // includes spool items whose locking time has expired. So this need to build
  328. // an OR condition for them.
  329. $status_or = db_or();
  330. $statuses = is_array($conditions['status']) ? $conditions['status'] : array($conditions['status']);
  331. foreach ($statuses as $status) {
  332. if ($status == SIMPLENEWS_SPOOL_IN_PROGRESS) {
  333. $status_or->condition(db_and()
  334. ->condition('status', $status)
  335. ->condition('s.timestamp', simplenews_get_expiration_time(), '<')
  336. );
  337. }
  338. else {
  339. $status_or->condition('status', $status);
  340. }
  341. }
  342. unset($conditions['status']);
  343. $query = db_select('simplenews_mail_spool', 's')
  344. ->fields('s')
  345. ->condition($status_or)
  346. ->orderBy('s.timestamp', 'ASC');
  347. // Add conditions.
  348. foreach ($conditions as $field => $value) {
  349. $query->condition($field, $value);
  350. }
  351. /* BEGIN CRITICAL SECTION */
  352. // The semaphore ensures that multiple processes get different message ID's,
  353. // so that duplicate messages are not sent.
  354. if (lock_acquire('simplenews_acquire_mail')) {
  355. // Get message id's
  356. // Allocate messages
  357. if ($limit > 0) {
  358. $query->range(0, $limit);
  359. }
  360. foreach ($query->execute() as $message) {
  361. if (strlen($message->data)) {
  362. $message->data = unserialize($message->data);
  363. }
  364. else {
  365. $message->data = simplenews_subscriber_load_by_mail($message->mail);
  366. }
  367. $messages[$message->msid] = $message;
  368. }
  369. if (count($messages) > 0) {
  370. // Set the state and the timestamp of the messages
  371. simplenews_update_spool(
  372. array_keys($messages),
  373. array('status' => SIMPLENEWS_SPOOL_IN_PROGRESS)
  374. );
  375. }
  376. lock_release('simplenews_acquire_mail');
  377. }
  378. /* END CRITICAL SECTION */
  379. return $messages;
  380. }
  381. /**
  382. * Update status of mail data in spool table.
  383. *
  384. * Time stamp is set to current time.
  385. *
  386. * @param array $msids
  387. * Array of Mail spool ids to be updated
  388. * @param array $data
  389. * Array containing email sent results, with the following keys:
  390. * - status: An integer indicating the updated status. Must be one of:
  391. * - 0: hold
  392. * - 1: pending
  393. * - 2: send
  394. * - 3: in progress
  395. * - error: (optional) The error id. Defaults to 0 (no error).
  396. *
  397. * @ingroup spool
  398. */
  399. function simplenews_update_spool($msids, $data) {
  400. db_update('simplenews_mail_spool')
  401. ->condition('msid', $msids)
  402. ->fields(array(
  403. 'status' => $data['status'],
  404. 'error' => isset($result['error']) ? (int)$data['error'] : 0,
  405. 'timestamp' => REQUEST_TIME,
  406. ))
  407. ->execute();
  408. }
  409. /**
  410. * Count data in mail spool table.
  411. *
  412. * @param $conditions
  413. * (Optional) Array of conditions which are applied to the query. Defaults
  414. *
  415. * @return
  416. * Count of mail spool elements of the passed in arguments.
  417. *
  418. * @ingroup spool
  419. */
  420. function simplenews_count_spool(array $conditions = array()) {
  421. // Add default status condition if not set.
  422. if (!isset($conditions['status'])) {
  423. $conditions['status'] = array(SIMPLENEWS_SPOOL_PENDING, SIMPLENEWS_SPOOL_IN_PROGRESS);
  424. }
  425. $query = db_select('simplenews_mail_spool');
  426. // Add conditions.
  427. foreach ($conditions as $field => $value) {
  428. $query->condition($field, $value);
  429. }
  430. $query->addExpression('COUNT(*)', 'count');
  431. return (int)$query
  432. ->execute()
  433. ->fetchField();
  434. }
  435. /**
  436. * Remove old records from mail spool table.
  437. *
  438. * All records with status 'send' and time stamp before the expiration date
  439. * are removed from the spool.
  440. *
  441. * @return
  442. * Number of deleted spool rows.
  443. *
  444. * @ingroup spool
  445. */
  446. function simplenews_clear_spool() {
  447. $expiration_time = REQUEST_TIME - variable_get('simplenews_spool_expire', 0) * 86400;
  448. return db_delete('simplenews_mail_spool')
  449. ->condition('status', SIMPLENEWS_SPOOL_DONE)
  450. ->condition('timestamp', $expiration_time, '<=')
  451. ->execute();
  452. }
  453. /**
  454. * Remove records from mail spool table according to the conditions.
  455. *
  456. * @return Count deleted
  457. *
  458. * @ingroup spool
  459. */
  460. function simplenews_delete_spool(array $conditions) {
  461. $query = db_delete('simplenews_mail_spool');
  462. foreach ($conditions as $condition => $value) {
  463. $query->condition($condition, $value);
  464. }
  465. return $query->execute();
  466. }
  467. /**
  468. * Update newsletter sent status.
  469. *
  470. * Set newsletter sent status based on email sent status in spool table.
  471. * Translated and untranslated nodes get a different treatment.
  472. *
  473. * The spool table holds data for emails to be sent and (optionally)
  474. * already send emails. The simplenews_newsletter table contains the overall
  475. * sent status of each newsletter issue (node).
  476. * Newsletter issues get the status pending when sending is initiated. As
  477. * long as unsend emails exist in the spool, the status of the newsletter remains
  478. * unsend. When no pending emails are found the newsletter status is set 'send'.
  479. *
  480. * Translated newsletters are a group of nodes that share the same tnid ({node}.tnid).
  481. * Only one node of the group is found in the spool, but all nodes should share
  482. * the same state. Therefore they are checked for the combined number of emails
  483. * in the spool.
  484. *
  485. * @ingroup issue
  486. */
  487. function simplenews_send_status_update() {
  488. $counts = array(); // number pending of emails in the spool
  489. $sum = array(); // sum of emails in the spool per tnid (translation id)
  490. $send = array(); // nodes with the status 'send'
  491. // For each pending newsletter count the number of pending emails in the spool.
  492. $query = db_select('simplenews_newsletter', 's');
  493. $query->innerJoin('node', 'n', 's.nid = n.nid');
  494. $query->fields('s', array('nid', 'tid'))
  495. ->fields('n', array('tnid'))
  496. ->condition('s.status', SIMPLENEWS_STATUS_SEND_PENDING);
  497. foreach ($query->execute() as $newsletter) {
  498. $counts[$newsletter->tnid][$newsletter->nid] = simplenews_count_spool(array('nid' => $newsletter->nid));
  499. }
  500. // Determine which nodes are send per translation group and per individual node.
  501. foreach ($counts as $tnid => $node_count) {
  502. // The sum of emails per tnid is the combined status result for the group of translated nodes.
  503. // Untranslated nodes have tnid == 0 which will be ignored later.
  504. $sum[$tnid] = array_sum($node_count);
  505. foreach ($node_count as $nid => $count) {
  506. // Translated nodes (tnid != 0)
  507. if ($tnid != '0' && $sum[$tnid] == '0') {
  508. $send[] = $nid;
  509. }
  510. // Untranslated nodes (tnid == 0)
  511. elseif ($tnid == '0' && $count == '0') {
  512. $send[] = $nid;
  513. }
  514. }
  515. }
  516. // Update overall newsletter status
  517. if (!empty($send)) {
  518. foreach ($send as $nid) {
  519. db_update('simplenews_newsletter')
  520. ->condition('nid', $nid)
  521. ->fields(array('status' => SIMPLENEWS_STATUS_SEND_READY))
  522. ->execute();
  523. }
  524. }
  525. }
  526. /**
  527. * Build formatted from-name and email for a mail object.
  528. *
  529. * @return Associative array with (un)formatted from address
  530. * 'address' => From address
  531. * 'formatted' => Formatted, mime encoded, from name and address
  532. */
  533. function _simplenews_set_from() {
  534. $address_default = variable_get('site_mail', ini_get('sendmail_from'));
  535. $name_default = variable_get('site_name', 'Drupal');
  536. $address = variable_get('simplenews_from_address', $address_default);
  537. $name = variable_get('simplenews_from_name', $name_default);
  538. // Windows based PHP systems don't accept formatted emails.
  539. $formatted_address = substr(PHP_OS, 0, 3) == 'WIN' ? $address : '"' . $name . '" <' . $address . '>';
  540. return array(
  541. 'address' => $address,
  542. 'formatted' => $formatted_address,
  543. );
  544. }
  545. /**
  546. * HTML to text conversion for HTML and special characters.
  547. *
  548. * Converts some special HTML characters in addition to drupal_html_to_text()
  549. *
  550. * @param string $text
  551. * The source text with HTML and special characters.
  552. * @param boolean $inline_hyperlinks
  553. * TRUE: URLs will be placed inline.
  554. * FALSE: URLs will be converted to numbered reference list.
  555. * @return string
  556. * The target text with HTML and special characters replaced.
  557. */
  558. function simplenews_html_to_text($text, $inline_hyperlinks = TRUE) {
  559. // By replacing <a> tag by only its URL the URLs will be placed inline
  560. // in the email body and are not converted to a numbered reference list
  561. // by drupal_html_to_text().
  562. // URL are converted to absolute URL as drupal_html_to_text() would have.
  563. if ($inline_hyperlinks) {
  564. $pattern = '@<a[^>]+?href="([^"]*)"[^>]*?>(.+?)</a>@is';
  565. $text = preg_replace_callback($pattern, '_simplenews_absolute_mail_urls', $text);
  566. }
  567. // Replace some special characters before performing the drupal standard conversion.
  568. $preg = _simplenews_html_replace();
  569. $text = preg_replace(array_keys($preg), array_values($preg), $text);
  570. // Perform standard drupal html to text conversion.
  571. return drupal_html_to_text($text);
  572. }
  573. /**
  574. * Helper function for simplenews_html_to_text().
  575. *
  576. * Replaces URLs with absolute URLs.
  577. */
  578. function _simplenews_absolute_mail_urls($match) {
  579. global $base_url, $base_path;
  580. $regexp = &drupal_static(__FUNCTION__);
  581. $url = $label = '';
  582. if ($match) {
  583. if (empty($regexp)) {
  584. $regexp = '@^' . preg_quote($base_path, '@') . '@';
  585. }
  586. list(, $url, $label) = $match;
  587. $url = strpos($url, '://') ? $url : preg_replace($regexp, $base_url . '/', $url);
  588. // If the link is formed by Drupal's URL filter, we only return the URL.
  589. // The URL filter generates a label out of the original URL.
  590. if (strpos($label, '...') === strlen($label) - 3) {
  591. // Remove ellipsis from end of label.
  592. $label = substr($label, 0, strlen($label) - 3);
  593. }
  594. if (strpos($url, $label) !== FALSE) {
  595. return $url;
  596. }
  597. return $label . ' ' . $url;
  598. }
  599. }
  600. /**
  601. * Helper function for simplenews_html_to_text().
  602. *
  603. * List of preg* regular expression patterns to search for and replace with
  604. */
  605. function _simplenews_html_replace() {
  606. return array(
  607. '/&quot;/i' => '"',
  608. '/&gt;/i' => '>',
  609. '/&lt;/i' => '<',
  610. '/&amp;/i' => '&',
  611. '/&copy;/i' => '(c)',
  612. '/&trade;/i' => '(tm)',
  613. '/&#8220;/' => '"',
  614. '/&#8221;/' => '"',
  615. '/&#8211;/' => '-',
  616. '/&#8217;/' => "'",
  617. '/&#38;/' => '&',
  618. '/&#169;/' => '(c)',
  619. '/&#8482;/' => '(tm)',
  620. '/&#151;/' => '--',
  621. '/&#147;/' => '"',
  622. '/&#148;/' => '"',
  623. '/&#149;/' => '*',
  624. '/&reg;/i' => '(R)',
  625. '/&bull;/i' => '*',
  626. '/&euro;/i' => 'Euro ',
  627. );
  628. }
  629. /**
  630. * Helper function to measure PHP execution time in microseconds.
  631. *
  632. * @param bool $start
  633. * If TRUE, reset the time and start counting.
  634. *
  635. * @return float
  636. * The elapsed PHP execution time since the last start.
  637. */
  638. function _simplenews_measure_usec($start = FALSE) {
  639. // Windows systems don't implement getrusage(). There is no alternative.
  640. if (!function_exists('getrusage')) {
  641. return;
  642. }
  643. $start_time = &drupal_static(__FUNCTION__);
  644. $usage = getrusage();
  645. $now = (float)($usage['ru_stime.tv_sec'] . '.' . $usage['ru_stime.tv_usec']) + (float)($usage['ru_utime.tv_sec'] . '.' . $usage['ru_utime.tv_usec']);
  646. if ($start) {
  647. $start_time = $now;
  648. return;
  649. }
  650. return $now - $start_time;
  651. }
  652. /**
  653. * Build subject and body of the test and normal newsletter email.
  654. *
  655. * @param array $message
  656. * Message array as used by hook_mail().
  657. * @param array $source
  658. * The SimplenewsSource instance.
  659. *
  660. * @ingroup source
  661. */
  662. function simplenews_build_newsletter_mail(&$message, SimplenewsSourceInterface $source) {
  663. // Get message data from source.
  664. $message['headers'] = $source->getHeaders($message['headers']);
  665. $message['subject'] = $source->getSubject();
  666. $message['body']['body'] = $source->getBody();
  667. $message['body']['footer'] = $source->getFooter();
  668. // Optional params for HTML mails.
  669. if ($source->getFormat() == 'html') {
  670. $message['params']['plain'] = NULL;
  671. $message['params']['plaintext'] = $source->getPlainBody() . "\n" . $source->getPlainFooter();
  672. $message['params']['attachments'] = $source->getAttachments();
  673. }
  674. else {
  675. $message['params']['plain'] = TRUE;
  676. }
  677. }
  678. /**
  679. * Build subject and body of the subscribe confirmation email.
  680. *
  681. * @param array $message
  682. * Message array as used by hook_mail().
  683. * @param array $params
  684. * Parameter array as used by hook_mail().
  685. */
  686. function simplenews_build_subscribe_mail(&$message, $params) {
  687. $context = $params['context'];
  688. $langcode = $message['language'];
  689. // Use formatted from address "name" <mail_address>
  690. $message['headers']['From'] = $params['from']['formatted'];
  691. $message['subject'] = simplenews_subscription_confirmation_text('subscribe_subject', $langcode);
  692. $message['subject'] = token_replace($message['subject'], $context, array('sanitize' => FALSE));
  693. if (simplenews_user_is_subscribed($context['simplenews_subscriber']->mail, $context['category']->tid)) {
  694. $body = simplenews_subscription_confirmation_text('subscribe_subscribed', $langcode);
  695. }
  696. else {
  697. $body = simplenews_subscription_confirmation_text('subscribe_unsubscribed', $langcode);
  698. }
  699. $message['body'][] = token_replace($body, $context, array('sanitize' => FALSE));
  700. }
  701. /**
  702. * Build subject and body of the subscribe confirmation email.
  703. *
  704. * @param array $message
  705. * Message array as used by hook_mail().
  706. * @param array $params
  707. * Parameter array as used by hook_mail().
  708. */
  709. function simplenews_build_combined_mail(&$message, $params) {
  710. $context = $params['context'];
  711. $changes = $context['changes'];
  712. $langcode = $message['language'];
  713. // Use formatted from address "name" <mail_address>
  714. $message['headers']['From'] = $params['from']['formatted'];
  715. $message['subject'] = simplenews_subscription_confirmation_text('combined_subject', $langcode);
  716. $message['subject'] = token_replace($message['subject'], $context, array('sanitize' => FALSE));
  717. $changes_list = '';
  718. $actual_changes = 0;
  719. foreach (simplenews_confirmation_get_changes_list($context['simplenews_subscriber'], $changes, $langcode) as $tid => $change) {
  720. $changes_list .= ' - ' . $change . "\n";
  721. // Count the actual changes.
  722. $subscribed = simplenews_user_is_subscribed($context['simplenews_subscriber']->mail, $tid);
  723. if ($changes[$tid] == 'subscribe' && !$subscribed || $changes[$tid] == 'unsubscribe' && $subscribed) {
  724. $actual_changes++;
  725. }
  726. }
  727. // If there are actual changes, use the combined_body key otherwise use the
  728. // one without a confirmation link.
  729. $body_key = $actual_changes ? 'combined_body' : 'combined_body_unchanged';
  730. $body = simplenews_subscription_confirmation_text($body_key, $langcode);
  731. // The changes list is not an actual token.
  732. $body = str_replace('[changes-list]', $changes_list, $body);
  733. $message['body'][] = token_replace($body, $context, array('sanitize' => FALSE));
  734. }
  735. /**
  736. * Build subject and body of the unsubscribe confirmation email.
  737. *
  738. * @param array $message
  739. * Message array as used by hook_mail().
  740. * @param array $params
  741. * Parameter array as used by hook_mail().
  742. */
  743. function simplenews_build_unsubscribe_mail(&$message, $params) {
  744. $context = $params['context'];
  745. $langcode = $message['language'];
  746. // Use formatted from address "name" <mail_address>
  747. $message['headers']['From'] = $params['from']['formatted'];
  748. $message['subject'] = simplenews_subscription_confirmation_text('subscribe_subject', $langcode);
  749. $message['subject'] = token_replace($message['subject'], $context, array('sanitize' => FALSE));
  750. if (simplenews_user_is_subscribed($context['simplenews_subscriber']->mail, $context['category']->tid)) {
  751. $body = simplenews_subscription_confirmation_text('unsubscribe_subscribed', $langcode);
  752. $message['body'][] = token_replace($body, $context, array('sanitize' => FALSE));
  753. }
  754. else {
  755. $body = simplenews_subscription_confirmation_text('unsubscribe_unsubscribed', $langcode);
  756. $message['body'][] = token_replace($body, $context, array('sanitize' => FALSE));
  757. }
  758. }
  759. /**
  760. * A mail sending implementation that captures sent messages to a variable.
  761. *
  762. * This class is for running tests or for development and does not convert HTML
  763. * to plaintext.
  764. */
  765. class SimplenewsHTMLTestingMailSystem implements MailSystemInterface {
  766. /**
  767. * Implements MailSystemInterface::format().
  768. */
  769. public function format(array $message) {
  770. // Join the body array into one string.
  771. $message['body'] = implode("\n\n", $message['body']);
  772. // Wrap the mail body for sending.
  773. $message['body'] = drupal_wrap_mail($message['body']);
  774. return $message;
  775. }
  776. /**
  777. * Implements MailSystemInterface::mail().
  778. */
  779. public function mail(array $message) {
  780. $captured_emails = variable_get('drupal_test_email_collector', array());
  781. $captured_emails[] = $message;
  782. // @todo: This is rather slow when sending 100 and more mails during tests.
  783. // Investigate in other methods like APC shared memory.
  784. variable_set('drupal_test_email_collector', $captured_emails);
  785. return TRUE;
  786. }
  787. }