Commit | Line | Data |
---|---|---|
bdf67e28 SL |
1 | <?php |
2 | /* | |
3 | +--------------------------------------------------------------------+ | |
4 | | Copyright CiviCRM LLC. All rights reserved. | | |
5 | | | | |
6 | | This work is published under the GNU AGPLv3 license with some | | |
7 | | permitted exceptions and without any warranty. For full license | | |
8 | | and copyright information, see https://civicrm.org/licensing | | |
9 | +--------------------------------------------------------------------+ | |
10 | */ | |
11 | namespace Civi\FlexMailer\Listener; | |
12 | ||
13 | use Civi\FlexMailer\Event\ComposeBatchEvent; | |
14 | ||
15 | class ToHeader extends BaseListener { | |
16 | ||
17 | /** | |
18 | * Inject the "To:" header. | |
19 | * | |
20 | * @param \Civi\FlexMailer\Event\ComposeBatchEvent $e | |
21 | */ | |
22 | public function onCompose(ComposeBatchEvent $e) { | |
23 | if (!$this->isActive()) { | |
24 | return; | |
25 | } | |
26 | ||
27 | $names = $this->getContactNames($e->getTasks()); | |
28 | foreach ($e->getTasks() as $task) { | |
29 | /** @var \Civi\FlexMailer\FlexMailerTask $task */ | |
30 | ||
31 | $task->setMailParam('toEmail', $task->getAddress()); | |
32 | ||
33 | if (isset($names[$task->getContactId()])) { | |
34 | $task->setMailParam('toName', $names[$task->getContactId()]); | |
35 | } | |
36 | else { | |
37 | $task->setMailParam('toName', ''); | |
38 | } | |
39 | } | |
40 | } | |
41 | ||
42 | /** | |
43 | * Lookup contact names as a batch. | |
44 | * | |
45 | * @param array<FlexMailerTask> $tasks | |
46 | * @return array | |
47 | * Array(int $contactId => string $displayName). | |
48 | */ | |
49 | protected function getContactNames($tasks) { | |
50 | $ids = array(); | |
51 | foreach ($tasks as $task) { | |
52 | /** @var \Civi\FlexMailer\FlexMailerTask $task */ | |
53 | $ids[$task->getContactId()] = $task->getContactId(); | |
54 | } | |
55 | ||
56 | $ids = array_filter($ids, 'is_numeric'); | |
57 | if (empty($ids)) { | |
58 | return array(); | |
59 | } | |
60 | ||
61 | $idString = implode(',', $ids); | |
62 | ||
63 | $query = \CRM_Core_DAO::executeQuery( | |
64 | "SELECT id, display_name FROM civicrm_contact WHERE id in ($idString)"); | |
65 | $names = array(); | |
66 | while ($query->fetch()) { | |
67 | $names[$query->id] = $query->display_name; | |
68 | } | |
69 | return $names; | |
70 | } | |
71 | ||
72 | } |