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

  • ContactsController
  • 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:  * @package application.modules.contacts.controllers
  40:  */
  41: class ContactsController extends x2base {
  42: 
  43:     public $modelClass = 'Contacts';
  44: 
  45:     /**
  46:      * Specifies the access control rules.
  47:      * This method is used by the 'accessControl' filter.
  48:      * No longer actually called since the permissions system changes
  49:      * @return array access control rules
  50:      * @deprecated
  51:      */
  52:     public function accessRules() {
  53: 
  54:         return array(
  55:             array('allow',
  56:                 'actions' => array('getItems', 'getLists', 'ignoreDuplicates', 'discardNew',
  57:                     'weblead', 'weblist'),
  58:                 'users' => array('*'),
  59:             ),
  60:             array('allow', // allow authenticated user to perform 'create' and 'update' actions
  61:                 'actions' => array(
  62:                     'index',
  63:                     'list',
  64:                     'lists',
  65:                     'view',
  66:                     'myContacts',
  67:                     'newContacts',
  68:                     'update',
  69:                     'create',
  70:                     'quickContact',
  71:                     'import',
  72:                     'importContacts',
  73:                     'viewNotes',
  74:                     'search',
  75:                     'addNote',
  76:                     'deleteNote',
  77:                     'saveChanges',
  78:                     'createAction',
  79:                     'importExcel',
  80:                     'export',
  81:                     'getTerms',
  82:                     'getContacts',
  83:                     'delete',
  84:                     'shareContact',
  85:                     'viewRelationships',
  86:                     'createList',
  87:                     'createListFromSelection',
  88:                     'updateList',
  89:                     'addToList',
  90:                     'removeFromList',
  91:                     'deleteList',
  92:                     'inlineEmail',
  93:                     'quickUpdateHistory',
  94:                     'subscribe',
  95:                     'qtip',
  96:                     'cleanFailedLeads',
  97:                 ),
  98:                 'users' => array('@'),
  99:             ),
 100:             array('allow', // allow admin user to perform 'admin' and 'delete' actions
 101:                 'actions' => array(
 102:                     'admin', 'testScalability'
 103:                 ),
 104:                 'users' => array('admin'),
 105:             ),
 106:             array('deny', // deny all users
 107:                 'users' => array('*'),
 108:             ),
 109:         );
 110:     }
 111: 
 112:     /**
 113:      * Return a list of external actions which need to be included.
 114:      * @return array A merge of the parent class's imported actions in addition to the ones that 
 115:      *  are specific to the Contacts controller
 116:      */
 117:     public function actions() {
 118:         $actions = array_merge(parent::actions(), array(
 119:             'weblead' => array(
 120:                 'class' => 'WebFormAction',
 121:             ),
 122:         ));
 123:         return $actions;
 124:     }
 125: 
 126:     /**
 127:      * Return a list of external behaviors which are necessary.
 128:      * @return array A merge of the parent class's behaviors with the ContactsController specific 
 129:      *  ones
 130:      */
 131:     public function behaviors() {
 132:         return array_merge(parent::behaviors(), array(
 133:             'X2MobileControllerBehavior' => array(
 134:                 'class' => 
 135:                     'application.modules.mobile.components.behaviors.X2MobileControllerBehavior'
 136:             ),
 137:             'LeadRoutingBehavior' => array(
 138:                 'class' => 'LeadRoutingBehavior'
 139:             ),
 140:             'ImportExportBehavior' => array(
 141:                 'class' => 'ImportExportBehavior'
 142:             ),
 143:             'QuickCreateRelationshipBehavior' => array(
 144:                 'class' => 'QuickCreateRelationshipBehavior',
 145:                 'attributesOfNewRecordToUpdate' => array(
 146:                     'Accounts' => array(
 147:                         'website' => 'website',
 148:                         'phone' => 'phone',
 149:                     ),
 150:                     'Opportunity' => array(
 151:                         'accountName' => 'company',
 152:                     )
 153:                 )
 154:             ),
 155:         ));
 156:     }
 157: 
 158:     /**
 159:      * Displays a particular model.
 160:      * @param integer $id the ID of the model to be displayed
 161:      */
 162:     public function actionView($id) {
 163:         $this->noBackdrop = true;
 164:         $contact = $this->loadModel($id);
 165:         if ($this->checkPermissions($contact, 'view')) {
 166: 
 167:             // Modify the time zone widget to display Contact time
 168:             if (isset($this->portlets['TimeZone'])) {
 169:                 $this->portlets['TimeZone']['params']['localTime'] = true;
 170:                 $this->portlets['TimeZone']['params']['model'] = &$contact;
 171:             }
 172: 
 173:             // Update the VCR list information to preserve what list we came from
 174:             if (isset($_COOKIE['vcr-list'])) {
 175:                 Yii::app()->user->setState('vcr-list', $_COOKIE['vcr-list']);
 176:             }
 177:             if ($contact->checkForDuplicates()) {
 178:                 $this->redirect($this->createUrl('/site/duplicateCheck', array(
 179:                             'moduleName' => 'contacts',
 180:                             'modelName' => 'Contacts',
 181:                             'id' => $id,
 182:                             'ref' => 'view',
 183:                 )));
 184:             } else {
 185:                 $contact->duplicateChecked();
 186:                 // add contact to user's recent item list
 187:                 User::addRecentItem('c', $id, Yii::app()->user->getId()); 
 188:                 parent::view($contact, 'contacts');
 189:             }
 190:         } else {
 191:             $this->denied ();
 192:         }
 193:     }
 194: 
 195:     /**
 196:      * This is a prototype function designed to re-build a record from the changelog.
 197:      *
 198:      * This method is largely a work in progress though it is functional right
 199:      * now as is, it could just use some refactoring and improvements. On the
 200:      * "View Changelog" page in the Admin tab there's a link on each Contact
 201:      * changelog entry to view the record at that point in the history. Clicking
 202:      * that link brings you here.
 203:      * @param int $id The ID of the Contact to be viewed
 204:      * @param int $timestamp The timestamp to view the Contact at... this should probably be refactored to changelog ID
 205:      */
 206:     public function actionRevisions($id, $timestamp) {
 207:         $contact = $this->loadModel($id);
 208:         // Find all the changelog entries associated with this Contact after the given
 209:         // timestamp. Realistically, this would be more accurate if Changelog ID
 210:         // was used instead of the timestamp.
 211:         $changes = X2Model::model('Changelog')->findAll('type="Contacts" AND itemId="' . $contact->id . '" AND timestamp > ' . $timestamp . ' ORDER BY timestamp DESC');
 212:         // Loop through the changes and apply each one retroactively to the Contact record.
 213:         foreach ($changes as $change) {
 214:             $fieldName = $change->fieldName;
 215:             if ($contact->hasAttribute($fieldName) && $fieldName != 'id')
 216:                 $contact->$fieldName = $change->oldValue;
 217:         }
 218:         // Set our widget info
 219:         if (isset($this->portlets['TimeZone']))
 220:             $this->portlets['TimeZone']['params']['model'] = &$contact;
 221: 
 222:         if ($this->checkPermissions($contact, 'view')) {
 223: 
 224:             if (isset($_COOKIE['vcr-list']))
 225:                 Yii::app()->user->setState('vcr-list', $_COOKIE['vcr-list']);
 226: 
 227:             User::addRecentItem('c', $id, Yii::app()->user->getId()); ////add contact to user's recent item list
 228:             // View the Contact with the data modified to this point
 229:             parent::view($contact, 'contacts');
 230:         } else
 231:             $this->redirect('index');
 232:     }
 233: 
 234:     /**
 235:      * @deprecated as of 4.1.6b
 236:      *
 237:      * Displays the a model's relationships with other models.
 238:      * This has been largely replaced with the relationships widget.
 239:      * @param type $id The id of the model to display relationships of
 240:      * @deprecated
 241:      *
 242:      */
 243:     /*public function actionViewRelationships($id) {
 244:         $model = $this->loadModel($id);
 245:         $dataProvider = new CActiveDataProvider('Relationships', array(
 246:             'criteria' => array(
 247:                 'condition' => '(firstType="Contacts" AND firstId="' . $id . '") OR (secondType="Contacts" AND secondId="' . $id . '")',
 248:             )
 249:         ));
 250:         $this->render('viewOpportunities', array(
 251:             'dataProvider' => $dataProvider,
 252:             'model' => $model,
 253:         ));
 254:     } */
 255: 
 256:     /**
 257:      * Used for accounts auto-complete method.  May be obsolete.
 258:      */
 259:     public function actionGetTerms() {
 260:         $sql = 'SELECT id, name as value FROM x2_accounts WHERE name LIKE :qterm ORDER BY name ASC';
 261:         $command = Yii::app()->db->createCommand($sql);
 262:         $qterm = $_GET['term'] . '%';
 263:         $command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
 264:         $result = $command->queryAll();
 265:         echo CJSON::encode($result);
 266:         exit;
 267:     }
 268: 
 269:     /**
 270:      * Used for auto-complete methods.  This method is likely obsolete.
 271:      */
 272:     public function actionGetContacts() {
 273:         $sql = 'SELECT id, CONCAT(firstName," ",lastName) as value FROM x2_contacts WHERE firstName LIKE :qterm OR lastName LIKE :qterm OR CONCAT(firstName," ",lastName) LIKE :qterm ORDER BY firstName ASC';
 274:         $command = Yii::app()->db->createCommand($sql);
 275:         $qterm = $_GET['term'] . '%';
 276:         $command->bindParam(":qterm", $qterm, PDO::PARAM_STR);
 277:         $result = $command->queryAll();
 278:         echo CJSON::encode($result);
 279:         exit;
 280:     }
 281: 
 282:     /**
 283:      *  Used for auto-complete methods
 284:      */
 285:     public function actionGetItems() {
 286:         $model = new Contacts('search');
 287:         $visCriteria = $model->getAccessCriteria();
 288:         list($fullNameCol,$fullNameParam) = Formatter::fullNameSelect(
 289:             'firstName', 'lastName', 'value');
 290:         // This is necessary because the query won't work if one simply compares
 291:         // the alias "value" as "value LIKE :qterm".
 292:         list($fullNameCol2, $fullNameParam2) = Formatter::fullNameSelect('firstName', 'lastName');
 293:         $sql = 'SELECT id, city, state, country, email, assignedTo, ' . $fullNameCol . '
 294:             FROM x2_contacts t 
 295:             WHERE (firstName LIKE :qterm OR lastName LIKE :qterm OR 
 296:                 ' . $fullNameCol2 . ' LIKE :qterm) AND (' . $visCriteria->condition . ')
 297:             ORDER BY firstName ASC';
 298:         $command = Yii::app()->db->createCommand($sql);
 299: 
 300:         $params = array(':qterm' => $_GET['term'] . '%') + $fullNameParam + $fullNameParam2 + 
 301:             $visCriteria->params;
 302:         $result = $command->queryAll(true, $params);
 303:         foreach (array_keys($result) as $key) {
 304:             $result[$key]['assignedTo'] = implode(
 305:                 ', ', $model->getAssigneeNames($result[$key]['assignedTo']));
 306:         }
 307:         echo CJSON::encode($result);
 308:         exit;
 309:     }
 310: 
 311:     /**
 312:      * Return a JSON encoded list of Contact lists
 313:      */
 314:     public function actionGetLists() {
 315:         if (!Yii::app()->user->checkAccess('ContactsAdminAccess')) {
 316:             $condition = ' AND (visibility="1" OR assignedTo="Anyone"  OR assignedTo="' . Yii::app()->user->getName() . '"';
 317:             /* x2temp */
 318:             $groupLinks = Yii::app()->db->createCommand()->select('groupId')->from('x2_group_to_user')->where('userId=' . Yii::app()->user->getId())->queryColumn();
 319:             if (!empty($groupLinks))
 320:                 $condition .= ' OR assignedTo IN (' . implode(',', $groupLinks) . ')';
 321: 
 322:             $condition .= ' OR (visibility=2 AND assignedTo IN
 323:                 (SELECT username FROM x2_group_to_user WHERE groupId IN
 324:                 (SELECT groupId FROM x2_group_to_user WHERE userId=' . Yii::app()->user->getId() . '))))';
 325:         } else {
 326:             $condition = '';
 327:         }
 328:         // Optional search parameter for autocomplete
 329:         $qterm = isset($_GET['term']) ? $_GET['term'] . '%' : '';
 330:         $static = isset($_GET['static']) && $_GET['static'];
 331:         $result = Yii::app()->db->createCommand()
 332:                 ->select('id,name as value')
 333:                 ->from('x2_lists')
 334:                 ->where(
 335:                     ($static ? 'type="static" AND ' : '').
 336:                     'modelName="Contacts" AND type!="campaign" 
 337:                     AND name LIKE :qterm' . $condition, 
 338:                     array(':qterm' => $qterm))
 339:                 ->order('name ASC')
 340:                 ->queryAll();
 341:         echo CJSON::encode($result);
 342:     }
 343: 
 344:     /**
 345:      * Synchronize a Contact record with its related Account.
 346:      * This function will load the linked Account record from the company field
 347:      * and overwrite any shared fields with the Account's version of that field.
 348:      * @param int $id The ID of the Contact
 349:      */
 350:     public function actionSyncAccount($id) {
 351:         $contact = $this->loadModel($id);
 352:         if ($contact->hasAttribute('company') && is_numeric($contact->company)) {
 353:             $account = X2Model::model('Accounts')->findByPk($contact->company);
 354:             if (isset($account)) {
 355:                 foreach ($account->attributes as $key => $value) {
 356:                     // Don't change ID or any of the date fields.
 357:                     if ($contact->hasAttribute($key) && $key != 'id' && $key != 'createDate' && $key != 'lastUpdated' && $key != 'lastActivity') {
 358:                         $contact->$key = $value;
 359:                     }
 360:                 }
 361:             }
 362:         }
 363:         $contact->save();
 364:         $this->redirect(array('view', 'id' => $id));
 365:     }
 366: 
 367:     /**
 368:      * Generates an email template to share Contact data
 369:      * @param int $id The ID of the Contact
 370:      */
 371:     public function actionShareContact($id) {
 372:         $users = User::getNames();
 373:         $model = $this->loadModel($id);
 374:         $body = "\n\n\n\n".Yii::t('contacts', '{module} Record Details', array(
 375:             '{module}'=>Modules::displayName(false)
 376:         ))." <br />
 377: <br />".Yii::t('contacts', 'Name').": $model->firstName $model->lastName
 378: <br />".Yii::t('contacts', 'E-Mail').": $model->email
 379: <br />".Yii::t('contacts', 'Phone').": $model->phone
 380: <br />".Yii::t('contacts', 'Account').": $model->company
 381: <br />".Yii::t('contacts', 'Address').": $model->address
 382: <br />$model->city, $model->state $model->zipcode
 383: <br />" . Yii::t('contacts', 'Background Info') . ": $model->backgroundInfo
 384: <br />" . Yii::t('app', 'Link') . ": " . CHtml::link($model->name,
 385:             $this->createAbsoluteUrl('/contacts/contacts/view', array('id' => $model->id)));
 386: 
 387:         $body = trim($body);
 388: 
 389:         $errors = array();
 390:         $hasError = false;
 391:         $status = array();
 392:         $email = array();
 393:         if (isset($_POST['email'], $_POST['body'])) {
 394: 
 395:             $subject = Yii::t('contacts', 'Contact Record Details');
 396:             $email['to'] = $this->parseEmailTo($this->decodeQuotes($_POST['email']));
 397:             $body = $_POST['body'];
 398:             // if(empty($email) || !preg_match("/[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/",$email))
 399:             if ($email['to'] === false)
 400:                 $errors[] = 'email';
 401:             if (empty($body))
 402:                 $errors[] = 'body';
 403: 
 404:             $emailFrom = Credentials::model()->getDefaultUserAccount(Credentials::$sysUseId['systemNotificationEmail'], 'email');
 405:             if ($emailFrom == Credentials::LEGACY_ID)
 406:                 if (!Yii::app()->params->profile->emailAddress) {
 407:                     Yii::app()->user->setFlash ('error', Yii::t('app', 'Email could not be sent: user profile does not have an email address.'));
 408:                     $hasError = true;
 409:                 } else {
 410:                     $emailFrom = array(
 411:                         'name' => Yii::app()->params->profile->fullName,
 412:                         'address' => Yii::app()->params->profile->emailAddress
 413:                     );
 414:                 }
 415: 
 416:             if (empty($errors) && !$hasError)
 417:                 $status = $this->sendUserEmail($email, $subject, $body, null, $emailFrom);
 418: 
 419:             if (array_search('200', $status)) {
 420:                 $this->redirect(array('view', 'id' => $model->id));
 421:                 return;
 422:             }
 423:             if ($email['to'] === false)
 424:                 $email = $_POST['email'];
 425:             else
 426:                 $email = $this->mailingListToString($email['to']);
 427:         }
 428:         $this->render('shareContact', array(
 429:             'model' => $model,
 430:             'users' => $users,
 431:             'body' => $body,
 432:             'currentWorkflow' => $this->getCurrentWorkflow($model->id, 'contacts'),
 433:             'email' => $email,
 434:             'status' => $status,
 435:             'errors' => $errors
 436:         ));
 437:     }
 438: 
 439:     /**
 440:      * Called by the duplicate checker to keep the current record
 441:      */
 442:     public function actionIgnoreDuplicates() {
 443:         if (isset($_POST['data'])) {
 444: 
 445:             $arr = json_decode($_POST['data'], true);
 446:             if ($_POST['ref'] != 'view') {
 447:                 if ($_POST['ref'] == 'create')
 448:                     $model = new Contacts;
 449:                 else {
 450:                     $id = $arr['id'];
 451:                     $model = Contacts::model()->findByPk($id);
 452:                 }
 453:                 $temp = $model->attributes;
 454:                 foreach ($arr as $key => $value) {
 455:                     $model->$key = $value;
 456:                 }
 457:             } else {
 458:                 $id = $arr['id'];
 459:                 $model = X2Model::model('Contacts')->findByPk($id);
 460:             }
 461:             $model->dupeCheck = 1;
 462:             $model->disableBehavior('X2TimestampBehavior');
 463:             if ($model->save()) {
 464:                 
 465:             }
 466:             // Optional parameter to determine what other steps to take, default null
 467:             $action = $_POST['action'];
 468:             if (!is_null($action)) {
 469:                 $criteria = new CDbCriteria();
 470:                 if (!empty($model->firstName) && !empty($model->lastName))
 471:                     $criteria->compare('CONCAT(firstName," ",lastName)', $model->firstName . " " . $model->lastName, false, "OR");
 472:                 if (!empty($model->email))
 473:                     $criteria->compare('email', $model->email, false, "OR");
 474:                 $criteria->compare('id', "<>" . $model->id, false, "AND");
 475:                 if (!Yii::app()->user->checkAccess('ContactsAdminAccess')) {
 476:                     $condition = 'visibility="1" OR (assignedTo="Anyone" AND visibility!="0")  OR assignedTo="' . Yii::app()->user->getName() . '"';
 477:                     /* x2temp */
 478:                     $groupLinks = Yii::app()->db->createCommand()->select('groupId')->from('x2_group_to_user')->where('userId=' . Yii::app()->user->getId())->queryColumn();
 479:                     if (!empty($groupLinks))
 480:                         $condition .= ' OR assignedTo IN (' . implode(',', $groupLinks) . ')';
 481: 
 482:                     $condition .= 'OR (visibility=2 AND assignedTo IN
 483:                         (SELECT username FROM x2_group_to_user WHERE groupId IN
 484:                             (SELECT groupId FROM x2_group_to_user WHERE userId=' . Yii::app()->user->getId() . ')))';
 485:                     $criteria->addCondition($condition);
 486:                 }
 487:                 // If the action was hide all, hide all the other records.
 488:                 if ($action == 'hideAll') {
 489:                     $duplicates = Contacts::model()->findAll($criteria);
 490:                     foreach ($duplicates as $duplicate) {
 491:                         $duplicate->dupeCheck = 1;
 492:                         $duplicate->assignedTo = 'Anyone';
 493:                         $duplicate->visibility = 0;
 494:                         $duplicate->doNotCall = 1;
 495:                         $duplicate->doNotEmail = 1;
 496:                         $duplicate->save();
 497:                         $notif = new Notification;
 498:                         $notif->user = 'admin';
 499:                         $notif->createdBy = Yii::app()->user->getName();
 500:                         $notif->createDate = time();
 501:                         $notif->type = 'dup_discard';
 502:                         $notif->modelType = 'Contacts';
 503:                         $notif->modelId = $duplicate->id;
 504:                         $notif->save();
 505:                     }
 506:                     // If it was delete all...
 507:                 } elseif ($action == 'deleteAll') {
 508:                     Contacts::model()->deleteAll($criteria);
 509:                 }
 510:             }
 511:             echo CHtml::encode ($model->id);
 512:         }
 513:     }
 514: 
 515:     /**
 516:      * Called by the duplicate checker when discarding the new record.
 517:      */
 518:     public function actionDiscardNew() {
 519: 
 520:         if (isset($_POST['id'])) {
 521:             $ref = $_POST['ref']; // Referring action
 522:             $action = $_POST['action'];
 523:             $oldId = $_POST['id'];
 524:             if ($ref == 'create' && is_null($action) || $action == 'null') {
 525:                 echo CHtml::encode ($oldId);
 526:                 return;
 527:             } elseif ($ref == 'create') {
 528:                 $oldRecord = X2Model::model('Contacts')->findByPk($oldId);
 529:                 if (isset($oldRecord)) {
 530:                     $oldRecord->disableBehavior('X2TimestampBehavior');
 531:                     Relationships::model()->deleteAllByAttributes(array('firstType' => 'Contacts', 'firstId' => $oldRecord->id));
 532:                     Relationships::model()->deleteAllByAttributes(array('secondType' => 'Contacts', 'secondId' => $oldRecord->id));
 533:                     if ($action == 'hideThis') {
 534:                         $oldRecord->dupeCheck = 1;
 535:                         $oldRecord->assignedTo = 'Anyone';
 536:                         $oldRecord->visibility = 0;
 537:                         $oldRecord->doNotCall = 1;
 538:                         $oldRecord->doNotEmail = 1;
 539:                         $oldRecord->save();
 540:                         $notif = new Notification;
 541:                         $notif->user = 'admin';
 542:                         $notif->createdBy = Yii::app()->user->getName();
 543:                         $notif->createDate = time();
 544:                         $notif->type = 'dup_discard';
 545:                         $notif->modelType = 'Contacts';
 546:                         $notif->modelId = $oldId;
 547:                         $notif->save();
 548:                         return;
 549:                     } elseif ($action == 'deleteThis') {
 550:                         $oldRecord->delete();
 551:                         return;
 552:                     }
 553:                 }
 554:             } elseif (isset($_POST['newId'])) {
 555:                 $newId = $_POST['newId'];
 556:                 $oldRecord = X2Model::model('Contacts')->findByPk($oldId);
 557:                 $oldRecord->disableBehavior('X2TimestampBehavior');
 558:                 $newRecord = Contacts::model()->findByPk($newId);
 559:                 $newRecord->disableBehavior('X2TimestampBehavior');
 560:                 $newRecord->dupeCheck = 1;
 561:                 $newRecord->save();
 562:                 if ($action === '') {
 563:                     $newRecord->delete();
 564:                     echo CHtml::encode ($oldId);
 565:                     return;
 566:                 } else {
 567:                     if (isset($oldRecord)) {
 568: 
 569:                         if ($action == 'hideThis') {
 570:                             $oldRecord->dupeCheck = 1;
 571:                             $oldRecord->assignedTo = 'Anyone';
 572:                             $oldRecord->visibility = 0;
 573:                             $oldRecord->doNotCall = 1;
 574:                             $oldRecord->doNotEmail = 1;
 575:                             $oldRecord->save();
 576:                             $notif = new Notification;
 577:                             $notif->user = 'admin';
 578:                             $notif->createdBy = Yii::app()->user->getName();
 579:                             $notif->createDate = time();
 580:                             $notif->type = 'dup_discard';
 581:                             $notif->modelType = 'Contacts';
 582:                             $notif->modelId = $oldId;
 583:                             $notif->save();
 584:                         } elseif ($action == 'deleteThis') {
 585:                             Relationships::model()->deleteAllByAttributes(array('firstType' => 'Contacts', 'firstId' => $oldRecord->id));
 586:                             Relationships::model()->deleteAllByAttributes(array('secondType' => 'Contacts', 'secondId' => $oldRecord->id));
 587:                             Tags::model()->deleteAllByAttributes(array('type' => 'Contacts', 'itemId' => $oldRecord->id));
 588:                             Actions::model()->deleteAllByAttributes(array('associationType' => 'Contacts', 'associationId' => $oldRecord->id));
 589:                             $oldRecord->delete();
 590:                         }
 591:                     }
 592: 
 593:                     echo CHtml::encode ($newId);
 594:                 }
 595:             }
 596:         }
 597:     }
 598: 
 599:     /**
 600:      * Creates a new Contact record
 601:      */
 602:     public function actionCreate() {
 603:         $model = new Contacts;
 604:         $name = 'Contacts';
 605:         $users = User::getNames();
 606: 
 607:         if (isset($_POST['Contacts'])) {
 608:             $model->setX2Fields($_POST['Contacts']);
 609:             $model->setName();
 610:             if (isset($_POST['x2ajax'])) {
 611:                 $ajaxErrors = $this->quickCreate($model);
 612:             } else {
 613:                 if ($model->validate () && $model->checkForDuplicates()) {
 614:                     Yii::app()->user->setState('json_attributes', json_encode($model->attributes));
 615:                     $this->redirect($this->createUrl('/site/duplicateCheck', array(
 616:                         'moduleName' => 'contacts',
 617:                         'modelName' => 'Contacts',
 618:                         'id' => null,
 619:                         'ref' => 'create',
 620:                     )));
 621:                 } else {
 622:                     if ($model->save()) {
 623:                         $this->redirect(array('view', 'id' => $model->id));
 624:                     }
 625:                 }
 626:             }
 627:         }
 628: 
 629:         if (isset($_POST['x2ajax'])) {
 630:             $this->renderInlineCreateForm($model, isset($ajaxErrors) ? $ajaxErrors : false);
 631:         } else {
 632:             $this->render('create', array(
 633:                 'model' => $model,
 634:                 'users' => $users,
 635:             ));
 636:         }
 637:     }
 638: 
 639:     /**
 640:      * Method of creating a Contact called by the Quick Create widget
 641:      */
 642:     public function actionQuickContact() {
 643: 
 644:         $model = new Contacts;
 645:         // collect user input data
 646:         if (isset($_POST['Contacts'])) {
 647:             // clear values that haven't been changed from the default
 648:             //$temp=$model->attributes;
 649:             $model->setX2Fields($_POST['Contacts']);
 650: 
 651:             $model->visibility = 1;
 652:             // validate user input and save contact
 653:             // $changes = $this->calculateChanges($temp, $model->attributes, $model);
 654:             // $model = $this->updateChangelog($model, $changes);
 655:             $model->createDate = time();
 656:             //if($model->validate()) {
 657:             if ($model->save()) {
 658:                 
 659:             } else {
 660:                 //echo CHtml::errorSummary ($model);
 661:                 echo CJSON::encode($model->getErrors());
 662:             }
 663:             return;
 664:             //}
 665:             //echo '';
 666:             //echo CJSON::encode($model->getErrors());
 667:         }
 668:         $this->renderPartial('application.components.views.quickContact', array(
 669:             'model' => $model
 670:         ));
 671:     }
 672: 
 673:     // Controller/action wrapper for update()
 674:     public function actionUpdate($id) {
 675:         $model = $this->loadModel($id);
 676:         $users = User::getNames();
 677:         $renderFlag = true;
 678: 
 679:         if (isset($_POST['Contacts'])) {
 680:             $oldAttributes = $model->attributes;
 681: 
 682:             $model->setX2Fields($_POST['Contacts']);
 683:             if ($model->save())
 684:                 $this->redirect(array('view', 'id' => $model->id));
 685:         }
 686:         if ($renderFlag) {
 687:             if (isset($_POST['x2ajax'])) {
 688:                 Yii::app()->clientScript->scriptMap['*.js'] = false;
 689:                 Yii::app()->clientScript->scriptMap['*.css'] = false;
 690:                 if (isset($x2ajaxCreateError) && $x2ajaxCreateError == true) {
 691:                     $this->widget ('FormView', array(
 692:                         'model' => $model
 693:                     ), true, true);
 694:                     // $page = $this->renderPartial(
 695:                     //     'application.components.views.@FORMVIEW', 
 696:                     //     array(
 697:                     //         'model' => $model,
 698:                     //         'users' => $users,
 699:                     //         'modelName' => 'contacts'
 700:                     //     ),
 701:                     //     true,
 702:                     //     true
 703:                     // );
 704:                     echo json_encode(
 705:                         array(
 706:                             'status' => 'userError',
 707:                             'page' => $page,
 708:                         )
 709:                     );
 710:                 } else {
 711:                     $this->widget ('FormView', array(
 712:                         'model' => $model,
 713:                     ), false, true);
 714:                     // $this->renderPartial(
 715:                     //    'application.components.views.@FORMVIEW', 
 716:                     //     array(
 717:                     //         'model' => $model,
 718:                     //         'users' => $users,
 719:                     //         'modelName' => 'contacts'
 720:                     //     ),
 721:                     //     false,
 722:                     //     true
 723:                     // );
 724:                 }
 725:             } else {
 726:                 $this->render('update', array(
 727:                     'model' => $model,
 728:                     'users' => $users,
 729:                 ));
 730:             }
 731:         }
 732:     }
 733: 
 734:     // Displays all visible Contact Lists
 735:     public function actionLists() {
 736:         $filter = new X2List ('search');
 737:         $criteria = new CDbCriteria();
 738:         $criteria->addCondition('type="static" OR type="dynamic"');
 739:         if (!Yii::app()->params->isAdmin) {
 740:             $condition = 
 741:                 'visibility="1" OR assignedTo="Anyone" OR 
 742:                  assignedTo="' . Yii::app()->user->getName() . '"';
 743:             /* x2temp */
 744:             $groupLinks = Yii::app()->db->createCommand()
 745:                 ->select('groupId')
 746:                 ->from('x2_group_to_user')
 747:                 ->where('userId=' . Yii::app()->user->getId())->queryColumn();
 748:             if (!empty($groupLinks))
 749:                 $condition .= ' OR assignedTo IN (' . implode(',', $groupLinks) . ')';
 750: 
 751:             $condition .= 'OR (visibility=2 AND assignedTo IN
 752:                 (SELECT username FROM x2_group_to_user WHERE groupId IN
 753:                     (SELECT groupId 
 754:                      FROM x2_group_to_user 
 755:                      WHERE userId=' . Yii::app()->user->getId() . ')
 756:                 )
 757:             )';
 758:             $criteria->addCondition($condition);
 759:         }
 760: 
 761:         $perPage = Profile::getResultsPerPage();
 762: 
 763:         //$criteria->offset = isset($_GET['page']) ? $_GET['page'] * $perPage - 3 : -3;
 764:         //$criteria->limit = $perPage;
 765:         $criteria->order = 'createDate DESC';
 766:         $filter->compareAttributes ($criteria);
 767: 
 768:         $contactLists = X2Model::model('X2List')->findAll($criteria);
 769: 
 770:         $totalContacts = X2Model::model('Contacts')->count();
 771:         $totalMyContacts = X2Model::model('Contacts')->count('assignedTo="' . Yii::app()->user->getName() . '"');
 772:         $totalNewContacts = X2Model::model('Contacts')->count('assignedTo="' . Yii::app()->user->getName() . '" AND createDate >= ' . mktime(0, 0, 0));
 773: 
 774:         $allContacts = new X2List;
 775:         $allContacts->attributes = array(
 776:             'id' => 'all',
 777:             'name' => Yii::t('contacts', 'All {module}', array('{module}'=>Modules::displayName())),
 778:             'description' => '',
 779:             'type' => 'dynamic',
 780:             'visibility' => 1,
 781:             'count' => $totalContacts,
 782:             'createDate' => 0,
 783:             'lastUpdated' => 0,
 784:         );
 785:         $newContacts = new X2List;
 786:         $newContacts->attributes = array(
 787:             'id' => 'new',
 788:             'assignedTo' => Yii::app()->user->getName(),
 789:             'name' => Yii::t('contacts', 'New {module}', array('{module}'=>Modules::displayName())),
 790:             'description' => '',
 791:             'type' => 'dynamic',
 792:             'visibility' => 1,
 793:             'count' => $totalNewContacts,
 794:             'createDate' => 0,
 795:             'lastUpdated' => 0,
 796:         );
 797:         $myContacts = new X2List;
 798:         $myContacts->attributes = array(
 799:             'id' => 'my',
 800:             'assignedTo' => Yii::app()->user->getName(),
 801:             'name' => Yii::t('contacts', 'My {module}', array('{module}'=>Modules::displayName())),
 802:             'description' => '',
 803:             'type' => 'dynamic',
 804:             'visibility' => 1,
 805:             'count' => $totalMyContacts,
 806:             'createDate' => 0,
 807:             'lastUpdated' => 0,
 808:         );
 809:         $contactListData = array(
 810:             $allContacts,
 811:             $myContacts,
 812:             $newContacts,
 813:         );
 814: 
 815:         $filteredPseudoLists = $filter->filter ($contactListData);
 816:         $lists = array_merge($filteredPseudoLists, $contactLists);
 817:         $dataProvider = new CArrayDataProvider($lists, array(
 818:             'pagination' => array('pageSize' => $perPage),
 819:             'sort' => array(
 820:                 'attributes' => array(
 821:                     'name' => array (
 822:                         'asc' => 'name asc, id desc',
 823:                         'desc' => 'name desc, id desc',
 824:                     ),
 825:                     // secondary order is needed to fix https://github.com/yiisoft/yii/issues/2082
 826:                     'type' => array (
 827:                         'asc' => 'type asc, id desc',
 828:                         'desc' => 'type desc, id desc',
 829:                     ),
 830: //                    'count' => array (
 831: //                        'asc' => 'count asc, id desc',
 832: //                        'desc' => 'count desc, id desc',
 833: //                    ),
 834:                     'assignedTo' => array (
 835:                         'asc' => 'assignedTo asc, id desc',
 836:                         'desc' => 'assignedTo desc, id desc',
 837:                     ),
 838:                 )),
 839:             'totalItemCount' => count($contactLists) + 3,
 840:         ));
 841: 
 842:         $this->render('listIndex', array(
 843:             'contactLists' => $dataProvider,
 844:             'filter' => $filter,
 845:         ));
 846:     }
 847: 
 848:     // Lists all contacts assigned to this user
 849:     public function actionMyContacts() {
 850:         $model = new Contacts('search');
 851:         Yii::app()->user->setState('vcr-list', 'myContacts');
 852:         $this->render('index', array('model' => $model));
 853:     }
 854: 
 855:     // Lists all contacts assigned to this user
 856:     public function actionNewContacts() {
 857:         $model = new Contacts('search');
 858:         Yii::app()->user->setState('vcr-list', 'newContacts');
 859:         $this->render('index', array('model' => $model));
 860:     }
 861: 
 862:     // Lists all visible contacts
 863:     public function actionIndex() {
 864:         $model = new Contacts('search');
 865: 
 866:         Yii::app()->user->setState('vcr-list', 'index');
 867:         $this->render('index', array('model' => $model));
 868:     }
 869: 
 870:     // Shows contacts in the specified list
 871:     public function actionList($id = null) {
 872:         $list = X2List::load($id);
 873: 
 874:         if (!isset($list)) {
 875:             Yii::app()->user->setFlash(
 876:                     'error', Yii::t('app', 'The requested page does not exist.'));
 877:             $this->redirect(array('lists'));
 878:         }
 879: 
 880:         $model = new Contacts('search');
 881:         Yii::app()->user->setState('vcr-list', $id);
 882:         $dataProvider = $model->searchList($id);
 883:         $list->count = $dataProvider->totalItemCount;
 884:         $list->runWithoutBehavior('X2FlowTriggerBehavior', function () use ($list) {
 885:             $list->save();
 886:         });
 887: 
 888:         X2Flow::trigger('RecordViewTrigger', array('model' => $list));
 889:         $this->render('list', array(
 890:             'listModel' => $list,
 891:             'dataProvider' => $dataProvider,
 892:             'model' => $model,
 893:         ));
 894:     }
 895: 
 896:     public function actionCreateList($ajax=false) {
 897:         $list = new X2List;
 898:         $list->modelName = 'Contacts';
 899:         $list->type = 'dynamic';
 900:         $list->assignedTo = Yii::app()->user->getName();
 901:         $list->visibility = 1;
 902: 
 903:         $contactModel = new Contacts;
 904:         $comparisonList = X2List::getComparisonList();
 905:         if (isset($_POST['X2List'])) {
 906: 
 907:             $list->attributes = $_POST['X2List'];
 908:             $list->modelName = 'Contacts';
 909:             $list->createDate = time();
 910:             $list->lastUpdated = time();
 911: 
 912:             if (isset($_POST['X2List'], $_POST['X2List']['attribute'], $_POST['X2List']['comparison'], $_POST['X2List']['value'])) {
 913: 
 914:                 $attributes = &$_POST['X2List']['attribute'];
 915:                 $comparisons = &$_POST['X2List']['comparison'];
 916:                 $values = &$_POST['X2List']['value'];
 917: 
 918:                 if (count($attributes) > 0 && count($attributes) == count($comparisons) && count($comparisons) == count($values)) {
 919:                     $list->modelName = 'Contacts';
 920:                     $list->lastUpdated = time();
 921: 
 922:                     if (!$list->hasErrors() && $list->save()) {
 923:                         if ($ajax) {
 924:                             echo CJSON::encode($list->attributes);
 925:                             return;
 926:                         }
 927:                         $this->redirect(array('/contacts/contacts/list', 'id' => $list->id));
 928:                     }
 929:                 }
 930:             }
 931:         }
 932: 
 933:         if (empty($criteriaModels)) {
 934:             $default = new X2ListCriterion;
 935:             $default->value = '';
 936:             $default->attribute = '';
 937:             $default->comparison = 'contains';
 938:             $criteriaModels[] = $default;
 939:         }
 940: 
 941:         if ($ajax) {
 942:             $html = $this->renderPartial('createList', array(
 943:                 'model' => $list,
 944:                 'criteriaModels' => $criteriaModels,
 945:                 'users' => User::getNames(),
 946:                 // 'attributeList'=>$attributeList,
 947:                 'comparisonList' => $comparisonList,
 948:                 'listTypes' => array(
 949:                     'dynamic' => Yii::t('contacts', 'Dynamic'),
 950:                     'static' => Yii::t('contacts', 'Static')
 951:                 ),
 952:                 'itemModel' => $contactModel,
 953:             ), false);
 954:             echo $this->processOutput($html);
 955:             return;
 956:         }
 957: 
 958:         $this->render('createList', array(
 959:             'model' => $list,
 960:             'criteriaModels' => $criteriaModels,
 961:             'users' => User::getNames(),
 962:             // 'attributeList'=>$attributeList,
 963:             'comparisonList' => $comparisonList,
 964:             'listTypes' => array(
 965:                 'dynamic' => Yii::t('contacts', 'Dynamic'),
 966:                 'static' => Yii::t('contacts', 'Static')
 967:             ),
 968:             'itemModel' => $contactModel,
 969:         ));
 970:     }
 971: 
 972:     public function actionUpdateList($id) {
 973:         $list = X2List::model()->findByPk($id);
 974: 
 975:         if (!isset($list))
 976:             throw new CHttpException(400, Yii::t('app', 'This list cannot be found.'));
 977: 
 978:         if (!$this->checkPermissions($list, 'edit'))
 979:             throw new CHttpException(403, Yii::t('app', 'You do not have permission to modify this list.'));
 980: 
 981:         $contactModel = new Contacts;
 982:         $comparisonList = X2List::getComparisonList();
 983:         $fields = $contactModel->getFields(true);
 984: 
 985:         if ($list->type == 'dynamic') {
 986:             $criteriaModels = X2ListCriterion::model()->findAllByAttributes(array('listId' => $list->id), new CDbCriteria(array('order' => 'id ASC')));
 987: 
 988:             if (isset($_POST['X2List'], $_POST['X2List']['attribute'], $_POST['X2List']['comparison'], $_POST['X2List']['value'])) {
 989: 
 990:                 $attributes = &$_POST['X2List']['attribute'];
 991:                 $comparisons = &$_POST['X2List']['comparison'];
 992:                 $values = &$_POST['X2List']['value'];
 993: 
 994:                 if (count($attributes) > 0 && count($attributes) == count($comparisons) && count($comparisons) == count($values)) {
 995: 
 996:                     $list->attributes = $_POST['X2List'];
 997:                     $list->modelName = 'Contacts';
 998:                     $list->lastUpdated = time();
 999: 
1000:                     if (!$list->hasErrors() && $list->save()) {
1001:                         $this->redirect(array('/contacts/contacts/list', 'id' => $list->id));
1002:                     }
1003:                 }
1004:             }
1005:         } else { //static or campaign lists
1006:             if (isset($_POST['X2List'])) {
1007:                 $list->attributes = $_POST['X2List'];
1008:                 $list->modelName = 'Contacts';
1009:                 $list->lastUpdated = time();
1010:                 $list->save();
1011:                 $this->redirect(array('/contacts/contacts/list', 'id' => $list->id));
1012:             }
1013:         }
1014: 
1015:         if (empty($criteriaModels)) {
1016:             $default = new X2ListCriterion;
1017:             $default->value = '';
1018:             $default->attribute = '';
1019:             $default->comparison = 'contains';
1020:             $criteriaModels[] = $default;
1021:         } else {
1022:             if ($list->type = 'dynamic') {
1023:                 foreach ($criteriaModels as $criM) {
1024:                     if (isset($fields[$criM->attribute])) {
1025:                         if ($fields[$criM->attribute]->type == 'link') {
1026:                             $criM->value = implode(',', array_map(function($c) {
1027:                                         list($name, $id) = Fields::nameAndId($c);
1028:                                         return $name;
1029:                                     }, explode(',', $criM->value)
1030:                                     )
1031:                             );
1032:                         }
1033:                     }
1034:                 }
1035:             }
1036:         }
1037: 
1038:         $this->render('updateList', array(
1039:             'model' => $list,
1040:             'criteriaModels' => $criteriaModels,
1041:             'users' => User::getNames(),
1042:             // 'attributeList'=>$attributeList,
1043:             'comparisonList' => $comparisonList,
1044:             'listTypes' => array(
1045:                 'dynamic' => Yii::t('contacts', 'Dynamic'),
1046:                 'static' => Yii::t('contacts', 'Static')
1047:             ),
1048:             'itemModel' => $contactModel,
1049:         ));
1050:     }
1051: 
1052:     // Yii::app()->db->createCommand()->select('id')->from($tableName)->where(array('like','name',"%$value%"))->queryColumn();
1053:     public function actionRemoveFromList() {
1054: 
1055:         if (isset($_POST['gvSelection'], $_POST['listId']) && !empty($_POST['gvSelection']) && is_array($_POST['gvSelection'])) {
1056: 
1057:             foreach ($_POST['gvSelection'] as $contactId)
1058:                 if (!ctype_digit((string) $contactId))
1059:                     throw new CHttpException(400, Yii::t('app', 'Invalid selection.'));
1060: 
1061:             $list = CActiveRecord::model('X2List')->findByPk($_POST['listId']);
1062: 
1063:             // check permissions
1064:             if ($list !== null && $this->checkPermissions($list, 'edit'))
1065:                 $list->removeIds($_POST['gvSelection']);
1066: 
1067:             echo 'success';
1068:         }
1069:     }
1070: 
1071:     public function actionDeleteList() {
1072: 
1073:         $id = isset($_GET['id']) ? $_GET['id'] : 'all';
1074: 
1075:         if (is_numeric($id))
1076:             $list = X2Model::model('X2List')->findByPk($id);
1077:         if (isset($list)) {
1078: 
1079:             // check permissions
1080:             if ($this->checkPermissions($list, 'edit'))
1081:                 $list->delete();
1082:             else
1083:                 throw new CHttpException(403, Yii::t('app', 'You do not have permission to modify this list.'));
1084:         }
1085:         $this->redirect(array('/contacts/contacts/lists'));
1086:     }
1087: 
1088:     /**
1089:      * @deprecated This functionality is superceded by the generalized
1090:      * import functionalitity in AdminController
1091:      * Contacts export function which generates human friendly data and also
1092:      * works for exporting particular lists of Contacts
1093:      * @param int $listId The ID of the list to be exported, if null it will be all Contacts
1094:      */
1095:     /*public function actionExportContacts($listId = null){
1096:         unset($_SESSION['contactExportFile'], $_SESSION['exportContactCriteria'], $_SESSION['contactExportMeta']);
1097:         if(is_null($listId)){
1098:             $file = "contact_export.csv";
1099:             $listName = CHtml::link(Yii::t('contacts', 'All Contacts'), array('/contacts/contacts/index'), array('style' => 'text-decoration:none;'));
1100:             $_SESSION['exportContactCriteria'] = array('with' => array()); // Forcefully disable eager loading so it doesn't go super-slow)
1101:         }else{
1102:             $list = X2List::load($listId);
1103:             $criteria = $list->queryCriteria();
1104:             $criteria->with = array();
1105:             $_SESSION['exportContactCriteria'] = $criteria;
1106:             $file = "list".$listId.".csv";
1107:             $listName = CHtml::link(Yii::t('contacts', 'List')." $listId: ".$list->name, array('/contacts/contacts/list','id'=>$listId), array('style' => 'text-decoration:none;'));
1108:         }
1109:         $filePath = $this->safePath($file);
1110:         $_SESSION['contactExportFile'] = $file;
1111:         $attributes = X2Model::model('Contacts')->attributes;
1112:         $meta = array_keys($attributes);
1113:         if(isset($list)){
1114:             // Figure out gridview settings to export those columns
1115:             $gridviewSettings = json_decode(Yii::app()->params->profile->gridviewSettings, true);
1116:             if(isset($gridviewSettings['contacts_list'.$listId])){
1117:                 $tempMeta = array_keys($gridviewSettings['contacts_list'.$listId]);
1118:                 $meta = array_intersect($tempMeta, $meta);
1119:             }
1120:         }
1121:         // Set up metadata
1122:         $_SESSION['contactExportMeta'] = $meta;
1123:         $fp = fopen($filePath, 'w+');
1124:         fputcsv($fp, $meta);
1125:         fclose($fp);
1126:         $this->render('exportContacts', array(
1127:             'listId' => $listId,
1128:             'listName' => $listName,
1129:         ));
1130:     } */
1131:     
1132:     public function actionDelete($id){
1133:         if(Yii::app()->request->isPostRequest){
1134:             $model = $this->loadModel($id);
1135:             $model->clearTags();
1136:             $model->delete();
1137:         } else {
1138:             throw new CHttpException(400, Yii::t('app', 'Invalid request. Please do not repeat this request again.'));
1139:         }
1140: 
1141:         // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
1142:         if (!isset($_GET['ajax']))
1143:             $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
1144:     }
1145: 
1146:     public function actionSubscribe() {
1147:         if (isset($_POST['ContactId']) && isset($_POST['Checked'])) {
1148:             $id = $_POST['ContactId'];
1149: 
1150:             $checked = json_decode($_POST['Checked']);
1151: 
1152:             if ($checked) { // user wants to subscribe to this contact
1153:                 $result = Yii::app()->db->createCommand()
1154:                         ->select()
1155:                         ->from('x2_subscribe_contacts')
1156:                         ->where(array('and', 'contact_id=:contact_id', 'user_id=:user_id'), array(':contact_id' => $id, 'user_id' => Yii::app()->user->id))
1157:                         ->queryAll();
1158:                 if (empty($result)) { // ensure user isn't already subscribed to this contact
1159:                     Yii::app()->db->createCommand()->insert('x2_subscribe_contacts', array('contact_id' => $id, 'user_id' => Yii::app()->user->id));
1160:                 }
1161:             } else { // user wants to unsubscribe to this contact
1162:                 $result = Yii::app()->db->createCommand()
1163:                         ->select()
1164:                         ->from('x2_subscribe_contacts')
1165:                         ->where(array('and', 'contact_id=:contact_id', 'user_id=:user_id'), array(':contact_id' => $id, 'user_id' => Yii::app()->user->id))
1166:                         ->queryAll();
1167:                 if (!empty($result)) { // ensure user is subscribed before unsubscribing
1168:                     Yii::app()->db->createCommand()->delete('x2_subscribe_contacts', array('contact_id=:contact_id', 'user_id=:user_id'), array(':contact_id' => $id, ':user_id' => Yii::app()->user->id));
1169:                 }
1170:             }
1171:         }
1172:     }
1173: 
1174:     public function actionQtip($id) {
1175:         $contact = $this->loadModel($id);
1176: 
1177:         $this->renderPartial('qtip', array('contact' => $contact));
1178:     }
1179: 
1180:     public function actionCleanFailedLeads() {
1181:         $file = $this->safePath('failed_leads.csv');
1182: 
1183:         if (file_exists($file)) {
1184:             header('Content-Description: File Transfer');
1185:             header('Content-Type: application/octet-stream');
1186:             header('Content-Disposition: attachment; filename=' . basename($file));
1187:             header('Content-Transfer-Encoding: binary');
1188:             header('Expires: 0');
1189:             header('Cache-Control: must-revalidate');
1190:             header('Pragma: public');
1191:             header('Content-Length: ' . filesize($file));
1192:             ob_clean();
1193:             flush();
1194:             readfile($file);
1195:             unlink($file);
1196:         }
1197:     }
1198: 
1199:     /**
1200:      * Create a menu for Contacts
1201:      * @param array Menu options to remove
1202:      * @param X2Model Model object passed to the view
1203:      * @param array Additional menu parameters
1204:      */
1205:     public function insertMenu($selectOptions = array(), $model = null, $menuParams = null) {
1206:         $Contacts = Modules::displayName();
1207:         $Contact = Modules::displayName(false);
1208:         $modelId = isset($model) ? $model->id : 0;
1209: 
1210:         $menuItems = array(
1211:             array(
1212:                 'name'=>'all',
1213:                 'label'=>Yii::t('contacts','All {module}', array('{module}'=>$Contacts)),
1214:                 'url'=>array('index')
1215:             ),
1216:             array(
1217:                 'name'=>'lists',
1218:                 'label'=>Yii::t('contacts','Lists'),
1219:                 'url'=>array('lists')
1220:             ),
1221:             array(
1222:                 'name'=>'create',
1223:                 'label'=>Yii::t('contacts','Create {module}', array('{module}'=>$Contact)),
1224:                 'url'=>array('create')
1225:             ),
1226:             RecordViewLayoutManager::getViewActionMenuListItem ($modelId),
1227:             array(
1228:                 'name'=>'edit',
1229:                 'label' => Yii::t('contacts', 'Edit {module}', array('{module}' => $Contact)), 
1230:                 'url' => array('update', 'id' => $modelId),
1231:             ),
1232:             array(
1233:                 'name'=>'save',
1234:                 'label'=>Yii::t('contacts','Save {module}', array('{module}'=>$Contact)),
1235:                 'url'=>'#',
1236:                 'linkOptions'=>array('onclick'=>"$('#save-button').click();return false;")
1237:             ),
1238:             array(
1239:                 'name'=>'share',
1240:                 'label' => Yii::t('contacts', 'Share {module}', array('{module}' => $Contact)), 
1241:                 'url' => array('shareContact', 'id' => $modelId)
1242:             ),
1243:             array(
1244:                 'name'=>'delete',
1245:                 'label' => Yii::t('contacts', 'Delete {module}', array('{module}' => $Contact)), 
1246:                 'url' => '#', 'linkOptions' => array('submit' => array('delete', 'id' => $modelId),
1247:                 'confirm' => 'Are you sure you want to delete this item?')
1248:             ),
1249:             array(
1250:                 'name'=>'email',
1251:                 'label' => Yii::t('app', 'Send Email'), 'url' => '#',
1252:                 'linkOptions' => array('onclick' => 'toggleEmailForm(); return false;')),
1253:             ModelFileUploader::menuLink(),
1254:             array(
1255:                 'name'=>'quotes',
1256:                 'label' => Yii::t('quotes', 'Quotes/Invoices'), 'url' => 'javascript:void(0)',
1257:                 'linkOptions' => array('onclick' => 'x2.inlineQuotes.toggle(); return false;')),
1258:             array(
1259:                 'name'=>'subscribe',
1260:                 'label' => Yii::t('quotes', 'Subscribe'),
1261:                 'url' => '#',
1262:                 'linkOptions' => array(
1263:                     'class' => 'x2-subscribe-button',
1264:                     'onclick' => 'return subscribe($(this));',
1265:                     'title' => Yii::t('contacts', 'Receive email updates every time information for {name} changes',
1266:                         array('{name}' => (isset($model->firstName, $model->lastName) ?
1267:                             CHtml::encode($model->firstName.' '.$model->lastName) : "")))
1268:             )),
1269:             array(
1270:                 'name'=>'unsubscribe',
1271:                 'label' => Yii::t('quotes', 'Unsubscribe'),
1272:                 'url' => '#',
1273:                 'linkOptions' => array(
1274:                     'class' => 'x2-subscribe-button',
1275:                     'onclick' => 'return subscribe($(this));',
1276:                     'title' => Yii::t('contacts', 'Receive email updates every time information for {name} changes',
1277:                         array('{name}' => (isset($model->firstName, $model->lastName) ?
1278:                             CHtml::encode($model->firstName.' '.$model->lastName) : "")))
1279:             )),
1280:             array(
1281:                 'name'=>'createList',
1282:                 'label'=>Yii::t('contacts','Create List'),
1283:                 'url'=>array('createList')
1284:             ),
1285:             array(
1286:                 'name'=>'viewList',
1287:                 'label'=>Yii::t('contacts','View List'),
1288:                 'url'=>array('list','id'=>$modelId)
1289:             ),
1290:             array(
1291:                 'name'=>'editList',
1292:                 'label'=>Yii::t('contacts','Edit List'),
1293:                 'url'=>array('updateList','id'=>$modelId)
1294:             ),
1295:             array(
1296:                 'name'=>'deleteList',
1297:                 'label'=>Yii::t('contacts','Delete List'),
1298:                 'url'=>'#',
1299:                 'linkOptions'=>array(
1300:                     'submit'=>array('deleteList','id'=>$modelId),
1301:                     'confirm'=>'Are you sure you want to delete this item?')
1302:             ),
1303:             array(
1304:                 'name'=>'import',
1305:                 'label'=>Yii::t('contacts','Import {module}', array('{module}'=>$Contacts)),
1306:                 'url'=>array('admin/importModels', 'model'=>'Contacts')
1307:             ),
1308:             array(
1309:                 'name'=>'export',
1310:                 'label'=>Yii::t('contacts', 'Export {module}', array('{module}'=>$Contacts)),
1311:                 'url'=>array('admin/exportModels', 'model'=>'Contacts')
1312:             ),
1313:             array(
1314:                 'name'=>'quick',
1315:                 'label'=>Yii::t('app', 'Quick Create'),
1316:                 'url'=>array('/site/createRecords', 'ret'=>'contacts'),
1317:                 'linkOptions'=>array(
1318:                     'id'=>'x2-create-multiple-records-button',
1319:                     'class'=>'x2-hint',
1320:                     'title'=>Yii::t('app', 'Create a {contact}, {account}, and {opportunity}.', 
1321:                         array(
1322:                             '{contact}' => $Contact,
1323:                             '{account}' => Modules::displayName(false, "Accounts"),
1324:                             '{opportunity}' => Modules::displayName(false, "Opportunities"),
1325:                         )))
1326:             ),
1327:             array(
1328:                 'name' => 'print',
1329:                 'label' => Yii::t('app', 'Print Record'),
1330:                 'url' => '#',
1331:                 'linkOptions' => array (
1332:                     'onClick'=>"window.open('".
1333:                         Yii::app()->createUrl('/site/printRecord', array (
1334:                             'modelClass' => 'Contacts',
1335:                             'id' => $modelId,
1336:                             'pageTitle' => Yii::t('app', 'Contact').': '.(isset($model) ? 
1337:                                 $model->name : "")
1338:                         ))."');"
1339:                 )
1340:             ),
1341:             array(
1342:                 'name'=>'addRecordAlias',
1343:                 'label'=>Yii::t('contacts', 'Add Social Profile'),
1344:                 'url' => '#',
1345:                 'linkOptions' => array (
1346:                     'id' => 'record-aliases-action-menu-link'
1347:                 )
1348:             ),
1349:             RecordViewLayoutManager::getEditLayoutActionMenuListItem (),
1350:         );
1351: 
1352:         $this->prepareMenu($menuItems, $selectOptions);
1353:         $this->actionMenu = $this->formatMenu($menuItems, $menuParams);
1354:     }
1355: 
1356: }
1357: 
X2CRM Documentation API documentation generated by ApiGen 2.8.0