4 * Copyright © 2003-2024 The Galette Team
6 * This file is part of Galette (https://galette.eu).
8 * Galette is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * Galette is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with Galette. If not, see <http://www.gnu.org/licenses/>.
22 namespace Galette\Core
;
26 use Galette\Entity\Adherent
;
28 use Laminas\Db\ResultSet\ResultSet
;
33 * @author Johan Cwiklinski <johan@x-tnd.be>
35 * @property string $subject
36 * @property string $message
37 * @property boolean $html
38 * @property integer $current_step
39 * @property-read integer $step
40 * @property integer|string $id
41 * @property-read string $alt_message
42 * @property-read string $wrapped_message
43 * @property-read PHPMailer\PHPMailer\PHPMailer $mail
44 * @property-read array $errors
45 * @property-read array $recipients
46 * @property-read array $unreachables
47 * @property-read string|false $tmp_path
48 * @property array $attachments
49 * @property-read string $sender_name
50 * @property-read string $sender_address
51 * @property integer $history_id
53 class Mailing
extends GaletteMail
55 public const STEP_START
= 0;
56 public const STEP_PREVIEW
= 1;
57 public const STEP_SEND
= 2;
58 public const STEP_SENT
= 3;
60 public const MIME_HTML
= 'text/html';
61 public const MIME_TEXT
= 'text/plain';
62 public const MIME_DEFAULT
= self
::MIME_TEXT
;
64 private string|
int $id;
66 /** @var array<int, Adherent> */
67 private array $unreachables = array();
68 /** @var array<int, Adherent> */
69 private array $mrecipients = array();
70 private int $current_step;
72 private string $mime_type;
74 private ?
string $tmp_path;
75 private int $history_id;
80 * @param Preferences $preferences Preferences instance
81 * @param array<int, Adherent> $members An array of members
82 * @param ?integer $id Identifier, defaults to null
84 public function __construct(Preferences
$preferences, array $members = [], int $id = null)
86 parent
::__construct($preferences);
87 $this->id
= $id ??
$this->generateNewId();
89 $this->current_step
= self
::STEP_START
;
90 $this->mime_type
= self
::MIME_DEFAULT
;
91 /** TODO: add a preference that propose default mime-type to use,
93 if (count($members)) {
94 //Check which members have a valid email address and which have not
95 $this->setRecipients($members);
97 $this->loadAttachments();
101 * Generate new mailing id and temporary path
105 private function generateNewId(): string
108 $chars = 'abcdefghjkmnpqrstuvwxyz0123456789';
111 while ($i <= $size - 1) {
112 $num = mt_rand(0, strlen($chars) - 1) %
strlen($chars);
113 $id .= substr($chars, $num, 1);
118 $this->generateTmpPath($this->id
);
123 * Generate temporary path
125 * @param ?string $id Random id, defaults to null
129 private function generateTmpPath(string $id = null): void
132 $id = $this->generateNewId();
134 $this->tmp_path
= GALETTE_ATTACHMENTS_PATH
. '/' . $id;
138 * Load mailing attachments
142 private function loadAttachments(): void
146 isset($this->tmp_path
)
147 && trim($this->tmp_path
) !== ''
149 $dir = $this->tmp_path
;
151 $dir = GALETTE_ATTACHMENTS_PATH
. $this->id
. '/';
154 $files = glob($dir . '*.*');
155 foreach ($files as $file) {
157 $f->setFileName(str_replace($dir, '', $file));
158 $this->attachments
[] = $f;
163 * Loads a mailing from history
165 * @param ArrayObject<string, mixed> $rs Mailing entry
166 * @param boolean $new True if we create a 'new' mailing,
167 * false otherwise (from preview for example)
171 public function loadFromHistory(ArrayObject
$rs, bool $new = true): bool
176 if (Galette
::isSerialized($rs->mailing_recipients
)) {
177 $orig_recipients = unserialize($rs->mailing_recipients
);
179 $orig_recipients = Galette
::jsonDecode($rs->mailing_recipients
);
181 } catch (\Throwable
$e) {
183 'Unable to retrieve recipients for mailing ' . $rs->mailing_id
,
186 $orig_recipients = [];
189 $_recipients = array();
190 $mdeps = ['parent' => true];
191 foreach ($orig_recipients as $k => $v) {
192 $m = new Adherent($zdb, $k, $mdeps);
195 $this->setRecipients($_recipients);
196 $this->subject
= $rs->mailing_subject
;
197 $this->message
= $rs->mailing_body
;
198 $this->html
= $this->message
!= strip_tags($this->message
) ?
true : false;
199 if ($rs->mailing_sender_name
!== null ||
$rs->mailing_sender_address
!== null) {
201 $rs->mailing_sender_name
,
202 $rs->mailing_sender_address
205 //if mailing has already been sent, generate a new id and copy attachments
206 if ($rs->mailing_sent
&& $new) {
207 $this->generateNewId();
208 $this->copyAttachments($rs->mailing_id
);
210 $this->tmp_path
= null;
211 $this->id
= $rs->mailing_id
;
212 if (!$this->attachments
) {
213 $this->loadAttachments();
215 $this->history_id
= $rs->mailing_id
;
221 * Copy attachments from another mailing
223 * @param int $id Original mailing id
227 private function copyAttachments(int $id): void
229 $source_dir = GALETTE_ATTACHMENTS_PATH
. $id . '/';
230 $dest_dir = GALETTE_ATTACHMENTS_PATH
. $this->id
. '/';
232 if (file_exists($source_dir)) {
233 if (file_exists($dest_dir)) {
234 throw new \
RuntimeException(
238 'Attachments directory already exists for mailing %s!'
244 //copy attachments from source mailing and populate attachments
245 $this->attachments
= array();
246 $files = glob($source_dir . '*.*');
247 foreach ($files as $file) {
248 $f = new File($source_dir);
249 $f->setFileName(str_replace($source_dir, '', $file));
250 $f->copyTo($dest_dir);
251 $this->attachments
[] = $f;
256 'No attachments in source directory',
263 * Apply final header to email and send it :-)
267 public function send(): int
270 foreach ($this->mrecipients
as $member) {
271 $email = $member->getEmail();
272 $m[$email] = $member->sname
;
274 parent
::setRecipients($m);
275 return parent
::send();
279 * Set mailing recipients
281 * @phpstan-ignore-next-line
282 * @param array<int, Adherent> $members Array of Adherent objects
286 public function setRecipients(array $members): bool
289 $this->mrecipients
= array();
290 $this->unreachables
= array();
292 foreach ($members as $member) {
293 $email = $member->getEmail();
295 if (trim($email) != '' && self
::isValidEmail($email)) {
296 if (!in_array($member, $this->mrecipients
)) {
297 $this->mrecipients
[] = $member;
299 $m[$email] = $member->sname
;
301 if (!in_array($member, $this->unreachables
)) {
302 $this->unreachables
[] = $member;
306 return parent
::setRecipients($m);
310 * Store maling attachments
312 * @param array<string, string|int> $files Array of uploaded files to store
314 * @return true|int error code
316 public function store(array $files): bool|
int
318 if ($this->tmp_path
=== null) {
319 $this->generateTmpPath();
322 if (!file_exists($this->tmp_path
)) {
323 //directory does not exist, create it
324 mkdir($this->tmp_path
);
327 if (!is_dir($this->tmp_path
)) {
328 throw new \
RuntimeException(
329 $this->tmp_path
. ' should be a directory!'
334 $attachment = new File($this->tmp_path
);
335 $res = $attachment->store($files);
339 $this->attachments
[] = $attachment;
346 * Move attachments with final id once mailing has been stored
348 * @param int $id Mailing history id
352 public function moveAttachments(int $id): void
355 isset($this->tmp_path
)
356 && trim($this->tmp_path
) !== ''
357 && count($this->attachments
) > 0
359 foreach ($this->attachments
as &$attachment) {
360 $old_path = $attachment->getDestDir() . $attachment->getFileName();
361 $new_path = GALETTE_ATTACHMENTS_PATH
. $id . '/' .
362 $attachment->getFileName();
363 if (!file_exists(GALETTE_ATTACHMENTS_PATH
. $id)) {
364 mkdir(GALETTE_ATTACHMENTS_PATH
. $id);
366 $moved = rename($old_path, $new_path);
368 $attachment->setDestDir(GALETTE_ATTACHMENTS_PATH
);
371 rmdir($this->tmp_path
);
372 $this->tmp_path
= null;
377 * Remove specified attachment
379 * @param string $name Filename
383 public function removeAttachment(string $name): void
387 isset($this->tmp_path
)
388 && trim($this->tmp_path
) !== ''
389 && file_exists($this->tmp_path
)
391 $to_remove = $this->tmp_path
;
392 } elseif (file_exists(GALETTE_ATTACHMENTS_PATH
. $this->id
)) {
393 $to_remove = GALETTE_ATTACHMENTS_PATH
. $this->id
;
396 if ($to_remove !== null) {
397 $to_remove .= '/' . $name;
399 if (!$this->attachments
) {
400 $this->loadAttachments();
403 if (file_exists($to_remove)) {
405 foreach ($this->attachments
as $att) {
406 if ($att->getFileName() == $name) {
407 unset($this->attachments
[$i]);
418 'File %file does not exists and cannot be removed!'
424 throw new \
RuntimeException(
425 'Unable to get attachments path!'
431 * Remove mailing attachments
433 * @param boolean $temp Remove only temporary attachments,
434 * to avoid history breaking
438 public function removeAttachments(bool $temp = false): bool
442 isset($this->tmp_path
)
443 && trim($this->tmp_path
) !== ''
444 && file_exists($this->tmp_path
)
446 $to_remove = $this->tmp_path
;
447 } elseif (file_exists(GALETTE_ATTACHMENTS_PATH
. $this->id
)) {
448 if ($temp === true) {
451 $to_remove = GALETTE_ATTACHMENTS_PATH
. $this->id
;
454 if ($to_remove !== null) {
455 $rdi = new \
RecursiveDirectoryIterator(
457 \FilesystemIterator
::SKIP_DOTS
459 $contents = new \
RecursiveIteratorIterator(
461 \RecursiveIteratorIterator
::CHILD_FIRST
463 foreach ($contents as $path) {
464 if ($path->isFile()) {
465 unlink($path->getPathname());
467 rmdir($path->getPathname());
476 * Return textual error message
478 * @param int $code The error code
480 * @return string Localized message
482 public function getAttachmentErrorMessage(int $code): string
484 $f = new File($this->tmp_path
);
485 return $f->getErrorMessage($code);
489 * Does mailing already exists in history?
493 public function existsInHistory(): bool
495 return isset($this->history_id
);
499 * Global getter method
501 * @param string $name name of the property we want to retrieve
503 * @return mixed the called property
505 public function __get(string $name)
507 $forbidden = array('ordered');
508 if (!in_array($name, $forbidden)) {
511 return $this->cleanedHtml();
513 return $this->current_step
;
515 return $this->getSubject();
517 return $this->getMessage();
518 case 'wrapped_message':
519 return $this->getWrappedMessage();
521 return $this->isHTML();
523 return $this->getPhpMailer();
525 return $this->getErrors();
527 return $this->mrecipients
;
529 if (isset($this->tmp_path
) && trim($this->tmp_path
) !== '') {
530 return $this->tmp_path
;
536 return $this->attachments
;
538 return $this->getSenderName();
539 case 'sender_address':
540 return $this->getSenderAddress();
545 '[' . get_class($this) . 'Trying to get ' . $name,
552 '[' . get_class($this) . 'Unable to get ' . $name,
560 * Global isset method
561 * Required for twig to access properties via __get
563 * @param string $name name of the property we want to retrieve
567 public function __isset(string $name): bool
569 $forbidden = array('ordered');
570 if (!in_array($name, $forbidden)) {
576 case 'wrapped_message':
584 case 'sender_address':
587 return isset($this->$name);
594 * Global setter method
596 * @param string $name name of the property we want to assign a value to
597 * @param mixed $value a relevant value for the property
601 public function __set(string $name, $value): void
605 $this->setSubject($value);
608 $this->setMessage($value);
611 if (is_bool($value)) {
612 $this->isHTML($value);
615 '[' . get_class($this) . '] Value for field `' . $name .
616 '` should be boolean - (' . gettype($value) . ')' .
625 && ($value == self
::STEP_START
626 ||
$value == self
::STEP_PREVIEW
627 ||
$value == self
::STEP_SEND
628 ||
$value == self
::STEP_SENT
)
630 $this->current_step
= (int)$value;
633 '[' . get_class($this) . '] Value for field `' . $name .
634 '` should be integer and know - (' . gettype($value) . ')' .
645 '[' . get_class($this) . '] Unable to set property `' . $name . '`',