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->setFrom(self::prepareFrom($from));
75  $email->setTo($to);
76  $email->setCc($cc);
77  $email->setBcc($bcc);
78  $email->setSubject($subject);
79  $email->setBody($body);
80  $email->setParams($params);
81  $email->setHeaders($headers);
82 
83  if (isset($params['attachments']) && is_array($params['attachments'])) {
84  foreach ($params['attachments'] as $attachment) {
85  $email->addAttachment($attachment);
86  }
87  }
88 
89  return $email;
90  }
91 
99  public function setSender(mixed $sender): self {
100  $prepared_sender = $this->prepareRecipients($sender);
101  $this->sender = !empty($prepared_sender) ? $prepared_sender[0] : null;
102  return $this;
103  }
104 
110  public function getSender(): Address {
111  if (isset($this->sender)) {
112  return $this->sender;
113  }
114 
116  return new Address($site->getEmailAddress(), $site->getDisplayName());
117  }
118 
126  public function setFrom(Address $from): self {
127  $this->from = $from;
128  return $this;
129  }
130 
136  public function getFrom(): ?Address {
137  return $this->from;
138  }
139 
147  public function setTo(mixed $recipient): self {
148  $this->to = $this->prepareRecipients($recipient);
149  return $this;
150  }
151 
157  public function getTo(): array {
158  return $this->to;
159  }
160 
168  public function setCc(mixed $recipient): self {
169  $this->cc = $this->prepareRecipients($recipient);
170  return $this;
171  }
172 
178  public function getCc(): array {
179  return $this->cc;
180  }
181 
189  public function setBcc(mixed $recipient): self {
190  $this->bcc = $this->prepareRecipients($recipient);
191  return $this;
192  }
193 
199  public function getBcc(): array {
200  return $this->bcc;
201  }
202 
210  public function setSubject(string $subject = ''): self {
211  $this->subject = $subject;
212  return $this;
213  }
214 
222  public function getSubject(): string {
223  return elgg_substr($this->subject, 0, (int) _elgg_services()->config->email_subject_limit);
224  }
225 
233  public function setBody(string $body = ''): self {
234  $this->body = $body;
235  return $this;
236  }
237 
243  public function getBody(): ?string {
244  return $this->body;
245  }
246 
254  public function setParams(array $params = []): self {
255  $this->params = $params;
256  return $this;
257  }
258 
264  public function getParams(): array {
265  return $this->params;
266  }
267 
276  public function addHeader(string $name, mixed $value): self {
277  $this->headers[$name] = $value;
278  return $this;
279  }
280 
288  public function setHeaders(array $headers = []): self {
289  $this->headers = $headers;
290  return $this;
291  }
292 
298  public function getHeaders(): array {
299  return $this->headers;
300  }
301 
311  public function addAttachment(mixed $attachment): self {
312  if ($attachment instanceof DataPart) {
313  $this->attachments[] = $attachment;
314  return $this;
315  }
316 
317  try {
318  $this->attachments[] = Attachment::factory($attachment);
319  } catch (InvalidArgumentException $e) {
320  elgg_log($e->getMessage(), LogLevel::ERROR);
321  }
322 
323  return $this;
324  }
325 
331  public function getAttachments(): array {
332  return $this->attachments;
333  }
334 
344  public function createEntityMessageID(\ElggEntity $entity, bool $add_microtime = false): string {
345  $microtime = '';
346  if ($add_microtime) {
347  $microtime = '.' . microtime(true);
348  }
349 
350  $hostname = parse_url(elgg_get_site_url(), PHP_URL_HOST);
351  $urlPath = parse_url(elgg_get_site_url(), PHP_URL_PATH);
352 
353  return "{$urlPath}.entity.{$entity->guid}{$microtime}@{$hostname}";
354  }
355 
364  protected static function prepareFrom(mixed $from): Address {
365  if (empty($from)) {
366  // get the site email address
368  $from = new Address($site->getEmailAddress(), $site->getDisplayName());
369  } elseif ($from instanceof \ElggSite) {
370  // use site email address
371  $from = new Address($from->getEmailAddress(), $from->getDisplayName());
372  } elseif ($from instanceof \ElggEntity) {
373  // If there's an email address, use it - but only if it's not from a user.
374  if (!$from instanceof \ElggUser && !empty($from->email)) {
375  $from = new Address($from->email, $from->getDisplayName());
376  } else {
377  // get the site email address
379  $from_display = elgg_echo('notification:method:email:from', [$from->getDisplayName(), $site->getDisplayName()]);
380  $from = new Address($site->getEmailAddress(), $from_display);
381  }
382  } elseif (is_string($from)) {
383  $from = Address::create($from);
384  }
385 
386  if (!$from instanceof Address) {
387  throw new InvalidArgumentException('From address is not in a valid format');
388  }
389 
390  return $from;
391  }
392 
401  protected function prepareRecipients(mixed $recipients): array {
402  if (empty($recipients)) {
403  return [];
404  }
405 
406  if (!is_array($recipients)) {
407  $recipients = [$recipients];
408  }
409 
410  $result = [];
411  foreach ($recipients as $recipient) {
412  if ($recipient instanceof Address) {
413  $result[] = $recipient;
414  continue;
415  }
416 
417  if ($recipient instanceof \ElggSite) {
418  $recipient = new Address($recipient->getEmailAddress(), $recipient->getDisplayName());
419  } elseif ($recipient instanceof \ElggEntity && !empty($recipient->email)) {
420  $recipient = new Address($recipient->email, $recipient->getDisplayName());
421  } elseif (is_string($recipient)) {
422  $recipient = Address::create($recipient);
423  }
424 
425  if (!$recipient instanceof Address) {
426  throw new InvalidArgumentException('Recipient address is not in a valid format');
427  }
428 
429  $result[] = $recipient;
430  }
431 
432  return $result;
433  }
434 }
$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/clear'=>['access'=> 'admin'], 'admin/site/cache/invalidate'=>['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', 'controller'=> \Elgg\Diagnostics\DownloadController::class,], '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:76
$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:344
addAttachment(mixed $attachment)
Add an attachment.
Definition: Email.php:311
setBody(string $body='')
Sets the email message body.
Definition: Email.php:233
getSubject()
Returns the subject.
Definition: Email.php:222
getSender()
Returns sender.
Definition: Email.php:110
setFrom(Address $from)
Sets sender address.
Definition: Email.php:126
addHeader(string $name, mixed $value)
Adds/replaces an HTTP/IMF header.
Definition: Email.php:276
setCc(mixed $recipient)
Sets recipient address in cc.
Definition: Email.php:168
getAttachments()
Get all attachments.
Definition: Email.php:331
getFrom()
Returns sender address.
Definition: Email.php:136
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:147
getHeaders()
Returns headers.
Definition: Email.php:298
getBody()
Returns email body.
Definition: Email.php:243
getCc()
Returns recipient address from cc.
Definition: Email.php:178
setSender(mixed $sender)
Sets email sender.
Definition: Email.php:99
setHeaders(array $headers=[])
Replaces header bag.
Definition: Email.php:288
getTo()
Returns recipient address.
Definition: Email.php:157
setBcc(mixed $recipient)
Sets recipient address in bcc.
Definition: Email.php:189
getBcc()
Returns recipient address from bcc.
Definition: Email.php:199
setParams(array $params=[])
Sets additional params.
Definition: Email.php:254
prepareRecipients(mixed $recipients)
Converts mixed input to an array of Symfony address instances.
Definition: Email.php:401
static prepareFrom(mixed $from)
Converts mixed input to an instance of \Symfony\Component\Mime\Address.
Definition: Email.php:364
getParams()
Returns additional params.
Definition: Email.php:264
setSubject(string $subject='')
Sets email subject.
Definition: Email.php:210
Exception thrown if an argument is not of the expected type.
if(count($css_vars)< 2) $options
elgg_get_site_url()
Get the URL for the current (or specified) site, ending with "/".
$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:347
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
$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_get_site_entity()
Get the current site entity.
Definition: entities.php:99
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