]> git.agnieray.net Git - galette.git/blob - galette/lib/Galette/Core/Mailing.php
Remove 'svn' lines
[galette.git] / galette / lib / Galette / Core / Mailing.php
1 <?php
2
3 /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4
5 /**
6 * Mailing features
7 *
8 * PHP version 5
9 *
10 * Copyright © 2009-2014 The Galette Team
11 *
12 * This file is part of Galette (http://galette.tuxfamily.org).
13 *
14 * Galette is free software: you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation, either version 3 of the License, or
17 * (at your option) any later version.
18 *
19 * Galette is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with Galette. If not, see <http://www.gnu.org/licenses/>.
26 *
27 * @category Core
28 * @package Galette
29 *
30 * @author Johan Cwiklinski <johan@x-tnd.be>
31 * @copyright 2009-2014 The Galette Team
32 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
33 * @link http://galette.tuxfamily.org
34 * @since Available since 0.7dev - 2009-03-07
35 */
36
37 namespace Galette\Core;
38
39 use Analog\Analog;
40 use Galette\Entity\Adherent;
41 use Galette\IO\File;
42
43 /**
44 * Mailing features
45 *
46 * @category Core
47 * @name Mailing
48 * @package Galette
49 * @author Johan Cwiklinski <johan@x-tnd.be>
50 * @copyright 2009-2014 The Galette Team
51 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL License 3.0 or (at your option) any later version
52 * @link http://galette.tuxfamily.org
53 * @since Available since 0.7dev - 2009-03-07
54 */
55 class Mailing extends GaletteMail
56 {
57 const STEP_START = 0;
58 const STEP_PREVIEW = 1;
59 const STEP_SEND = 2;
60 const STEP_SENT = 3;
61
62 const MIME_HTML = 'text/html';
63 const MIME_TEXT = 'text/plain';
64 const MIME_DEFAULT = self::MIME_TEXT;
65
66 private $id;
67
68 private $unreachables = array();
69 private $mrecipients = array();
70 private $current_step;
71
72 private $mime_type;
73
74 private $tmp_path;
75 private $history_id;
76
77 /**
78 * Default constructor
79 *
80 * @param Preferences $preferences Preferences instance
81 * @param array $members An array of members
82 * @param int $id Identifier, defaults to null
83 */
84 public function __construct(Preferences $preferences, $members, $id = null)
85 {
86 parent::__construct($preferences);
87 if ($id !== null) {
88 $this->id = $id;
89 } else {
90 $this->generateNewId();
91 }
92 $this->current_step = self::STEP_START;
93 $this->mime_type = self::MIME_DEFAULT;
94 /** TODO: add a preference that propose default mime-type to use,
95 then init it here */
96 if ($members !== null) {
97 //Check which members have a valid email address and which have not
98 $this->setRecipients($members);
99 }
100 $this->loadAttachments();
101 }
102
103 /**
104 * Generate new mailing id and temporary path
105 *
106 * @return void
107 */
108 private function generateNewId()
109 {
110 global $zdb;
111
112 $pass = new Password($zdb);
113 $this->id = $pass->makeRandomPassword(30);
114 $this->generateTmpPath($this->id);
115 }
116
117 /**
118 * Generate temporary path
119 *
120 * @param string $id Random id, defautls to null
121 *
122 * @return void
123 */
124 private function generateTmpPath($id = null)
125 {
126 if ($id === null) {
127 global $zdb;
128
129 $pass = new Password($zdb);
130 $id = $pass->makeRandomPassword(30);
131 }
132 $this->tmp_path = GALETTE_ATTACHMENTS_PATH . '/' . $id;
133 }
134
135 /**
136 * Load mailing attachments
137 *
138 * @return void
139 */
140 private function loadAttachments()
141 {
142 $dir = '';
143 if (
144 isset($this->tmp_path)
145 && trim($this->tmp_path) !== ''
146 ) {
147 $dir = $this->tmp_path;
148 } else {
149 $dir = GALETTE_ATTACHMENTS_PATH . $this->id . '/';
150 }
151
152 $files = glob($dir . '*.*');
153 foreach ($files as $file) {
154 $f = new File($dir);
155 $f->setFileName(str_replace($dir, '', $file));
156 $this->attachments[] = $f;
157 }
158 }
159
160 /**
161 * Loads a mailing from history
162 *
163 * @param ResultSet $rs Mailing entry
164 * @param boolean $new True if we create a 'new' mailing,
165 * false otherwise (from preview for example)
166 *
167 * @return boolean
168 */
169 public function loadFromHistory($rs, $new = true)
170 {
171 global $zdb;
172
173 $orig_recipients = unserialize($rs->mailing_recipients);
174
175 $_recipients = array();
176 $mdeps = ['parent' => true];
177 foreach ($orig_recipients as $k => $v) {
178 $m = new Adherent($zdb, $k, $mdeps);
179 $_recipients[] = $m;
180 }
181 $this->setRecipients($_recipients);
182 $this->subject = $rs->mailing_subject;
183 $this->message = $rs->mailing_body;
184 if ($rs->mailing_sender_name !== null || $rs->mailing_sender_address !== null) {
185 $this->setSender(
186 $rs->mailing_sender_name,
187 $rs->mailing_sender_address
188 );
189 }
190 //if mailing has already been sent, generate a new id and copy attachments
191 if ($rs->mailing_sent && $new) {
192 $this->generateNewId();
193 $this->copyAttachments($rs->mailing_id);
194 } else {
195 $this->tmp_path = null;
196 $this->id = $rs->mailing_id;
197 if (!$this->attachments) {
198 $this->loadAttachments();
199 }
200 $this->history_id = $rs->mailing_id;
201 }
202 }
203
204 /**
205 * Copy attachments from another mailing
206 *
207 * @param int $id Original mailing id
208 *
209 * @return void
210 */
211 private function copyAttachments($id)
212 {
213 $source_dir = GALETTE_ATTACHMENTS_PATH . $id . '/';
214 $dest_dir = GALETTE_ATTACHMENTS_PATH . $this->id . '/';
215
216 if (file_exists($source_dir)) {
217 if (file_exists($dest_dir)) {
218 throw new \RuntimeException(
219 str_replace(
220 '%s',
221 $this->id,
222 'Attachments directory already exists for mailing %s!'
223 )
224 );
225 } else {
226 //create directory
227 mkdir($dest_dir);
228 //copy attachments from source mailing and populate attachments
229 $this->attachments = array();
230 $files = glob($source_dir . '*.*');
231 foreach ($files as $file) {
232 $f = new File($source_dir);
233 $f->setFileName(str_replace($source_dir, '', $file));
234 $f->copyTo($dest_dir);
235 $this->attachments[] = $f;
236 }
237 }
238 } else {
239 Analog::log(
240 'No attachments in source directory',
241 Analog::DEBUG
242 );
243 }
244 }
245
246 /**
247 * Apply final header to email and send it :-)
248 *
249 * @return GaletteMail::MAIL_ERROR|GaletteMail::MAIL_SENT
250 */
251 public function send()
252 {
253 $m = array();
254 foreach ($this->mrecipients as $member) {
255 $email = $member->getEmail();
256 $m[$email] = $member->sname;
257 }
258 parent::setRecipients($m);
259 return parent::send();
260 }
261
262 /**
263 * Set mailing recipients
264 *
265 * @param array $members Array of Adherent objects
266 *
267 * @return void
268 */
269 public function setRecipients($members)
270 {
271 $m = array();
272 $this->mrecipients = array();
273 $this->unreachables = array();
274
275 foreach ($members as $member) {
276 $email = $member->getEmail();
277
278 if (trim($email) != '' && self::isValidEmail($email)) {
279 if (!in_array($member, $this->mrecipients)) {
280 $this->mrecipients[] = $member;
281 }
282 $m[$email] = $member->sname;
283 } else {
284 if (!in_array($member, $this->unreachables)) {
285 $this->unreachables[] = $member;
286 }
287 }
288 }
289 parent::setRecipients($m);
290 }
291
292 /**
293 * Store maling attachments
294 *
295 * @param array $files Array of uploaded files to store
296 *
297 * @return true|int error code
298 */
299 public function store($files)
300 {
301 if ($this->tmp_path === null) {
302 $this->generateTmpPath();
303 }
304
305 if (!file_exists($this->tmp_path)) {
306 //directory does not exists, create it
307 mkdir($this->tmp_path);
308 }
309
310 if (!is_dir($this->tmp_path)) {
311 throw new \RuntimeException(
312 $this->tmp_path . ' should be a directory!'
313 );
314 }
315
316 //store files
317 $attachment = new File($this->tmp_path);
318 $res = $attachment->store($files);
319 if ($res < 0) {
320 return $res;
321 } else {
322 $this->attachments[] = $attachment;
323 }
324
325 return true;
326 }
327
328 /**
329 * Move attachments with final id once mailing has been stored
330 *
331 * @param int $id Mailing history id
332 *
333 * @return boolean
334 */
335 public function moveAttachments($id)
336 {
337 if (
338 isset($this->tmp_path)
339 && trim($this->tmp_path) !== ''
340 && count($this->attachments) > 0
341 ) {
342 foreach ($this->attachments as &$attachment) {
343 $old_path = $attachment->getDestDir() . $attachment->getFileName();
344 $new_path = GALETTE_ATTACHMENTS_PATH . $this->id . '/' .
345 $attachment->getFileName();
346 if (!file_exists(GALETTE_ATTACHMENTS_PATH . $this->id)) {
347 mkdir(GALETTE_ATTACHMENTS_PATH . $this->id);
348 }
349 $moved = rename($old_path, $new_path);
350 if ($moved) {
351 $attachment->setDestDir(GALETTE_ATTACHMENTS_PATH);
352 }
353 }
354 rmdir($this->tmp_path);
355 $this->tmp_path = null;
356 }
357 }
358
359 /**
360 * Remove specified attachment
361 *
362 * @param string $name Filename
363 *
364 * @return void
365 */
366 public function removeAttachment($name)
367 {
368 $to_remove = null;
369 if (
370 isset($this->tmp_path)
371 && trim($this->tmp_path) !== ''
372 && file_exists($this->tmp_path)
373 ) {
374 $to_remove = $this->tmp_path;
375 } elseif (file_exists(GALETTE_ATTACHMENTS_PATH . $this->id)) {
376 $to_remove = GALETTE_ATTACHMENTS_PATH . $this->id;
377 }
378
379 if ($to_remove !== null) {
380 $to_remove .= '/' . $name;
381
382 if (!$this->attachments) {
383 $this->loadAttachments();
384 }
385
386 if (file_exists($to_remove)) {
387 $i = 0;
388 foreach ($this->attachments as $att) {
389 if ($att->getFileName() == $name) {
390 unset($this->attachments[$i]);
391 unlink($to_remove);
392 break;
393 }
394 $i++;
395 }
396 } else {
397 Analog::log(
398 str_replace(
399 '%file',
400 $name,
401 'File %file does not exists and cannot be removed!'
402 ),
403 Analog::WARNING
404 );
405 }
406 } else {
407 throw new \RuntimeException(
408 'Unable to get attachments path!'
409 );
410 }
411 }
412
413 /**
414 * Remove mailing attachments
415 *
416 * @param boolean $temp Remove only tmporary attachments,
417 * to avoid history breaking
418 *
419 * @return void
420 */
421 public function removeAttachments($temp = false)
422 {
423 $to_remove = null;
424 if (
425 isset($this->tmp_path)
426 && trim($this->tmp_path) !== ''
427 && file_exists($this->tmp_path)
428 ) {
429 $to_remove = $this->tmp_path;
430 } elseif (file_exists(GALETTE_ATTACHMENTS_PATH . $this->id)) {
431 if ($temp === true) {
432 return false;
433 }
434 $to_remove = GALETTE_ATTACHMENTS_PATH . $this->id;
435 }
436
437 if ($to_remove !== null) {
438 $rdi = new \RecursiveDirectoryIterator(
439 $to_remove,
440 \FilesystemIterator::SKIP_DOTS
441 );
442 $contents = new \RecursiveIteratorIterator(
443 $rdi,
444 \RecursiveIteratorIterator::CHILD_FIRST
445 );
446 foreach ($contents as $path) {
447 if ($path->isFile()) {
448 unlink($path->getPathname());
449 } else {
450 rmdir($path->getPathname());
451 }
452 }
453 rmdir($to_remove);
454 }
455 }
456
457 /**
458 * Return textual error message
459 *
460 * @param int $code The error code
461 *
462 * @return string Localized message
463 */
464 public function getAttachmentErrorMessage($code)
465 {
466 $f = new File($this->tmp_path);
467 return $f->getErrorMessage($code);
468 }
469
470 /**
471 * Does mailing already exists in history?
472 *
473 * @return boolean
474 */
475 public function existsInHistory()
476 {
477 return isset($this->history_id);
478 }
479
480 /**
481 * Global getter method
482 *
483 * @param string $name name of the property we want to retrive
484 *
485 * @return false|object the called property
486 */
487 public function __get($name)
488 {
489 $forbidden = array('ordered');
490 if (!in_array($name, $forbidden)) {
491 switch ($name) {
492 case 'alt_message':
493 return $this->cleanedHtml();
494 break;
495 case 'step':
496 return $this->current_step;
497 break;
498 case 'subject':
499 return $this->getSubject();
500 break;
501 case 'message':
502 return $this->getMessage();
503 break;
504 case 'wrapped_message':
505 return $this->getWrappedMessage();
506 break;
507 case 'html':
508 return $this->isHTML();
509 break;
510 case 'mail':
511 case '_mail':
512 return $this->getPhpMailer();
513 break;
514 case 'errors':
515 return $this->getErrors();
516 break;
517 case 'recipients':
518 return $this->mrecipients;
519 break;
520 case 'tmp_path':
521 if (isset($this->tmp_path) && trim($this->tmp_path) !== '') {
522 return $this->tmp_path;
523 } else {
524 //no attachments
525 return false;
526 }
527 break;
528 case 'attachments':
529 return $this->attachments;
530 break;
531 case 'sender_name':
532 return $this->getSenderName();
533 break;
534 case 'sender_address':
535 return $this->getSenderAddress();
536 break;
537 default:
538 Analog::log(
539 '[' . get_class($this) . 'Trying to get ' . $name,
540 Analog::DEBUG
541 );
542 return $this->$name;
543 break;
544 }
545 } else {
546 Analog::log(
547 '[' . get_class($this) . 'Unable to get ' . $name,
548 Analog::ERROR
549 );
550 return false;
551 }
552 }
553
554 /**
555 * Global setter method
556 *
557 * @param string $name name of the property we want to assign a value to
558 * @param object $value a relevant value for the property
559 *
560 * @return void
561 */
562 public function __set($name, $value)
563 {
564 switch ($name) {
565 case 'subject':
566 $this->setSubject($value);
567 break;
568 case 'message':
569 $this->setMessage($value);
570 break;
571 case 'html':
572 if (is_bool($value)) {
573 $this->isHTML($value);
574 } else {
575 Analog::log(
576 '[' . get_class($this) . '] Value for field `' . $name .
577 '` should be boolean - (' . gettype($value) . ')' .
578 $value . ' given',
579 Analog::WARNING
580 );
581 }
582 break;
583 case 'current_step':
584 if (
585 is_int($value)
586 && ($value == self::STEP_START
587 || $value == self::STEP_PREVIEW
588 || $value == self::STEP_SEND
589 || $value == self::STEP_SENT)
590 ) {
591 $this->current_step = (int)$value;
592 } else {
593 Analog::log(
594 '[' . get_class($this) . '] Value for field `' . $name .
595 '` should be integer and know - (' . gettype($value) . ')' .
596 $value . ' given',
597 Analog::WARNING
598 );
599 }
600 break;
601 case 'id':
602 $this->id = $value;
603 break;
604 default:
605 Analog::log(
606 '[' . get_class($this) . '] Unable to set proprety `' . $name . '`',
607 Analog::WARNING
608 );
609 return false;
610 break;
611 }
612 }
613 }