1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36:
37:
38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48:
49: class EmailDeliveryBehavior extends CBehavior {
50:
51: 52: 53: 54:
55: private $_credentials;
56:
57: 58: 59: 60:
61: private $_credId = null;
62:
63: 64: 65:
66: private $_from;
67:
68: 69: 70: 71:
72: private $_mailer;
73:
74: 75: 76: 77:
78: private $_userProfile;
79:
80: 81: 82:
83: public $status = array();
84:
85:
86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99:
100: public static function ($header,$ignoreInvalidAddresses=false) {
101:
102:
103: preg_match_all('/"(?:\\\\.|[^\\\\"])*"|[^,\s]+/', $header, $matches);
104: $tokenCount = 0;
105: $values = array();
106: foreach($matches[0] as $matchedPiece) {
107: $piece = trim($matchedPiece,',');
108: $token = "\{token_$tokenCount\}";
109: $values[$token] = $piece;
110: $tokenCount++;
111: }
112: $tokens = array_flip($values);
113: $delimiter = '-&@&-';
114: $tokenizedHeader = str_replace(',',$delimiter,strtr($header,$tokens));
115: $headerPieces = explode($delimiter,strtr($tokenizedHeader,$values));
116: $headerArray = array();
117: foreach($headerPieces as $recipient){
118: $recipient = trim($recipient);
119: if(empty($recipient))
120: continue;
121: $matches = array();
122: $emailValidator = new CEmailValidator;
123:
124:
125: if($emailValidator->validateValue($recipient)) {
126: $headerArray[] = array('', $recipient);
127: } elseif(strlen($recipient) < 255 &&
128:
129: preg_match('/^"?((?:\\\\"|[^"])*)"?\s*<(.+)>$/i', $recipient, $matches)){
130:
131:
132:
133: if(count($matches) == 3 && $emailValidator->validateValue($matches[2])){
134: $headerArray[] = array($matches[1], $matches[2]);
135: }else{
136: if (!$ignoreInvalidAddresses)
137: throw new CException(Yii::t('app', 'Invalid email address list.'));
138: }
139: }else{
140: if (!$ignoreInvalidAddresses)
141: throw new CException(Yii::t('app', 'Invalid email address list:'.$recipient));
142: }
143: }
144: return $headerArray;
145: }
146:
147: 148: 149: 150: 151:
152: public function addEmailAddresses(&$phpMail, $addresses){
153:
154: if(isset($addresses['to'])){
155: foreach($addresses['to'] as $target){
156: if(count($target) == 2)
157: $phpMail->AddAddress($target[1], $target[0]);
158: }
159: } else{
160: if(count($addresses) == 2 && !is_array($addresses[0])){
161:
162: $phpMail->AddAddress($addresses[1], $addresses[0]);
163: }else{
164: foreach($addresses as $target){
165: if(count($target) == 2)
166: $phpMail->AddAddress($target[1], $target[0]);
167: }
168: }
169: }
170: if(isset($addresses['cc'])){
171: foreach($addresses['cc'] as $target){
172: if(count($target) == 2)
173: $phpMail->AddCC($target[1], $target[0]);
174: }
175: }
176: if(isset($addresses['bcc'])){
177: foreach($addresses['bcc'] as $target){
178: if(count($target) == 2)
179: $phpMail->AddBCC($target[1], $target[0]);
180: }
181: }
182: }
183:
184: 185: 186: 187: 188:
189: public function validateFileSize ($size) {
190: if($size > (10 * 1024 * 1024)) {
191: throw new Exception(
192: "Attachment '{$attachment['filename']}' exceeds size ".
193: "limit of 10mb.");
194: }
195: return true;
196: }
197:
198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209:
210: public function deliverEmail($addresses, $subject, $message, $attachments = array(), $unsubLink = null){
211: if(YII_UNIT_TESTING && defined ('X2_DEBUG_EMAIL') && X2_DEBUG_EMAIL) {
212:
213: AuxLib::debugLog(
214: 'Faking an email delivery to address(es): '.var_export($addresses,1));
215: return $this->status = $this->getDebugStatus();
216: }
217:
218: try {
219: $phpMail = $this->mailer;
220: }catch (phpmailerException $e){
221:
222: $escalated = new phpmailerException (
223: $e->getMessage (), PHPMailer::STOP_CRITICAL);
224: $this->status['code'] = '500';
225: $this->status['exception'] = $escalated;
226: $this->status['message'] = $e->getMessage ();
227: return $this->status;
228: }
229:
230:
231:
232:
233:
234: if ($this->credentials) {
235: try {
236: $phpMail->smtpConnect ();
237: } catch (phpmailerException $e) {
238: $escalated = new phpmailerException (
239: $e->getMessage (), PHPMailer::STOP_CRITICAL);
240: $this->status['code'] = '500';
241: $this->status['exception'] = $escalated;
242: $this->status['message'] = $phpMail->ErrorInfo." ".$e->getFile()." L".$e->getLine();
243: return $this->status;
244: }
245: }
246:
247: try{
248: $this->addEmailAddresses($phpMail, $addresses);
249:
250: $phpMail->Subject = $subject;
251:
252: $phpMail->MsgHTML($message);
253:
254:
255: if($attachments){
256: foreach($attachments as $attachment){
257: $type = $attachment['type'];
258: switch ($type) {
259: case 'temp':
260: $file = 'uploads/protected/media/temp/'.$attachment['folder'].'/'.
261: $attachment['filename'];
262: if(file_exists($file))
263: if ($this->validateFileSize (filesize ($file))) {
264: $phpMail->AddAttachment($file);
265: }
266: break;
267: case 'media':
268: $file = 'uploads/protected/media/'.$attachment['folder'].'/'.
269: $attachment['filename'];
270: if(file_exists($file))
271: if ($this->validateFileSize (filesize ($file))) {
272: $phpMail->AddAttachment($file);
273: }
274: break;
275:
276: default:
277: throw new CException ('Invalid attachment type');
278: }
279: }
280: }
281:
282:
283: if (Yii::app()->settings->enableUnsubscribeHeader && !empty($unsubLink)) {
284: $phpMail->AddCustomHeader ('List-Unsubscribe:<'.$unsubLink.'>');
285: }
286: $phpMail->Send();
287:
288: $this->status['code'] = '200';
289: $this->status['exception'] = null;
290: $this->status['message'] = Yii::t('app', 'Email Sent!');
291: }catch (phpmailerException $e){
292:
293: $this->status['code'] = '500';
294: $this->status['exception'] = $e;
295: $this->status['message'] = $phpMail->ErrorInfo." ".$e->getFile()." L".$e->getLine();
296: }catch (Exception $e){
297: $this->status['code'] = '500';
298: $this->status['exception'] = $e;
299: $this->status['message'] = $e->getMessage()." ".$e->getFile()." L".$e->getLine();
300: }
301: return $this->status;
302: }
303:
304: public function clearTemporaryFiles (array $attachments = array ()) {
305: foreach($attachments as $attachment){
306: $type = $attachment['type'];
307: if($type === 'temp'){
308: $file = 'uploads/protected/media/temp/'.$attachment['folder'].'/'.
309: $attachment['filename'];
310: $folder = 'uploads/protected/media/temp/'.$attachment['folder'];
311: if(file_exists($file))
312: unlink($file);
313: if(file_exists($folder))
314: rmdir($folder);
315: TempFile::model()->deleteByPk($attachment['id']);
316: }
317: }
318: }
319:
320: 321: 322: 323:
324: public function getCredentials(){
325: if(!isset($this->_credentials)){
326: if($this->credId == Credentials::LEGACY_ID)
327: $this->_credentials = false;
328: else{
329: $cred = Credentials::model()->findByPk($this->credId);
330: $this->_credentials = empty($cred) ? false : $cred;
331: }
332: }
333: return $this->_credentials;
334: }
335:
336: public function getCredId() {
337: return $this->_credId;
338: }
339:
340: 341: 342:
343: public function getDebugStatus() {
344: return require(implode(DIRECTORY_SEPARATOR,array(
345: Yii::app()->basePath,
346: 'tests',
347: 'data',
348: 'marketing',
349: 'debugStatus.php'
350: )));
351: }
352:
353: 354: 355: 356:
357: public function getFrom(){
358: if(!isset($this->_from)) {
359: if($this->credentials) {
360: $this->_from = array(
361: 'name' => $this->credentials->auth->senderName,
362: 'address' => $this->credentials->auth->email
363: );
364: } else {
365: if(empty($this->userProfile) ||
366: $this->userProfile->username === Profile::GUEST_PROFILE_USERNAME) {
367:
368: $this->_from = array(
369: 'name' => Yii::app()->settings->appName,
370: 'address' => Yii::app()->settings->emailFromAddr
371: );
372: }else{
373:
374: $this->_from = array(
375: 'name' => $this->userProfile->fullName,
376: 'address' => $this->userProfile->emailAddress
377: );
378: }
379: }
380: }
381: return $this->_from;
382: }
383:
384: 385: 386: 387:
388: public function getMailer(){
389: if(!isset($this->_mailer)){
390: require_once(
391: realpath(Yii::app()->basePath.'/components/phpMailer/PHPMailerAutoload.php'));
392:
393:
394: $phpMail = new PHPMailer(true);
395: $phpMail->CharSet = 'utf-8';
396:
397: $cred = $this->credentials;
398: if($cred){
399: $phpMail->IsSMTP();
400: $phpMail->Host = $cred->auth->server;
401: $phpMail->Port = $cred->auth->port;
402: $phpMail->SMTPSecure = $cred->auth->security;
403: if(!empty($cred->auth->password)){
404: $phpMail->SMTPAuth = true;
405: $cred->auth->emailUser('user');
406: $phpMail->Username = $cred->auth->user;
407: $phpMail->Password = $cred->auth->password;
408: }
409:
410: $phpMail->AddReplyTo($cred->auth->email, $cred->auth->senderName);
411: $phpMail->SetFrom($cred->auth->email, $cred->auth->senderName);
412: $this->from = array(
413: 'address' => $cred->auth->email, 'name' => $cred->auth->senderName);
414: }else{
415: switch(Yii::app()->settings->emailType){
416: case 'sendmail':
417: $phpMail->IsSendmail();
418: break;
419: case 'qmail':
420: $phpMail->IsQmail();
421: break;
422: case 'smtp':
423: $phpMail->IsSMTP();
424:
425: $phpMail->Host = Yii::app()->settings->emailHost;
426: $phpMail->Port = Yii::app()->settings->emailPort;
427: $phpMail->SMTPSecure = Yii::app()->settings->emailSecurity;
428: if(Yii::app()->settings->emailUseAuth == 'admin'){
429: $phpMail->SMTPAuth = true;
430: $phpMail->Username = Yii::app()->settings->emailUser;
431: $phpMail->Password = Yii::app()->settings->emailPass;
432: }
433:
434:
435: break;
436: case 'mail':
437: default:
438: $phpMail->IsMail();
439: }
440:
441: $from = $this->from;
442: if($from == null){
443: if(empty($this->userProfile->emailAddress))
444: throw new Exception('Your profile doesn\'t have a valid email address.');
445:
446: $phpMail->AddReplyTo(
447: $this->userProfile->emailAddress, $this->userProfile->fullName);
448: $phpMail->SetFrom(
449: $this->userProfile->emailAddress, $this->userProfile->fullName);
450: } else{
451: $phpMail->AddReplyTo($from['address'], $from['name']);
452: $phpMail->SetFrom($from['address'], $from['name']);
453: }
454: }
455:
456: $this->_mailer = $phpMail;
457: }
458: return $this->_mailer;
459: }
460:
461: 462: 463: 464:
465: public function getUserProfile(){
466: if(!isset($this->_userProfile)){
467: if(empty($this->_userProfile)){
468: if(Yii::app()->params->noSession){
469:
470: $this->_userProfile = Profile::model()->findByPk(1);
471: }else{
472:
473:
474: $this->_userProfile = Yii::app()->params->profile;
475: }
476: }
477: }
478: return $this->_userProfile;
479: }
480:
481: public function setCredId($value) {
482: $this->_credId = $value;
483: }
484:
485: public function setFrom($from){
486: $this->_from = $from;
487: }
488:
489: 490: 491: 492:
493: public function setUserProfile(Profile $profile){
494: $this->_userProfile = $profile;
495: }
496:
497: public function testUserCredentials($email, $password, $server, $port, $security) {
498: require_once(
499: realpath(Yii::app()->basePath.'/components/phpMailer/PHPMailerAutoload.php'));
500: $phpMail = new PHPMailer(true);
501:
502: $phpMail->isSMTP();
503: $phpMail->SMTPAuth = true;
504: $phpMail->Username = $email;
505: $phpMail->Password = $password;
506: $phpMail->Host = $server;
507: $phpMail->Port = $port;
508: $phpMail->SMTPSecure = $security;
509:
510: try {
511: $validCredentials = $phpMail->SmtpConnect();
512: } catch(phpmailerException $error) {
513: $validCredentials = false;
514: }
515: return $validCredentials;
516: }
517:
518: }
519:
520: ?>
521: