Elgg  Version master
Email.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Elgg;
4 
7 use Psr\Log\LogLevel;
8 use Symfony\Component\Mime\Address;
9 use Symfony\Component\Mime\Part\DataPart;
10 
14 final class Email {
15 
16  protected ?Address $from = null;
17 
21  protected array $to = [];
22 
26  protected array $cc = [];
27 
31  protected array $bcc = [];
32 
33  protected ?Address $sender = null;
34 
35  protected string $subject = '';
36 
37  protected ?string $body = null;
38 
39  protected array $params = [];
40 
41  protected array $headers = [];
42 
46  protected array $attachments = [];
47 
63  public static function factory(array $options = []): Email {
64  $from = elgg_extract('from', $options);
65  $to = elgg_extract('to', $options);
66  $cc = elgg_extract('cc', $options);
67  $bcc = elgg_extract('bcc', $options);
68  $subject = elgg_extract('subject', $options);
69  $body = elgg_extract('body', $options);
70  $params = elgg_extract('params', $options, []);
71  $headers = elgg_extract('headers', $options, []);
72 
73  $email = new self();
74  $email->setSender($from);
75  $email->setFrom(self::prepareFrom($from));
76  $email->setTo($to);
77  $email->setCc($cc);
78  $email->setBcc($bcc);
79  $email->setSubject($subject);
80  $email->setBody($body);
81  $email->setParams($params);
82  $email->setHeaders($headers);
83 
84  if (isset($params['attachments']) && is_array($params['attachments'])) {
85  foreach ($params['attachments'] as $attachment) {
86  $email->addAttachment($attachment);
87  }
88  }
89 
90  return $email;
91  }
92 
100  public function setSender(mixed $sender): self {
101  $prepared_sender = $this->prepareRecipients($sender);
102  $this->sender = !empty($prepared_sender) ? $prepared_sender[0] : null;
103  return $this;
104  }
105 
111  public function getSender(): Address {
112  if (isset($this->sender)) {
113  return $this->sender;
114  }
115 
117  return new Address($site->getEmailAddress(), $site->getDisplayName());
118  }
119 
127  public function setFrom(Address $from): self {
128  $this->from = $from;
129  return $this;
130  }
131 
137  public function getFrom(): ?Address {
138  return $this->from;
139  }
140 
148  public function setTo(mixed $recipient): self {
149  $this->to = $this->prepareRecipients($recipient);
150  return $this;
151  }
152 
158  public function getTo(): array {
159  return $this->to;
160  }
161 
169  public function setCc(mixed $recipient): self {
170  $this->cc = $this->prepareRecipients($recipient);
171  return $this;
172  }
173 
179  public function getCc(): array {
180  return $this->cc;
181  }
182 
190  public function setBcc(mixed $recipient): self {
191  $this->bcc = $this->prepareRecipients($recipient);
192  return $this;
193  }
194 
200  public function getBcc(): array {
201  return $this->bcc;
202  }
203 
211  public function setSubject(string $subject = ''): self {
212  $this->subject = $subject;
213  return $this;
214  }
215 
223  public function getSubject(): string {
224  return elgg_substr($this->subject, 0, (int) _elgg_services()->config->email_subject_limit);
225  }
226 
234  public function setBody(string $body = ''): self {
235  $this->body = $body;
236  return $this;
237  }
238 
244  public function getBody(): ?string {
245  return $this->body;
246  }
247 
255  public function setParams(array $params = []): self {
256  $this->params = $params;
257  return $this;
258  }
259 
265  public function getParams(): array {
266  return $this->params;
267  }
268 
277  public function addHeader(string $name, mixed $value): self {
278  $this->headers[$name] = $value;
279  return $this;
280  }
281 
289  public function setHeaders(array $headers = []): self {
290  $this->headers = $headers;
291  return $this;
292  }
293 
299  public function getHeaders(): array {
300  return $this->headers;
301  }
302 
312  public function addAttachment(mixed $attachment): self {
313  if ($attachment instanceof DataPart) {
314  $this->attachments[] = $attachment;
315  return $this;
316  }
317 
318  try {
319  $this->attachments[] = Attachment::factory($attachment);
320  } catch (InvalidArgumentException $e) {
321  elgg_log($e->getMessage(), LogLevel::ERROR);
322  }
323 
324  return $this;
325  }
326 
332  public function getAttachments(): array {
333  return $this->attachments;
334  }
335 
345  public function createEntityMessageID(\ElggEntity $entity, bool $add_microtime = false): string {
346  $microtime = '';
347  if ($add_microtime) {
348  $microtime = '.' . microtime(true);
349  }
350 
351  $hostname = parse_url(elgg_get_site_url(), PHP_URL_HOST);
352  $urlPath = parse_url(elgg_get_site_url(), PHP_URL_PATH);
353 
354  return "{$urlPath}.entity.{$entity->guid}{$microtime}@{$hostname}";
355  }
356 
365  protected static function prepareFrom(mixed $from): Address {
366  if (empty($from)) {
367  // get the site email address
369  $from = new Address($site->getEmailAddress(), $site->getDisplayName());
370  } elseif ($from instanceof \ElggSite) {
371  // use site email address
372  $from = new Address($from->getEmailAddress(), $from->getDisplayName());
373  } elseif ($from instanceof \ElggEntity) {
374  // If there's an email address, use it - but only if it's not from a user.
375  if (!$from instanceof \ElggUser && !empty($from->email)) {
376  $from = new Address($from->email, $from->getDisplayName());
377  } else {
378  // get the site email address
380  $from_display = elgg_echo('notification:method:email:from', [$from->getDisplayName(), $site->getDisplayName()]);
381  $from = new Address($site->getEmailAddress(), $from_display);
382  }
383  } elseif (is_string($from)) {
384  $from = Address::create($from);
385  }
386 
387  if (!$from instanceof Address) {
388  throw new InvalidArgumentException('From address is not in a valid format');
389  }
390 
391  return $from;
392  }
393 
402  protected function prepareRecipients(mixed $recipients): array {
403  if (empty($recipients)) {
404  return [];
405  }
406 
407  if (!is_array($recipients)) {
408  $recipients = [$recipients];
409  }
410 
411  $result = [];
412  foreach ($recipients as $recipient) {
413  if ($recipient instanceof Address) {
414  $result[] = $recipient;
415  continue;
416  }
417 
418  if ($recipient instanceof \ElggSite) {
419  $recipient = new Address($recipient->getEmailAddress(), $recipient->getDisplayName());
420  } elseif ($recipient instanceof \ElggEntity && !empty($recipient->email)) {
421  $recipient = new Address($recipient->email, $recipient->getDisplayName());
422  } elseif (is_string($recipient)) {
423  $recipient = Address::create($recipient);
424  }
425 
426  if (!$recipient instanceof Address) {
427  throw new InvalidArgumentException('Recipient address is not in a valid format');
428  }
429 
430  $result[] = $recipient;
431  }
432 
433  return $result;
434  }
435 }
$site
Definition: icons.php:5
$entity
Definition: reset.php:8
$email
Definition: change_email.php:7
if(! $user||! $user->canDelete()) $name
Definition: delete.php:22
$recipient
Definition: mute.php:8
$params
Saves global plugin settings.
Definition: save.php:13
return[ 'admin/delete_admin_notices'=>['access'=> 'admin'], 'admin/menu/save'=>['access'=> 'admin'], 'admin/plugins/activate'=>['access'=> 'admin'], 'admin/plugins/activate_all'=>['access'=> 'admin'], 'admin/plugins/deactivate'=>['access'=> 'admin'], 'admin/plugins/deactivate_all'=>['access'=> 'admin'], 'admin/plugins/set_priority'=>['access'=> 'admin'], 'admin/security/security_txt'=>['access'=> 'admin'], 'admin/security/settings'=>['access'=> 'admin'], 'admin/security/regenerate_site_secret'=>['access'=> 'admin'], 'admin/site/cache/invalidate'=>['access'=> 'admin'], 'admin/site/flush_cache'=>['access'=> 'admin'], 'admin/site/icons'=>['access'=> 'admin'], 'admin/site/set_maintenance_mode'=>['access'=> 'admin'], 'admin/site/set_robots'=>['access'=> 'admin'], 'admin/site/theme'=>['access'=> 'admin'], 'admin/site/unlock_upgrade'=>['access'=> 'admin'], 'admin/site/settings'=>['access'=> 'admin'], 'admin/upgrade'=>['access'=> 'admin'], 'admin/upgrade/reset'=>['access'=> 'admin'], 'admin/user/ban'=>['access'=> 'admin'], 'admin/user/bulk/ban'=>['access'=> 'admin'], 'admin/user/bulk/delete'=>['access'=> 'admin'], 'admin/user/bulk/unban'=>['access'=> 'admin'], 'admin/user/bulk/validate'=>['access'=> 'admin'], 'admin/user/change_email'=>['access'=> 'admin'], 'admin/user/delete'=>['access'=> 'admin'], 'admin/user/login_as'=>['access'=> 'admin'], 'admin/user/logout_as'=>[], 'admin/user/makeadmin'=>['access'=> 'admin'], 'admin/user/resetpassword'=>['access'=> 'admin'], 'admin/user/removeadmin'=>['access'=> 'admin'], 'admin/user/unban'=>['access'=> 'admin'], 'admin/user/validate'=>['access'=> 'admin'], 'annotation/delete'=>[], 'avatar/upload'=>[], 'comment/save'=>[], 'diagnostics/download'=>['access'=> 'admin'], 'entity/chooserestoredestination'=>[], 'entity/delete'=>[], 'entity/mute'=>[], 'entity/restore'=>[], 'entity/subscribe'=>[], 'entity/trash'=>[], 'entity/unmute'=>[], 'entity/unsubscribe'=>[], 'login'=>['access'=> 'logged_out'], 'logout'=>[], 'notifications/mute'=>['access'=> 'public'], 'plugins/settings/remove'=>['access'=> 'admin'], 'plugins/settings/save'=>['access'=> 'admin'], 'plugins/usersettings/save'=>[], 'register'=>['access'=> 'logged_out', 'middleware'=>[\Elgg\Router\Middleware\RegistrationAllowedGatekeeper::class,],], 'river/delete'=>[], 'settings/notifications'=>[], 'settings/notifications/subscriptions'=>[], 'user/changepassword'=>['access'=> 'public'], 'user/requestnewpassword'=>['access'=> 'public'], 'useradd'=>['access'=> 'admin'], 'usersettings/save'=>[], 'widgets/add'=>[], 'widgets/delete'=>[], 'widgets/move'=>[], 'widgets/save'=>[],]
Definition: actions.php:73
$attachments
Outputs attachments.
Definition: attachments.php:9
foreach($categories as $key=> $category) $body
Definition: categories.php:38
Email attachment.
Definition: Attachment.php:11
Email message.
Definition: Email.php:14
createEntityMessageID(\ElggEntity $entity, bool $add_microtime=false)
Create a Message-ID header string for the given entity.
Definition: Email.php:345
addAttachment(mixed $attachment)
Add an attachment.
Definition: Email.php:312
setBody(string $body='')
Sets the email message body.
Definition: Email.php:234
getSubject()
Returns the subject.
Definition: Email.php:223
getSender()
Returns sender.
Definition: Email.php:111
setFrom(Address $from)
Sets sender address.
Definition: Email.php:127
addHeader(string $name, mixed $value)
Adds/replaces an HTTP/IMF header.
Definition: Email.php:277
setCc(mixed $recipient)
Sets recipient address in cc.
Definition: Email.php:169
getAttachments()
Get all attachments.
Definition: Email.php:332
getFrom()
Returns sender address.
Definition: Email.php:137
static factory(array $options=[])
Create an email instance form an array of options.
Definition: Email.php:63
setTo(mixed $recipient)
Sets recipient address.
Definition: Email.php:148
getHeaders()
Returns headers.
Definition: Email.php:299
getBody()
Returns email body.
Definition: Email.php:244
getCc()
Returns recipient address from cc.
Definition: Email.php:179
setSender(mixed $sender)
Sets email sender.
Definition: Email.php:100
setHeaders(array $headers=[])
Replaces header bag.
Definition: Email.php:289
getTo()
Returns recipient address.
Definition: Email.php:158
setBcc(mixed $recipient)
Sets recipient address in bcc.
Definition: Email.php:190
getBcc()
Returns recipient address from bcc.
Definition: Email.php:200
setParams(array $params=[])
Sets additional params.
Definition: Email.php:255
prepareRecipients(mixed $recipients)
Converts mixed input to an array of Symfony address instances.
Definition: Email.php:402
static prepareFrom(mixed $from)
Converts mixed input to an instance of \Symfony\Component\Mime\Address.
Definition: Email.php:365
getParams()
Returns additional params.
Definition: Email.php:265
setSubject(string $subject='')
Sets email subject.
Definition: Email.php:211
Exception thrown if an argument is not of the expected type.
elgg_get_site_url()
Get the URL for the current (or specified) site, ending with "/".
if($who_can_change_language==='nobody') elseif($who_can_change_language==='admin_only' &&!elgg_is_admin_logged_in()) $options
Definition: language.php:20
$subject
HTML body of an email.
Definition: body.php:11
if($item instanceof \ElggEntity) elseif($item instanceof \ElggRiverItem) elseif($item instanceof \ElggRelationship) elseif(is_callable([ $item, 'getType']))
Definition: item.php:48
elgg_log($message, $level=\Psr\Log\LogLevel::NOTICE)
Log a message.
Definition: elgglib.php:94
_elgg_services()
Get the global service provider.
Definition: elgglib.php:343
elgg_extract($key, $array, $default=null, bool $strict=true)
Checks for $array[$key] and returns its value if it exists, else returns $default.
Definition: elgglib.php:246
elgg_get_site_entity()
Get the current site entity.
Definition: entities.php:99
$value
Definition: generic.php:51
elgg_echo(string $message_key, array $args=[], string $language='')
Elgg language module Functions to manage language and translations.
Definition: languages.php:17
elgg_substr()
Wrapper function for mb_substr().
Definition: mb_wrapper.php:195
$headers
Definition: section.php:21
if(parse_url(elgg_get_site_url(), PHP_URL_PATH) !=='/') if(file_exists(elgg_get_root_path() . 'robots.txt'))
Set robots.txt.
Definition: robots.php:10