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