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: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61:
62: class Credentials extends CActiveRecord {
63:
64: 65: 66: 67: 68:
69: const LEGACY_ID = -1;
70:
71: 72: 73: 74:
75: const SYS_ID = -1;
76:
77: private static $_authModelLabels;
78:
79: private static $_authModels;
80:
81: private static $_defaultCredentials;
82:
83: private static $_sysDefaultCredentials;
84:
85: 86: 87: 88: 89:
90: public static $sysUseAlias = array(
91: -1 => 'bulkEmail',
92: -2 => 'serviceCaseEmail',
93: -3 => 'systemResponseEmail',
94: -4 => 'systemNotificationEmail'
95: );
96:
97:
98: 99: 100: 101: 102: 103: 104: 105: 106: 107: 108:
109: public static $sysUseId = array(
110: 'bulkEmail' => -1,
111: 'serviceCaseEmail' => -2,
112: 'systemResponseEmail' => -3,
113: 'systemNotificationEmail' => -4
114: );
115:
116: 117: 118: 119: 120:
121: public static $sysUseTypes = array(
122: -1 => 'email',
123: -2 => 'email',
124: -3 => 'email',
125: -4 => 'email'
126: );
127:
128: 129: 130: 131:
132: private $_isInUseBySystem;
133:
134: 135: 136: 137:
138: protected $validModels = array(
139: 'EmailAccount',
140: 'GMailAccount',
141: 'MandrillAccount',
142: 'MailjetAccount',
143: 'MailgunAccount',
144: 'OutlookEmailAccount',
145: 'SendgridAccount',
146: 'SESAccount',
147: 'YahooEmailAccount',
148: 'TwitterApp',
149: 'GoogleProject',
150: );
151:
152: 153: 154: 155:
156: protected static $imapModels = array(
157: 'EmailAccount',
158: 'GMailAccount',
159: 'OutlookEmailAccount',
160: 'YahooEmailAccount',
161: );
162:
163: public function afterDelete () {
164: parent::afterDelete ();
165:
166: }
167:
168: public function attributeLabels() {
169: return array(
170: 'name' => Yii::t('app','Name'),
171: 'userId' => Yii::t('app','Owner'),
172: 'private' => Yii::t('app','Private'),
173: 'isEncrypted' => Yii::t('app','Encryption Enabled'),
174: 'createDate' => Yii::t('app','Date Created'),
175: 'lastUpdated' => Yii::t('app','Date Last Updated'),
176: 'auth' => Yii::t('app','Authentication Details'),
177: );
178: }
179:
180: public function relations () {
181: return array(
182: 'user' => array(self::BELONGS_TO, 'User', array ('userId' => 'id')),
183: );
184: }
185:
186: public function behaviors(){
187: return array(
188: 'JSONEmbeddedModelFieldsBehavior' => array(
189: 'class' => 'application.components.JSONEmbeddedModelFieldsBehavior',
190: 'transformAttributes' => array('auth'),
191: 'templateAttr' => 'modelClass',
192: 'encryptedFlagAttr' => 'isEncrypted',
193: ),
194: );
195: }
196:
197: public function afterSave () {
198: if ($this->modelClass &&
199: in_array ($this->modelClass, array ('TwitterApp', 'GoogleProject'))) {
200:
201: $modelClass = $this->modelClass;
202: $prop = $modelClass::getAdminProperty ();
203: Yii::app()->settings->$prop = $this->id;
204: Yii::app()->settings->save ();
205: }
206: parent::afterSave ();
207: }
208:
209: public function beforeDelete(){
210: Yii::app()->db->createCommand()->delete('x2_credentials_default',"credId=:id", array(':id'=>$this->id));
211: return parent::beforeDelete();
212: }
213:
214: 215: 216: 217: 218:
219: public function defaultHooks($userId, $serviceType){
220: switch($serviceType){
221: case 'email':
222: $adminAliasMap = array(
223: 'bulkEmail' => 'emailBulkAccount',
224: 'serviceCaseEmail' => 'serviceCaseEmailAccount',
225: 'systemResponseEmail' => 'webLeadEmailAccount',
226: 'systemNotificationEmail' => 'emailNotificationAccount'
227: );
228:
229:
230: if(array_key_exists($userId,self::$sysUseAlias)){
231: $adminAttr = $adminAliasMap[self::$sysUseAlias[$userId]];
232: Yii::app()->settings->{$adminAttr} = $this->id;
233: Yii::app()->settings->update(array($adminAttr));
234: }
235: break;
236: }
237: }
238:
239: 240: 241: 242: 243:
244: public function findDefault($userId, $serviceType){
245: if(array_key_exists($userId, $this->defaultCredentials)){
246: if(array_key_exists($serviceType, $this->defaultCredentials[$userId])){
247: return self::model()->findByPk($this->defaultCredentials[$userId][$serviceType]);
248: }
249: }
250:
251: $criteria = new CDbCriteria(array('condition' => '`userId`=:uid', 'params' => array(':uid' => $userId)));
252: if(array_key_exists($serviceType, $this->defaultSubstitutes)){
253: if(count($this->defaultSubstitutes[$serviceType])){
254: $criteria->addInCondition('modelClass', $this->defaultSubstitutes[$serviceType]);
255: }
256: }
257: return self::model()->find($criteria);
258: }
259:
260: 261: 262: 263:
264: public function getAuthModels(){
265: if(!isset(self::$_authModels)){
266: self::$_authModels = array();
267: foreach($this->validModels as $class){
268: self::$_authModels[$class] = new $class;
269: }
270: }
271: return self::$_authModels;
272: }
273:
274: 275: 276: 277:
278: public function getAuthModelLabels(){
279: if(!isset(self::$_authModelLabels)){
280: self::$_authModelLabels = array();
281: foreach($this->authModels as $class => $model){
282: self::$_authModelLabels[$class] = $model->modelLabel();
283: }
284: }
285: return self::$_authModelLabels;
286: }
287:
288: 289: 290: 291: 292:
293: public function getDefaultCredentials($refresh=false){
294: if(!isset(self::$_defaultCredentials) || $refresh){
295: $allDefaults = Yii::app()->db->createCommand()
296: ->select('*')->from('x2_credentials_default')->queryAll();
297: self::$_defaultCredentials = array_fill_keys(array_map(function($d){
298: return $d['userId'];
299: }, $allDefaults), array());
300: foreach($allDefaults as $d){
301: self::$_defaultCredentials[$d['userId']][$d['serviceType']] = $d['credId'];
302: }
303: }
304: return self::$_defaultCredentials;
305: }
306:
307: 308: 309:
310: public function getDefaultSubstitutes(){
311: return array(
312: 'email' => array(
313: 'EmailAccount',
314: 'GMailAccount',
315: 'MandrillAccount',
316: 'MailjetAccount',
317: 'MailgunAccount',
318: 'OutlookEmailAccount',
319: 'SendgridAccount',
320: 'SESAccount',
321: 'YahooEmailAccount',
322: ),
323: 'twitter' => array ('TwitterApp'),
324: 'googleProject' => array ('GoogleProject'),
325:
326: );
327: }
328:
329: 330: 331:
332: public function getDefaultSubstitutesInv() {
333: return array(
334: 'EmailAccount' => array('email'),
335: 'GMailAccount' => array('email'),
336: 'MandrillAccount' => array('email'),
337: 'MailjetAccount' => array('email'),
338: 'MailgunAccount' => array('email'),
339: 'OutlookEmailAccount' => array('email'),
340: 'SendgridAccount' => array('email'),
341: 'SESAccount' => array('email'),
342: 'YahooEmailAccount' => array('email'),
343: 'TwitterApp' => array ('twitter'),
344: 'GoogleProject' => array ('googleProject'),
345: );
346: }
347:
348: 349: 350:
351: public function getDefaultUserAccount($userId=null,$type='email'){
352: $userId = $userId === null ? Yii::app()->user->id : $userId;
353: $defaultCreds = $this->defaultCredentials;
354: if(array_key_exists($userId, $defaultCreds)){
355: $userDefaults = $defaultCreds[$userId];
356: if(array_key_exists($type, $userDefaults))
357: return $userDefaults[$type];
358: }
359: return self::LEGACY_ID;
360: }
361:
362: 363: 364: 365:
366: public function getIsInUseBySystem() {
367: if(!isset($this->_isInUseBySystem)) {
368: if($this->userId != self::SYS_ID)
369: $this->_isInUseBySystem = false;
370: else{
371: $defaults = $this->getDefaultCredentials();
372: $this->_isInUseBySystem = false;
373: foreach(self::$sysUseId as $alias => $id){
374: if(isset($defaults[$id]))
375: if(in_array($this->id, $defaults[$id])){
376: $this->_isInUseBySystem = true;
377: break;
378: }
379: }
380: }
381: }
382: return $this->_isInUseBySystem;
383: }
384:
385: public function getAuthModel () {
386: if(!$this->auth instanceof JSONEmbeddedModel)
387: $this->instantiateField('auth');
388: return $this->auth;
389: }
390:
391: 392: 393: 394:
395: public function getPageTitle() {
396: if (method_exists ($this->getAuthModel (), 'getPageTitle')) {
397:
398: return $this->getAuthModel ()->getPageTitle ();
399: } else {
400: return $this->isNewRecord ?
401: Yii::t('app', "New {service}", array('{service}' => $this->serviceLabel)) :
402: Yii::t('app', 'Editing:')." <em>{$this->name}</em> ({$this->serviceLabel})";
403: }
404: }
405:
406: 407: 408: 409:
410: public function getServiceLabel() {
411: return $this->authModelLabels[$this->modelClass];
412: }
413:
414: 415: 416: 417:
418: public function getServiceLabels(){
419: return array(
420: 'email' => Yii::t('app', 'Email Account'),
421: 'twitter' => Yii::t('app', 'Twitter App'),
422: 'googleProject' => Yii::t('app', 'Google Project'),
423:
424: );
425: }
426:
427: 428: 429: 430: 431: 432:
433: public function getSubstituteLabels() {
434: $subInv = $this->defaultSubstitutesInv[$this->modelClass];
435: $subLab = array();
436: $serviceLabels = $this->getServiceLabels();
437: foreach($subInv as $serviceType) {
438: $subLab[$serviceType] = $serviceLabels[$serviceType];
439: }
440: return $subLab;
441: }
442:
443: 444: 445: 446:
447: public function getSysUseLabel(){
448: return array(
449: -1 => Yii::t('app', 'Bulk Email Account'),
450: -2 => Yii::t('app', 'Service Case Email Account'),
451: -3 => Yii::t('app', 'System Response Emailer'),
452: -4 => Yii::t('app', 'System Notification Emailer')
453: );
454: }
455:
456: 457: 458: 459: 460: 461: 462: 463: 464: 465: 466: 467: 468: 469: 470:
471: public static function getCredentialOptions (
472: $model,$name,$type='email',$uid=null,$htmlOptions=array(),$excludeLegacy=false,$imapOnly=false){
473:
474:
475: $defaultUserId = in_array($uid,self::$sysUseId) ?
476: $uid :
477: ($uid !==null ? $uid : Yii::app()->user->id);
478: $uid = Yii::app()->user->id;
479:
480:
481: $criteria = new CDbCriteria(array('params'=>array(':uid'=>$uid)));
482: $staticModel = self::model();
483: $staticModel->userId = self::SYS_ID;
484: $criteria->addCondition('userId=:uid');
485:
486:
487: if ($imapOnly) {
488: $criteria->addInCondition ('modelClass', self::$imapModels);
489: }
490:
491:
492: if(Yii::app()->user->checkAccess(
493: 'CredentialsSelectSystemwide',array('model'=>$staticModel))) {
494:
495: $criteria->addCondition('userId='.self::SYS_ID,'OR');
496: } else {
497: $defaultUserId = $uid;
498: }
499: $staticModel->private = 0;
500:
501:
502: if(Yii::app()->user->checkAccess(
503: 'CredentialsSelectNonPrivate',array('model'=>$staticModel))) {
504: $criteria->addCondition('private=0','OR');
505: }
506: 507:
508: $criteria->addInCondition('modelClass',$staticModel->defaultSubstitutes[$type]);
509: $credRecords = $staticModel->findAll($criteria);
510: $credentials = array();
511: if($model === null || $model->$name == null){
512:
513: $defaultCreds = $staticModel->getDefaultCredentials();
514: if($type == 'email')
515: $selectedCredentials = self::LEGACY_ID;
516: if(array_key_exists($defaultUserId, $defaultCreds))
517: if(array_key_exists($type, $defaultCreds[$defaultUserId]))
518: $selectedCredentials = $defaultCreds[$defaultUserId][$type];
519: }else{
520:
521: $selectedCredentials = $model->$name;
522: }
523:
524: foreach($credRecords as $cred) {
525: $credentials[$cred->id] = $cred->name;
526: if($type == 'email') {
527: $credentials[$cred->id] = Formatter::truncateText($credentials[$cred->id].
528: ' : "'.$cred->auth->senderName.'" <'.$cred->auth->email.'>',50);
529: }
530: }
531: if($type == 'email' && !$excludeLegacy) {
532: $credentials[self::LEGACY_ID] = Yii::t('app','System default (legacy)');
533: }
534: $options = array();
535: $selectedOption = $selectedCredentials;
536: foreach($credentials as $credId => $label) {
537: if($credId == $selectedCredentials) {
538: $options[$credId] = array('selected'=>'selected');
539: } else {
540: $options[$credId] = array('selected' => false);
541: }
542: }
543: if($type=='email')
544: $options[self::LEGACY_ID]['class'] = 'legacy-email';
545:
546: $htmlOptions['options']=$options;
547:
548: $retDict = array (
549: 'credentials' => $credentials,
550: 'htmlOptions' => $htmlOptions,
551: 'selectedOption' => $selectedOption
552: );
553: return $retDict;
554:
555: }
556:
557: 558: 559: 560: 561: 562: 563: 564: 565: 566: 567: 568: 569:
570: public static function selectorField(
571: $model,$name,$type='email',$uid=null,$htmlOptions=array(),$excludeLegacy=false,$imapOnly=false) {
572:
573: $retDict = self::getCredentialOptions ($model,$name,$type,$uid,$htmlOptions,$excludeLegacy,$imapOnly);
574: $credentials = $retDict['credentials'];
575: $htmlOptions = $retDict['htmlOptions'];
576: return CHtml::activeDropDownList($model,$name,$credentials,$htmlOptions);
577: }
578:
579: 580: 581: 582: 583: 584:
585: public function isDefaultOf($uid){
586: $services = array();
587: if(array_key_exists($uid,$this->defaultCredentials)) {
588: foreach($this->defaultCredentials[$uid] as $service => $id) {
589: if($id == $this->id)
590: $services[] = $service;
591: }
592: }
593: return $services;
594: }
595:
596: 597: 598: 599: 600: 601:
602: public function makeDefault($userId,$serviceType,$hooks = true){
603: if($hooks)
604: $this->defaultHooks($userId,$serviceType);
605: Yii::app()->db->createCommand()
606: ->delete('x2_credentials_default', 'userId=:uid AND serviceType=:st', array(
607: ':uid' => $userId,
608: ':st' => $serviceType
609: ));
610: Yii::app()->db->createCommand()
611: ->insert('x2_credentials_default', array(
612: 'userId' => $userId,
613: 'serviceType' => $serviceType,
614: 'credId' => $this->id
615: ));
616: }
617:
618: public static function model($className = __CLASS__){
619: return parent::model($className);
620: }
621:
622: public function rules() {
623: return array(
624: array('name,private,auth','safe'),
625: array('userId','safe','on'=>'create'),
626: array('name','required')
627: );
628: }
629:
630: public function tableName(){
631: return 'x2_credentials';
632: }
633:
634: }
635:
636: ?>
637: