Overview

Packages

  • application
    • commands
    • components
      • actions
      • filters
      • leftWidget
      • permissions
      • sortableWidget
      • util
      • webupdater
      • x2flow
        • actions
        • triggers
      • X2GridView
      • X2Settings
    • controllers
    • models
      • embedded
    • modules
      • accounts
        • controllers
        • models
      • actions
        • controllers
        • models
      • calendar
        • controllers
        • models
      • charts
        • models
      • contacts
        • controllers
        • models
      • docs
        • components
        • controllers
        • models
      • groups
        • controllers
        • models
      • marketing
        • components
        • controllers
        • models
      • media
        • controllers
        • models
      • mobile
        • components
      • opportunities
        • controllers
        • models
      • products
        • controllers
        • models
      • quotes
        • controllers
        • models
      • services
        • controllers
        • models
      • template
        • models
      • users
        • controllers
        • models
      • workflow
        • controllers
        • models
      • x2Leads
        • controllers
        • models
  • None
  • system
    • base
    • caching
    • console
    • db
      • ar
      • schema
    • validators
    • web
      • actions
      • auth
      • helpers
      • widgets
        • captcha
        • pagers
  • zii
    • widgets
      • grid

Classes

  • ActionMetaData
  • ActionText
  • Admin
  • AmorphousModel
  • ApiHook
  • APIModel
  • ChartSetting
  • ContactForm
  • ContactList
  • Credentials
  • Criteria
  • Dropdowns
  • Events
  • EventsData
  • Fields
  • FormLayout
  • Imports
  • InlineEmail
  • LeadRouting
  • Locations
  • LoginForm
  • Maps
  • Modules
  • Notes
  • Notification
  • PhoneNumber
  • Profile
  • Record
  • Relationships
  • Roles
  • RoleToPermission
  • RoleToUser
  • RoleToWorkflow
  • Rules
  • Session
  • SessionLog
  • Social
  • Tags
  • TempFile
  • Tips
  • Tours
  • TrackEmail
  • TriggerLog
  • URL
  • ViewLog
  • Widgets
  • X2List
  • X2ListCriterion
  • X2ListItem
  • X2Model
  • Overview
  • Package
  • Class
  • Tree
  1: <?php
  2: 
  3: /*****************************************************************************************
  4:  * X2Engine Open Source Edition is a customer relationship management program developed by
  5:  * X2Engine, Inc. Copyright (C) 2011-2016 X2Engine Inc.
  6:  * 
  7:  * This program is free software; you can redistribute it and/or modify it under
  8:  * the terms of the GNU Affero General Public License version 3 as published by the
  9:  * Free Software Foundation with the addition of the following permission added
 10:  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 11:  * IN WHICH THE COPYRIGHT IS OWNED BY X2ENGINE, X2ENGINE DISCLAIMS THE WARRANTY
 12:  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 13:  * 
 14:  * This program is distributed in the hope that it will be useful, but WITHOUT
 15:  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 16:  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
 17:  * details.
 18:  * 
 19:  * You should have received a copy of the GNU Affero General Public License along with
 20:  * this program; if not, see http://www.gnu.org/licenses or write to the Free
 21:  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 22:  * 02110-1301 USA.
 23:  * 
 24:  * You can contact X2Engine, Inc. P.O. Box 66752, Scotts Valley,
 25:  * California 95067, USA. or at email address contact@x2engine.com.
 26:  * 
 27:  * The interactive user interfaces in modified source and object code versions
 28:  * of this program must display Appropriate Legal Notices, as required under
 29:  * Section 5 of the GNU Affero General Public License version 3.
 30:  * 
 31:  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
 32:  * these Appropriate Legal Notices must retain the display of the "Powered by
 33:  * X2Engine" logo. If the display of the logo is not reasonably feasible for
 34:  * technical reasons, the Appropriate Legal Notices must display the words
 35:  * "Powered by X2Engine".
 36:  *****************************************************************************************/
 37: 
 38: /**
 39:  * Model implementing encrypted, generic credentials storage.
 40:  *
 41:  * @property array $authModelLabels (read-only) labels for embedded models;
 42:  *  classes to display labels.
 43:  * @property array $defaultCredentials (read-only) all credential default
 44:  *  records indexed by user ID and service type
 45:  * @property array $defaultSubstitutes (read-only) a map of service types to
 46:  *  valid embedded classes for storing data for that service. For example, the
 47:  *  Google account model can be used for sending email just as well as the
 48:  *  generic email account model, so it would need to be included among a list of
 49:  *  credentials to use as the default email account.
 50:  * @property array $defaultSubstitutesInv (read-only) Like {@link defaultSubstitutes}
 51:  *  but "inverted"; displays, for a given model class, the list of service types
 52:  *  for which it can act as a stand-in.
 53:  * @property bool $isInUseBySystem (read-only) indicates whether the attribute
 54:  *  is being used for some system-wide/generic task.
 55:  * @property array $serviceLabels (read-only) An array of UI-friendly names for service
 56:  *  keyworkds, i.e. "Email Account" for "email".
 57:  * @property array $sysUseLabels (read-only) An array of labels for system-wide
 58:  *  uses of system-owned credentials.
 59:  * @package application.models
 60:  * @author Demitri Morgan <demitri@x2engine.com>
 61:  */
 62: class Credentials extends CActiveRecord {
 63: 
 64:     /**
 65:      * When selecting a Credentials record: this as an ID indicates to use the
 66:      * (legacy) system default method. This should only ever be used in scenarios
 67:      * where "email" is the generic type of service being configured.
 68:      */
 69:     const LEGACY_ID = -1;
 70: 
 71:     /**
 72:      * When the userId of the record is set to this value, that denotes that it
 73:      * is available system-wide for generic tasks not tied to any one person.
 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:      * Effectively the inverse map of {@link sysUseId}; declared statically to
 87:      * avoid having to generate it.
 88:      * @var array
 89:      */
 90:     public static $sysUseAlias = array(
 91:         -1 => 'bulkEmail',
 92:         -2 => 'serviceCaseEmail',
 93:         -3 => 'systemResponseEmail',
 94:         -4 => 'systemNotificationEmail'
 95:     );
 96: 
 97: 
 98:     /**
 99:      * When selecting a user to set as the owner: values of this array as the
100:      * userId field in the x2_credentials_default record indicate that it is
101:      * it's owned by no one but can be used by anyone, and that it's the default
102:      * for a particular usage that is generic (i.e. not tied to any one user),
103:      * i.e. bulk email (which might typically use a non-personal address).
104:      *
105:      * Different values of userId derived from this array hence distinguish
106:      * different types of usage for system-wide credentials.
107:      * @var array
108:      */
109:     public static $sysUseId = array(
110:         'bulkEmail' => -1,
111:         'serviceCaseEmail' => -2,
112:         'systemResponseEmail' => -3,
113:         'systemNotificationEmail' => -4
114:     );
115: 
116:     /**
117:      * For each system use type, define (as a comma-delineated list) the service
118:      * type for that system use type.
119:      * @var type
120:      */
121:     public static $sysUseTypes = array(
122:         -1 => 'email',
123:         -2 => 'email',
124:         -3 => 'email',
125:         -4 => 'email'
126:     );
127: 
128:     /**
129:      * Stores {@link isInUseBySystem}
130:      * @var bool
131:      */
132:     private $_isInUseBySystem;
133: 
134:     /**
135:      * Model classes to include/list as valid for storing auth data
136:      * @var array
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:      * Model classes which support the IMAP protocol
154:      * @var array
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:      * Actions to take during setting of a default, especially when the default
216:      * is system-wide.
217:      * @param type $event
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:                 // For these system use aliases: set the appropriate values in the admin 
229:                 // model for consistency with legacy configuration page in admin
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:      * Returns the model with default credentials for a given type.
241:      * @param type $userId The ID of the user whose credentials are being looked up
242:      * @param type $type The type of service for which credentials are being looked up
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:         // Fallback: return the first model found associated with user ID that meets the criteria for use ($serviceType)
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:      * An array of credential storage model objects, for reference
262:      * @return type
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:      * Getter for {@link authModelLabels}
276:      * @return type
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:      * Getter for {@link defaultCredentials}
290:      * @param type $d
291:      * @return type
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:      * Returns the value for {@link defaultSubstitutes}
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: //          'google' => array('GMailAccount'),
326:         );
327:     }
328: 
329:     /**
330:      * Returns the value for {@link defaultSubstitutesInv}
331:      */
332:     public function getDefaultSubstitutesInv() {
333:         return array(
334:             'EmailAccount' => array('email'),
335:             'GMailAccount' => array('email'), // ,'google'),
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:      * Gets the default service record ID for the user of a given type.
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:      * Getter for {@link sysDefaultCredentials}
364:      * @param type $refresh
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:      * Returns an appropriate title for create/update pages.
393:      * @return type
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:      * Obtains the service type label (UI-friendly name for the category of credentials)
408:      * @return type
409:      */
410:     public function getServiceLabel() {
411:         return $this->authModelLabels[$this->modelClass];
412:     }
413: 
414:     /**
415:      * Gets translated labels for each service type ({@link serviceLabels})
416:      * @return array
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:             // 'google' => Yii::t('app','Google Account')
424:         );
425:     }
426: 
427:     /**
428:      * Gets a UI-friendly list of substitute classes to names for the current
429:      * embedded model (i.e. for a selector of services for which the current
430:      * credentials should be used as default)
431:      * @return array
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:      * Returns a list of labels for designated systemwide-use types.
445:      * @return type 
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:      * @param CModel $model Model whose attribute is being used to specify a set of credentials
458:      * @param string $name Attribute storing the ID of the credentials record
459:      * @param string $type Keyword specifying the "service type" (i.e. "email" encompasess 
460:      *  credentials 
461:      *  with modelClass "EmailAccount" and "GMailAccount"
462:      * @param integer $uid The user ID or system role ID for which the input is being generated
463:      * @param array $htmlOptions HTML options to pass to {@link CHtml::activeDropDownList()}
464:      * @param boolean $getNameEmailsArr if true, returned array will include array indexed by 
465:      *  credId which 
466:      *  contains associated email and name
467:      * @return array containing values which can be used to instantiate an activeDropDownList.
468:      *  This inludes an array of credential names as well an array of the options' selected 
469:      *  attributes.
470:      */
471:     public static function getCredentialOptions (
472:         $model,$name,$type='email',$uid=null,$htmlOptions=array(),$excludeLegacy=false,$imapOnly=false){
473: 
474:         // First get credentials available to the user:
475:         $defaultUserId = in_array($uid,self::$sysUseId) ? 
476:             $uid : 
477:             ($uid !==null ? $uid : Yii::app()->user->id); // The "user" (actual user or system role)
478:         $uid = Yii::app()->user->id; // The actual user
479: 
480:         // Users can always use their own credentials, it's assumed
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:         // Exclude accounts types that do not support IMAP if requested
487:         if ($imapOnly) {
488:             $criteria->addInCondition ('modelClass', self::$imapModels);
489:         }
490: 
491:         // Include system-owned credentials
492:         if(Yii::app()->user->checkAccess(
493:             'CredentialsSelectSystemwide',array('model'=>$staticModel))) {
494: 
495:             $criteria->addCondition('userId='.self::SYS_ID,'OR');
496:         } else { // Select the user's own default
497:             $defaultUserId = $uid;
498:         }
499:         $staticModel->private = 0;
500: 
501:         // Include non-private credentials if the user has access to them
502:         if(Yii::app()->user->checkAccess(
503:             'CredentialsSelectNonPrivate',array('model'=>$staticModel))) {
504:             $criteria->addCondition('private=0','OR');
505:         }
506:         /* Cover only credentials for the given type of third-party service for which the selector 
507:         field is being used: */
508:         $criteria->addInCondition('modelClass',$staticModel->defaultSubstitutes[$type]);
509:         $credRecords = $staticModel->findAll($criteria);
510:         $credentials = array();
511:         if($model === null || $model->$name == null){
512:             // Figure out which one is default since it hasn't been set yet
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:             // Use the one previously set
521:             $selectedCredentials = $model->$name;
522:         }
523:         // Compose options for the selector
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) {// Legacy email delivery method(s)
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:      * Generates a select input for a form that includes a list of credentials
559:      * available for the current user.
560:      * @param CModel $model Model whose attribute is being used to specify a set of credentials
561:      * @param string $name Attribute storing the ID of the credentials record
562:      * @param string $type Keyword specifying the "service type" (i.e. "email" encompasess 
563:      *  credentials with modelClass "EmailAccount" and "GMailAccount"
564:      * @param integer $uid The user ID or system role ID for which the input is being generated
565:      * @param array $htmlOptions HTML options to pass to {@link CHtml::activeDropDownList()}
566:      * @param array $excludeLegacy Exclude the sendmail legacy option
567:      * @param array $imapOnly Hide models which do not support IMAP
568:      * @return string
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:      * Given a user id, returns an array of all service types for which the
581:      * current record is default.
582:      * @param integer $uid
583:      * @return array
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:      * Set the default account for a given user to use for a given service.
598:      * @param type $userId ID of the user whose default is getting set. Null for generic/system 
599:      *  account.
600:      * @param type $serviceType Service type, i.e. 'email'
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: 
X2CRM Documentation API documentation generated by ApiGen 2.8.0