public function renderLink($field, array $htmlOptions = array()) { $fieldName = $field->fieldName; $linkId = ''; $name = ''; $linkSource = null; // TODO: move this code and duplicate code in X2Model::renderModelInput into a helper // method. Might be able to use X2Model::getLinkedModel. if (class_exists($field->linkType)) { if (!empty($this->owner->{$fieldName})) { list($name, $linkId) = Fields::nameAndId($this->owner->{$fieldName}); $linkModel = X2Model::getLinkedModelMock($field->linkType, $name, $linkId, true); } else { $linkModel = X2Model::model($field->linkType); } if ($linkModel instanceof X2Model && $linkModel->asa('X2LinkableBehavior') instanceof X2LinkableBehavior) { $linkSource = Yii::app()->controller->createAbsoluteUrl($linkModel->autoCompleteSource); $linkId = $linkModel->id; $oldLinkFieldVal = $this->owner->{$fieldName}; $this->owner->{$fieldName} = $name; } } $input = CHtml::hiddenField($field->modelName . '[' . $fieldName . '_id]', $linkId, array()); $input .= CHtml::activeTextField($this->owner, $field->fieldName, array_merge(array('title' => $field->attributeLabel, 'data-x2-link-source' => $linkSource, 'class' => 'x2-mobile-autocomplete', 'autocomplete' => 'off'), $htmlOptions)); return $input; }
public static function getCriteria($associationId, $associationType, $relationships, $historyType) { // Based on our filter, we need a particular additional criteria $historyCriteria = array('all' => '', 'action' => ' AND type IS NULL', 'overdueActions' => ' AND type IS NULL AND complete="NO" AND dueDate <= ' . time(), 'incompleteActions' => ' AND type IS NULL AND complete="NO"', 'call' => ' AND type="call"', 'note' => ' AND type="note"', 'attachments' => ' AND type="attachment"', 'event' => ' AND type="event"', 'email' => ' AND type IN ("email","email_staged",' . '"email_opened","email_clicked","email_unsubscribed")', 'marketing' => ' AND type IN ("email","webactivity","weblead","email_staged",' . '"email_opened","email_clicked","email_unsubscribed","event")', 'quotes' => 'AND type like "quotes%"', 'time' => ' AND type="time"', 'webactivity' => 'AND type IN ("weblead","webactivity")', 'workflow' => ' AND type="workflow"'); $multiAssociationIds = array($associationId); if ($relationships) { // Add association conditions for our relationships $type = $associationType; $model = X2Model::model($type)->findByPk($associationId); if (count($model->relatedX2Models) > 0) { $associationCondition = "((associationId={$associationId} AND " . "associationType='{$associationType}')"; // Loop through related models and add an association type OR for each foreach ($model->relatedX2Models as $relatedModel) { if ($relatedModel instanceof X2Model) { $multiAssociationIds[] = $relatedModel->id; $associationCondition .= " OR (associationId={$relatedModel->id} AND " . "associationType='{$relatedModel->myModelName}')"; } } $associationCondition .= ")"; } else { $associationCondition = 'associationId=' . $associationId . ' AND ' . 'associationType="' . $associationType . '"'; } } else { $associationCondition = 'associationId=' . $associationId . ' AND ' . 'associationType="' . $associationType . '"'; } /* Fudge replacing Opportunity and Quote because they're stored as plural in the actions table */ $associationCondition = str_replace('Opportunity', 'opportunities', $associationCondition); $associationCondition = str_replace('Quote', 'quotes', $associationCondition); $visibilityCondition = ''; $module = isset(Yii::app()->controller->module) ? Yii::app()->controller->module->getId() : Yii::app()->controller->getId(); // Apply history privacy settings so that only allowed actions are viewable. if (!Yii::app()->user->checkAccess(ucfirst($module) . 'Admin')) { if (Yii::app()->settings->historyPrivacy == 'user') { $visibilityCondition = ' AND (assignedTo="' . Yii::app()->user->getName() . '")'; } elseif (Yii::app()->settings->historyPrivacy == 'group') { $visibilityCondition = ' AND ( t.assignedTo IN ( SELECT DISTINCT b.username FROM x2_group_to_user a INNER JOIN x2_group_to_user b ON a.groupId=b.groupId WHERE a.username="******") OR (t.assignedTo="' . Yii::app()->user->getName() . '"))'; } else { $visibilityCondition = ' AND (visibility="1" OR assignedTo="' . Yii::app()->user->getName() . '")'; } } $orderStr = 'IF(complete="No", GREATEST(createDate, IFNULL(dueDate,0), ' . 'IFNULL(lastUpdated,0)), GREATEST(createDate, ' . 'IFNULL(completeDate,0), IFNULL(lastUpdated,0))) DESC'; $mainCountCmd = Yii::app()->db->createCommand()->select('COUNT(*)')->from('x2_actions t')->where($associationCondition . $visibilityCondition . $historyCriteria[$historyType]); $mainCmd = Yii::app()->db->createCommand()->select('*')->from('x2_actions t')->where($associationCondition . $visibilityCondition . $historyCriteria[$historyType])->order($orderStr); $multiAssociationIdParams = AuxLib::bindArray($multiAssociationIds); $associationCondition = '((' . $associationCondition . ') OR ' . 'x2_action_to_record.recordId in ' . AuxLib::arrToStrList(array_keys($multiAssociationIdParams)) . ')'; $associationCondition = 'x2_action_to_record.recordId in ' . AuxLib::arrToStrList(array_keys($multiAssociationIdParams)); $joinCountCmd = Yii::app()->db->createCommand()->select('COUNT(*)')->from('x2_actions t')->join('x2_action_to_record', 'actionId=t.id')->where($associationCondition . $visibilityCondition . $historyCriteria[$historyType] . ' AND x2_action_to_record.recordType=:recordType'); $joinCmd = Yii::app()->db->createCommand()->select('t.*')->from('x2_actions t')->join('x2_action_to_record', 'actionId=t.id')->where($associationCondition . $visibilityCondition . $historyCriteria[$historyType] . ' AND x2_action_to_record.recordType=:recordType'); $count = $mainCountCmd->union($joinCountCmd->getText())->queryScalar(array_merge(array(':recordType' => X2Model::getModelName($associationType)), $multiAssociationIdParams)); return array('cmd' => $mainCmd->union($joinCmd->getText()), 'count' => $count, 'params' => array_merge(array(':recordType' => X2Model::getModelName($associationType)), $multiAssociationIdParams)); }
public function execute(&$params) { $campaign = CActiveRecord::model('Campaign')->findByPk($this->config['options']['campaign']); if ($campaign === null || $campaign->launchDate != 0 && $campaign->launchDate < time() || empty($campaign->subject)) { return false; } if (!isset($campaign->list) || $campaign->list->type == 'dynamic' && X2Model::model($campaign->list->modelName)->count($campaign->list->queryCriteria()) < 1) { return false; } // check if there's a template, and load that into the content field if ($campaign->template != 0) { $template = X2Model::model('Docs')->findByPk($campaign->template); if (isset($template)) { $campaign->content = $template->text; } } //Duplicate the list for campaign tracking, leave original untouched //only if the list is not already a campaign list if ($campaign->list->type != 'campaign') { $newList = $campaign->list->staticDuplicate(); if (!isset($newList)) { return false; } $newList->type = 'campaign'; if (!$newList->save()) { return false; } $campaign->list = $newList; $campaign->listId = $newList->id; } $campaign->launchDate = time(); return $campaign->save(); }
public static function getX2LeadsLinks($accountId) { $allX2Leads = X2Model::model('X2Leads')->findAllByAttributes(array('accountName' => $accountId)); $links = array(); foreach ($allX2Leads as $model) { $links[] = CHtml::link($model->name, array('/x2Leads/x2Leads/view', 'id' => $model->id)); } return implode(', ', $links); }
public function execute(array $gvSelection) { if (Yii::app()->controller->modelClass !== 'Contacts' || !isset($_POST['listName']) || $_POST['listName'] === '') { throw new CHttpException(400, Yii::t('app', 'Bad Request')); } if (!Yii::app()->params->isAdmin && !Yii::app()->user->checkAccess('ContactsCreateListFromSelection')) { return -1; } $listName = $_POST['listName']; foreach ($gvSelection as &$contactId) { if (!ctype_digit((string) $contactId)) { throw new CHttpException(400, Yii::t('app', 'Invalid selection.')); } } $list = new X2List(); $list->name = $_POST['listName']; $list->modelName = 'Contacts'; $list->type = 'static'; $list->assignedTo = Yii::app()->user->getName(); $list->visibility = 1; $list->createDate = time(); $list->lastUpdated = time(); $itemModel = X2Model::model('Contacts'); $success = true; if ($list->save()) { // if the list is valid save it so we can get the ID $count = 0; foreach ($gvSelection as &$itemId) { if ($itemModel->exists('id="' . $itemId . '"')) { // check if contact exists $item = new X2ListItem(); $item->contactId = $itemId; $item->listId = $list->id; if ($item->save()) { // add all the things! $count++; } } } $list->count = $count; $this->listId = $list->id; if ($list->save()) { self::$successFlashes[] = Yii::t('app', '{count} record' . ($count === 1 ? '' : 's') . ' added to new list "{list}"', array('{count}' => $count, '{list}' => $list->name)); } else { self::$errorFlashes[] = Yii::t('app', 'List created but records could not be added to it'); } } else { $success = false; self::$errorFlashes[] = Yii::t('app', 'List could not be created'); } return $success ? $count : -1; }
public function run() { $actionParams = Yii::app()->controller->getActionParams(); $twitter = null; if (isset(Yii::app()->controller->module) && Yii::app()->controller->module instanceof ContactsModule && Yii::app()->controller->action->id == 'view' && isset($actionParams['id'])) { // must have an actual ID value $currentRecord = X2Model::model('Contacts')->findByPk($actionParams['id']); if (!empty($currentRecord->twitter)) { $twitter = $currentRecord->twitter; } } $this->render('twitterFeed', array('twitter' => $twitter)); }
protected function validateValue(CModel $object, $value, $attribute) { // exception added for case where validator is added to AmorphousModel if (!$object instanceof X2Model) { return; } $field = $object->getField($attribute); $linkType = $field->linkType; $model = X2Model::model($linkType); if (!$model || !$model->findByPk($value)) { $this->error(Yii::t('admin', 'Invalid {fieldName}', array('{fieldName}' => $field->attributeLabel))); return false; } }
public function actionIndex() { $user = User::model()->findByPk(Yii::app()->user->getId()); $topList = $user->topContacts; $pieces = explode(',', $topList); $contacts = array(); foreach ($pieces as $piece) { $contact = X2Model::model('Contacts')->findByPk($piece); if (isset($contact)) { $contacts[] = $contact; } } $dataProvider = new CActiveDataProvider('Contacts'); $dataProvider->setData($contacts); $this->render('index', array('dataProvider' => $dataProvider)); }
/** * Extension of a base Yii function, this method is run before every action * in a controller. If true is returned, it procedes as normal, otherwise * it will redirect to the login page or generate a 403 error. * @param string $action The name of the action being executed. * @return boolean True if the user can procede with the requested action */ public function beforeAction($action = null) { if (is_int(Yii::app()->locked) && !Yii::app()->user->checkAccess('GeneralAdminSettingsTask')) { $this->owner->appLockout(); } $auth = Yii::app()->authManager; $params = array(); if (empty($action)) { $action = $this->owner->getAction()->getId(); } elseif (is_string($action)) { $action = $this->owner->createAction($action); } $actionId = $action->getId(); // These actions all have a model provided with them but its assignment // should not be checked for an exception. They either have permission // for this action or they do not. $exceptions = array('updateStageDetails', 'deleteList', 'updateList', 'userCalendarPermissions', 'exportList', 'updateLocation'); if (($this->owner->hasProperty('modelClass') || property_exists($this->owner, 'modelClass')) && class_exists($this->owner->modelClass)) { $staticModel = X2Model::model($this->owner->modelClass); } if (isset($_GET['id']) && !in_array($actionId, $exceptions) && !Yii::app()->user->isGuest && isset($staticModel)) { // Check assignment fields in the current model $retrieved = true; $model = $staticModel->findByPk($_GET['id']); if ($model instanceof X2Model) { $params['X2Model'] = $model; } } // Generate the proper name for the auth item $actionAccess = ucfirst($this->owner->getId()) . ucfirst($actionId); $authItem = $auth->getAuthItem($actionAccess); // Return true if the user is explicitly allowed to do it, or if there is no permission // item, or if they are an admin if (Yii::app()->params->isAdmin || (!Yii::app()->user->isGuest || Yii::app()->controller instanceof ApiController || Yii::app()->controller instanceof Api2Controller) && !$authItem instanceof CAuthItem || Yii::app()->user->checkAccess($actionAccess, $params)) { return true; } elseif (Yii::app()->user->isGuest) { Yii::app()->user->returnUrl = Yii::app()->request->url; if (Yii::app()->params->isMobileApp) { $this->owner->redirect($this->owner->createAbsoluteUrl('/mobile/login')); } else { $this->owner->redirect($this->owner->createUrl('/site/login')); } } else { $this->owner->denied(); } }
public function renderContactFields($model) { $defaultFields = X2Model::model('Fields')->findAllByAttributes(array('modelName' => 'Contacts'), array('condition' => "fieldName IN ('firstName', 'lastName', 'email', 'phone')")); $requiredFields = X2Model::model('Fields')->findAllByAttributes(array('modelName' => 'Contacts', 'required' => 1), array('condition' => "fieldName NOT IN ('firstName', 'lastName', 'phone', 'email', 'visibility')")); $i = 0; $fields = array_merge($requiredFields, $defaultFields); foreach ($fields as $field) { if ($field->type === 'boolean') { $class = ""; echo "<div>"; } else { $class = $field->fieldName === 'firstName' || $field->fieldName === 'lastName' ? 'quick-contact-narrow' : 'quick-contact-wide'; } $htmlAttr = array('class' => $class, 'tabindex' => 100 + $i, 'title' => $field->attributeLabel, 'id' => 'quick_create_' . $field->modelName . '_' . $field->fieldName); if ($field->type === 'boolean') { echo CHtml::label($field->attributeLabel, $htmlAttr['id']); } echo X2Model::renderModelInput($model, $field, $htmlAttr); if ($field->type === 'boolean') { echo "</div>"; } ++$i; } }
/** * Deletes duplicate notifications. Meant to be called before the creation of new notifications * @param string $notificationUsers assignee of the newly created notifications * TODO: unit test */ private function deleteOldNotifications($notificationUsers) { $notifCount = (int) X2Model::model('Notification')->countByAttributes(array('modelType' => 'Actions', 'modelId' => $this->id, 'type' => 'action_reminder')); if ($notifCount === 0) { return; } $notifications = X2Model::model('Notification')->findAllByAttributes(array('modelType' => 'Actions', 'modelId' => $this->id, 'type' => 'action_reminder')); foreach ($notifications as $notification) { if ($this->isAssignedTo($notification->user, true) && ($notificationUsers == 'assigned' || $notificationUsers == 'both')) { $notification->delete(); } elseif ($notification->user == Yii::app()->user->getName() && ($notificationUsers == 'me' || $notificationUsers == 'both')) { $notification->delete(); } } }
/** * Generates a description message with a link and optional preview image * for media items. * * @param string $actionDescription * @param boolean $makeLink * @param boolean $makeImage * @return string */ public static function attachmentActionText($actionDescription, $makeLink = false, $makeImage = false) { $data = explode(':', $actionDescription); $media = null; if (count($data) == 2 && is_numeric($data[1])) { // ensure data is formatted properly $media = X2Model::model('Media')->findByPK($data[1]); } // look for an entry in the media table if ($media) { // did we find an entry in the media table? if ($media->drive) { $str = Yii::t('media', 'Google Drive:') . ' '; } else { $str = Yii::t('media', 'File:') . ' '; } $fileExists = $media->fileExists(); if ($fileExists == false) { return $str . $data[0] . ' ' . Yii::t('media', '(deleted)'); } if ($makeLink) { $str .= $media->getMediaLink(); if (!$media->drive) { $str .= " | " . CHtml::link('[Download]', array('/media/media/download', 'id' => $media->id)); } } else { $str .= $data[0]; } if ($makeImage && $media->isImage()) { // to render an image, first check file extension $str .= $media->getImage(); } return $str; } else { return $actionDescription; } }
/** * Retrieves the item name for the specified Module * @param string $module Module to retrieve item name for, or the current module if null */ public static function itemDisplayName($moduleName = null) { if (is_null($moduleName)) { $moduleName = Yii::app()->controller->module->name; } $module = X2Model::model('Modules')->findByAttributes(array('name' => $moduleName)); $itemName = $moduleName; if (!empty($module->itemName)) { $itemName = $module->itemName; } else { // Attempt to load item name from legacy module options file $moduleDir = implode(DIRECTORY_SEPARATOR, array('protected', 'modules', $moduleName)); $configFile = implode(DIRECTORY_SEPARATOR, array($moduleDir, lcfirst($moduleName) . "Config.php")); if (is_dir($moduleDir) && file_exists($configFile)) { $file = Yii::app()->file->set($configFile); $contents = $file->getContents(); if (preg_match("/.*'recordName'.*/", $contents, $matches)) { $itemNameLine = $matches[0]; $itemNameRegex = "/.*'recordName'=>'([\\w\\s]*?)'.*/"; $itemName = preg_replace($itemNameRegex, "\$1", $itemNameLine); if (!empty($itemName)) { // Save this name in the database for the future $module->itemName = $itemName; $module->save(); } } } } return $itemName; }
/** * Returns the static model of the specified AR class. * @return Groups the static model class */ public static function model($className = __CLASS__) { return parent::model($className); }
/** * Get autocomplete options * @param string $term */ public static function getItems($term) { $model = X2Model::model(Yii::app()->controller->modelClass); if (isset($model)) { $tableName = $model->tableName(); $sql = 'SELECT id, name as value FROM ' . $tableName . ' WHERE name LIKE :qterm ORDER BY name ASC'; $command = Yii::app()->db->createCommand($sql); $qterm = $term . '%'; $command->bindParam(":qterm", $qterm, PDO::PARAM_STR); $result = $command->queryAll(); echo CJSON::encode($result); } Yii::app()->end(); }
/** * Test setting default values in new records */ public function testDefaultValues() { foreach (X2Model::model('Contacts')->getFields() as $field) { // Retrieve new values: $field->refresh(); } // Setting default values in the constructor $contact = new Contacts(); $this->assertEquals('Gustavo', $contact->firstName); $this->assertEquals('Fring', $contact->lastName); // Setting default values in setX2Fields $contact->firstName = ''; $contact->lastName = ''; $input = array(); $contact->setX2Fields($input); $this->assertEquals('Gustavo', $contact->firstName); $this->assertEquals('Fring', $contact->lastName); }
public function responseToModels($modelClass, array $response) { $models = array(); foreach ($response as $record) { $models[] = X2Model::model($modelClass)->findByAttributes($record); } return $models; }
public static function listOption($attributes, $name) { if ($attributes instanceof Fields) { $attributes = $attributes->getAttributes(); } $data = array('name' => $name, 'label' => $attributes['attributeLabel']); if (isset($attributes['type']) && $attributes['type']) { $data['type'] = $attributes['type']; } if (isset($attributes['required']) && $attributes['required']) { $data['required'] = 1; } if (isset($attributes['readOnly']) && $attributes['readOnly']) { $data['readOnly'] = 1; } if (isset($attributes['type'])) { if ($attributes['type'] === 'assignment' || $attributes['type'] === 'optionalAssignment') { $data['options'] = AuxLib::dropdownForJson(X2Model::getAssignmentOptions(true, true)); } elseif ($attributes['type'] === 'dropdown' && isset($attributes['linkType'])) { $data['linkType'] = $attributes['linkType']; $data['options'] = AuxLib::dropdownForJson(Dropdowns::getItems($attributes['linkType'])); } elseif ($attributes['type'] === 'link' && isset($attributes['linkType'])) { $staticLinkModel = X2Model::model($attributes['linkType']); if (array_key_exists('X2LinkableBehavior', $staticLinkModel->behaviors())) { $data['linkType'] = $attributes['linkType']; $data['linkSource'] = Yii::app()->controller->createUrl($staticLinkModel->autoCompleteSource); } } } return $data; }
break; } } $attributeLabels = $model->itemAttributeLabels; //hack tags in $fieldTypes['tags'] = 'tags'; $fieldOptions['tags'] = Tags::getAllTags(); $attributeLabels['tags'] = Yii::t('contacts', 'Tags'); natcasesort($attributeLabels); $comparisonList = array('=' => Yii::t('contacts', 'equals'), '>' => Yii::t('contacts', 'greater than'), '<' => Yii::t('contacts', 'less than'), '<>' => Yii::t('contacts', 'not equal to'), 'list' => Yii::t('contacts', 'in list'), 'notList' => Yii::t('contacts', 'not in list'), 'empty' => Yii::t('contacts', 'empty'), 'notEmpty' => Yii::t('contacts', 'not empty'), 'contains' => Yii::t('contacts', 'contains'), 'noContains' => Yii::t('contacts', 'does not contain')); $criteriaAttr = array(); foreach ($criteriaModels as $criterion) { $attr = $criterion->getAttributes(); //for any link types, look up the name belonging to the id if (isset($fieldTypes[$attr['attribute']]) && $fieldTypes[$attr['attribute']] == 'link') { $record = X2Model::model(ucfirst($fieldLinkTypes[$attr['attribute']]))->findByPk($attr['value']); if (isset($record) && isset($record->name)) { $attr['name'] = $record->name; } } $criteriaAttr[] = $attr; } $headjs = "\nvar fieldTypes = " . json_encode($fieldTypes, false) . ";\nvar fieldLinkTypes = " . json_encode($fieldLinkTypes, false) . ";\nvar fieldOptions = " . json_encode($fieldOptions, false) . ";\nvar comparisonList = " . json_encode($comparisonList, false) . ";\nvar attributeLabels = " . json_encode($attributeLabels, false) . ";\nvar criteria = " . json_encode($criteriaAttr, false) . ";\nvar baseUrl = '" . Yii::app()->baseUrl . "';\n"; $headjs .= <<<EOB function deleteCriterion(object) { if(\$('#list-criteria li').length == 2) // prevent people from deleting the last criterion \$('#list-criteria a.del').fadeOut(300); \$(object).closest('li').animate({ opacity: 0, height: 0
public function afterSave($event) { $oldAttributes = $this->owner->getOldAttributes(); $linkFields = Fields::model()->findAllByAttributes(array('modelName' => get_class($this->owner), 'type' => 'link')); foreach ($linkFields as $field) { $nameAndId = Fields::nameAndId($this->owner->getAttribute($field->fieldName)); $oldNameAndId = Fields::nameAndId(isset($oldAttributes[$field->fieldName]) ? $oldAttributes[$field->fieldName] : ''); if (!empty($oldNameAndId[1]) && $nameAndId[1] !== $oldNameAndId[1]) { $oldTarget = X2Model::model($field->linkType)->findByPk($oldNameAndId[1]); $this->owner->deleteRelationship($oldTarget); } $newTarget = X2Model::model($field->linkType)->findByPk($nameAndId[1]); $this->owner->createRelationship($newTarget); } parent::afterSave($event); }
/** * Convenience method to retrieve a Campaign model by id. Filters by the current user's permissions. * * @param integer $id Model id * @return Campaign */ public static function load($id) { $model = X2Model::model('Campaign'); return $model->with('list')->findByPk((int) $id, $model->getAccessCriteria()); }
* 02110-1301 USA. * * You can contact X2Engine, Inc. P.O. Box 66752, Scotts Valley, * California 95067, USA. or at email address contact@x2engine.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * X2Engine" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by X2Engine". *****************************************************************************************/ $user = X2Model::model('User')->findByPk(Yii::app()->user->getId()); $showCalendars = json_decode($user->showCalendars, true); // list of user calendars current user can edit $editableUserCalendars = X2CalendarPermissions::getEditableUserCalendarNames(); // User Calendars if (isset($this->calendarUsers) && $this->calendarUsers !== null) { // actionTogglePortletVisible is defined in calendar controller $toggleUserCalendarsVisibleUrl = $this->createUrl('togglePortletVisible', array('portlet' => 'userCalendars')); $visible = Yii::app()->params->profile->userCalendarsVisible; $this->beginWidget('LeftWidget', array('widgetLabel' => Yii::t('calendar', 'User {calendars}', array('{calendars}' => Modules::displayName() . "s")), 'widgetName' => 'UserCalendars', 'id' => 'user-calendars')); $showUserCalendars = $showCalendars['userCalendars']; echo '<ul style="font-size: 0.8em; font-weight: bold; color: black;">'; foreach ($this->calendarUsers as $userName => $user) { if ($user == 'Anyone') { $user = Yii::t('app', $user); }
// commented out since default logo size is different than display size // find out the dimensions of the user-uploaded logo so the menu can do its layout calculations $logoOptions = array(); if(is_file(Yii::app()->params->logo)){ $logoSize = @getimagesize(Yii::app()->params->logo); if($logoSize) $logoSize = array(min($logoSize[0], 200), min($logoSize[1], 30)); else $logoSize = array(92, 30); $logoOptions['width'] = $logoSize[0]; $logoOptions['height'] = $logoSize[1]; }*/ /* Construction of the user menu */ $notifCount = X2Model::model('Notification')->countByAttributes(array('user' => Yii::app()->user->getName()), 'createDate < ' . time()); $searchbarHtml = CHtml::beginForm(array('/search/search'), 'get') . '<button class="x2-button black" type="submit"><span></span></button>' . CHtml::textField('term', Yii::t('app', 'Search for contact, action, deal...'), array('id' => 'search-bar-box', 'onfocus' => 'x2.forms.toggleTextResponsive(this);', 'onblur' => 'x2.forms.toggleTextResponsive(this);', 'data-short-default-text' => Yii::t('app', 'Search'), 'data-long-default-text' => Yii::t('app', 'Search for contact, action, deal...'), 'autocomplete' => 'off')) . '</form>'; if (!empty($profile->avatar) && file_exists($profile->avatar)) { $avatar = Profile::renderAvatarImage($profile->id, 25, 25); } else { $avatar = X2Html::defaultAvatar(25); } $widgetsImageUrl = $themeUrl . '/images/admin_settings.png'; if (!Yii::app()->user->isGuest) { $widgetMenu = $profile->getWidgetMenu(); } else { $widgetMenu = ""; } $userMenu = array(array('label' => Yii::t('app', 'Admin'), 'url' => array('/admin/index'), 'active' => $module == 'admin' ? true : null, 'visible' => $isAdmin, 'itemOptions' => array('id' => 'admin-user-menu-link', 'class' => 'user-menu-link ' . ($isAdmin ? 'x2-first' : ''))), array('label' => Yii::t('app', 'Profile'), 'url' => array('/profile/view', 'id' => Yii::app()->user->getId()), 'itemOptions' => array('id' => 'profile-user-menu-link', 'class' => 'user-menu-link ' . ($isAdmin ? '' : 'x2-first'))), array('label' => Yii::t('app', 'Users'), 'url' => array('/users/users/admin'), 'visible' => $isAdmin, 'itemOptions' => array('id' => 'admin-users-user-menu-link', 'class' => 'user-menu-link')), array('label' => Yii::t('app', 'Users'), 'url' => array('/profile/profiles'), 'visible' => !$isAdmin, 'itemOptions' => array('id' => 'non-admin-users-user-menu-link', 'class' => 'user-menu-link')), array('label' => $searchbarHtml, 'itemOptions' => array('id' => 'search-bar', 'class' => 'special'))); $userMenuItems = array(array('label' => Yii::t('app', 'Profile'), 'url' => array('/profile/view', 'id' => Yii::app()->user->getId())), array('label' => Yii::t('app', 'Notifications'), 'url' => array('/site/viewNotifications')), array('label' => Yii::t('app', 'Preferences'), 'url' => array('/profile/settings')), array('label' => Yii::t('profile', 'Manage Apps'), 'url' => array('/profile/manageCredentials')), array('label' => Yii::t('help', 'Icon Reference'), 'url' => array('/site/page', 'view' => 'iconreference')), array('label' => Yii::t('help', 'Help'), 'url' => 'http://www.x2crm.com/reference_guide', 'linkOptions' => array('target' => '_blank')), array('label' => Yii::t('app', 'Report A Bug'), 'url' => array('/site/bugReport')), array('label' => Yii::t('app', '---'), 'itemOptions' => array('class' => 'divider')), array('label' => Yii::app()->params->sessionStatus ? Yii::t('app', 'Go Invisible') : Yii::t('app', 'Go Visible'), 'url' => '#', 'linkOptions' => array('submit' => array('/site/toggleVisibility', 'visible' => !Yii::app()->params->sessionStatus, 'redirect' => Yii::app()->request->requestUri), 'csrf' => true, 'confirm' => 'Are you sure you want to toggle your session status?')), array('label' => Yii::t('app', 'Logout'), 'url' => array('/site/logout'))); if (!$isGuest) {
public function getMessage() { if (empty($this->modelId) || empty($this->modelType)) { // skip if there is no association $record = null; } else { if (class_exists($this->modelType)) { $record = X2Model::model($this->modelType)->findByPk($this->modelId); } else { return 'Error: unknown record <b>' . $this->modelType . '</b>'; } if ($record === null) { $this->delete(); return null; } } if (!isset($record) && $this->type !== 'lead_failure' && $this->type !== 'custom') { // return var_dump($this->attributes); return null; } $passive = $this->createdBy === 'API' || empty($this->createdBy); switch ($this->type) { case 'action_complete': if ($passive) { return Yii::t('actions', 'Action completed: {action}', array('{action}' => $record->getLink())); } else { return Yii::t('actions', '{user} completed an action: {action}', array('{user}' => User::getUserLinks($record->completedBy), '{action}' => $record->getLink(20))); } case 'action_reminder': return Yii::t('actions', '<b>Reminder!</b> The following action is due: {action}', array('{action}' => $record->getLink())); // case 'workflow_complete': // if($passive) // return Yii::t('actions','Stage {n}: {stage} was completed for {record}',array('{record}'=>$record->getLink())); // else // return Yii::t('actions','{user} completed stage {n}: {stage} was completed for {record}',array('{record}'=>$record->getLink())); // case 'workflow_complete': // if($passive) // return Yii::t('actions','Stage {n}: {stage} was completed for {record}',array('{record}'=>$record->getLink())); // else // return Yii::t('actions','{user} completed stage {n}: {stage} was completed for {record}',array('{record}'=>$record->getLink())); case 'create': return Yii::t('app', 'New record assigned to you: {link}.', array('{link}' => $record->getLink())); case 'change': if ($this->comparison == 'change') { $msg = $passive ? '{record}\'s {field} was changed to {value}' : '{user} changed {record}\'s {field} to {value}'; return Yii::t('app', $msg, array('{field}' => $record->getAttributeLabel($this->fieldName), '{value}' => $record->renderAttribute($this->fieldName, true, true), '{record}' => $record->getLink(), '{user}' => Yii::app()->user->getName() == $this->createdBy ? CHtml::link('You', array('/profile/view', 'id' => Yii::app()->user->getId())) : User::getUserLinks($this->createdBy))); } else { // > < = $msg = $passive ? '{record}\'s {field} was changed to {value}' : '{user} changed {record}\'s {field} to {value}'; return Yii::t('app', $msg, array('{field}' => $record->getAttributeLabel($this->fieldName), '{value}' => $record->renderAttribute($this->fieldName, true, true), '{record}' => $record->getLink(), '{user}' => Yii::app()->user->getName() == $this->createdBy ? CHtml::link('You', array('/profile/view', 'id' => Yii::app()->user->getId())) : User::getUserLinks($this->createdBy))); } case 'lead_failure': return Yii::t('app', 'A lead failed to come through Lead Capture. Check {link} to recover it.', array('{link}' => CHtml::link(Yii::t('app', 'here'), Yii::app()->controller->createUrl('/contacts/contacts/cleanFailedLeads')))); case 'assignment': if ($passive) { return Yii::t('app', 'You have been assigned a record: {record}', array('{record}' => $record->getLink())); } else { return Yii::t('app', '{user} assigned a record to you: {record}', array('{user}' => User::getUserLinks($this->createdBy), '{record}' => $record->getLink())); } case 'delete': if ($passive) { return Yii::t('app', 'Record deleted: {record}', array('{record}' => $this->modelType . ' ' . $this->modelId)); } else { return Yii::t('app', '{user} deleted a record: {record}', array('{user}' => User::getUserLinks($this->createdBy), '{record}' => $this->modelType . ' ' . $this->modelId)); } case 'event_broadcast': return Yii::t('app', '{user} broadcast an event: {event}', array('{user}' => User::getUserLinks($record->user), '{event}' => $record->getText())); case 'update': if ($passive) { return Yii::t('app', 'Record updated: {record}', array('{record}' => $record->getLink())); } else { return Yii::t('app', '{user} updated a record: {record}', array('{user}' => User::getUserLinks($this->createdBy), '{record}' => $record->getLink())); } case 'dup_discard': if ($passive) { return Yii::t('app', 'A record has been marked as a duplicate and hidden to everyone but the admin: {record}', array('{record}' => $record->getLink())); } else { return Yii::t('app', '{user} marked a record as a duplicate. This record is hidden to everyone but the admin: {record}', array('{user}' => User::getUserLinks($this->createdBy), '{record}' => $record->getLink())); } case 'email_clicked': return Yii::t('app', '{record} clicked an email link: {campaign}', array('{record}' => $record->getLink(), '{campaign}' => $this->value)); case 'email_opened': return Yii::t('app', '{record} opened an email: {campaign}', array('{record}' => $record->getLink(), '{campaign}' => $this->value)); case 'email_unsubscribed': return Yii::t('app', '{record} unsubscribed from a campaign: {campaign}', array('{record}' => $record->getLink(), '{campaign}' => $this->value)); case 'social_post': return Yii::t('app', '{user} posted on {link}', array('{user}' => User::getUserLinks($this->createdBy), '{link}' => $record->getLink())); case 'social_comment': return Yii::t('app', '{user} replied on {link}', array('{user}' => User::getUserLinks($this->createdBy), '{link}' => $record->getLink())); case 'voip_call': return Yii::t('app', 'Incoming call from <b>{phone}</b> ({record}) {time}', array('{record}' => $record->getLink(), '{phone}' => $this->value, '{time}' => Formatter::formatDateDynamic($this->createDate))); case 'weblead': return Yii::t('app', 'New web lead: {link}.', array('{link}' => $record->getLink())); case 'webactivity': if ($record instanceof Actions) { if ($link = $record->getAssociationLink()) { return Yii::t('app', '{name} is currently on {url}', array('{name}' => $link, '{url}' => $record->actionDescription)); } } elseif ($record instanceof Contacts) { return Yii::t('app', '{name} is currently on your website.', array('{name}' => $record->getLink())); } return null; case 'escalateCase': return Yii::t('app', '{user} escalated a Service Case to you: {record}', array('{user}' => User::getUserLinks($this->createdBy), '{record}' => $record->createLink())); case 'custom': return $this->text; default: return 'Error: unknown type <b>' . $this->type . '</b>'; } }
public function actionDeleteAction() { if (isset($_POST['id'])) { $id = $_POST['id']; $action = Actions::model()->findByPk($id); $profile = Profile::model()->findByAttributes(array('username' => $action->assignedTo)); if (isset($profile)) { $profile->deleteGoogleCalendarEvent($action); } // update action in Google Calendar if user has a Google Calendar X2Model::model('Events')->deleteAllByAttributes(array('associationType' => 'Actions', 'type' => 'calendar_event', 'associationId' => $action->id)); $action->delete(); } }
/** * Save associated criterion objects for a dynamic list * * Takes data from the dynamic list criteria designer form and turns them * into {@link X2ListCriterion} records. */ public function processCriteria() { X2ListCriterion::model()->deleteAllByAttributes(array('listId' => $this->id)); // delete old criteria foreach (array('attribute', 'comparison', 'value') as $property) { // My lazy refactor: bring properties into the current scope as // temporary variables with their names pluralized ${"{$property}s"} = $this->criteriaInput[$property]; } $comparisonList = self::getComparisonList(); $contactModel = Contacts::model(); $fields = $contactModel->getFields(true); for ($i = 0; $i < count($attributes); $i++) { // create new criteria if ((array_key_exists($attributes[$i], $contactModel->attributeLabels()) || $attributes[$i] == 'tags') && array_key_exists($comparisons[$i], $comparisonList)) { $fieldRef = isset($fields[$attributes[$i]]) ? $fields[$attributes[$i]] : null; if ($fieldRef instanceof Fields && $fieldRef->type == 'link') { $nameList = explode(',', $values[$i]); $namesParams = AuxLib::bindArray($nameList); $namesIn = AuxLib::arrToStrList(array_keys($namesParams)); $lookupModel = X2Model::model(ucfirst($fieldRef->linkType)); $lookupModels = $lookupModel->findAllBySql('SELECT * FROM `' . $lookupModel->tableName() . '` ' . 'WHERE `name` IN ' . $namesIn, $namesParams); if (!empty($lookupModels)) { $values[$i] = implode(',', array_map(function ($m) { return $m->nameId; }, $lookupModels)); //$lookup->nameId; } } $criterion = new X2ListCriterion(); $criterion->listId = $this->id; $criterion->type = 'attribute'; $criterion->attribute = $attributes[$i]; $criterion->comparison = $comparisons[$i]; $criterion->value = $values[$i]; $criterion->save(); } } }
public function getInsertableAttributeTokens() { X2Model::$getInsertableAttributeTokensDepth++; $tokens = array(); if (X2Model::$getInsertableAttributeTokensDepth > 2) { return $tokens; } // simple tokens $tokens = array_merge($tokens, array_map(function ($elem) { return '{' . $elem . '}'; }, $this->attributeNames())); // assignment tokens if (X2Model::$getInsertableAttributeTokensDepth < 2) { $assignmentFields = array_filter($this->fields, function ($elem) { return $elem->type === 'assignment'; }); foreach ($assignmentFields as $field) { $assignmentModel = X2Model::model('Profile'); $tokens = array_merge($tokens, array_map(function ($elem) use($field) { return '{' . $field->fieldName . '.' . $elem . '}'; }, $assignmentModel->attributeNames())); } } // link tokens if (X2Model::$getInsertableAttributeTokensDepth < 2) { $linkFields = array_filter($this->fields, function ($elem) { return $elem->type === 'link'; }); foreach ($linkFields as $field) { $linkModelName = $field->linkType; $linkModel = $linkModelName::model(); $tokens = array_merge($tokens, array_map(function ($elem) use($field) { return '{' . $field->fieldName . '.' . preg_replace('/\\{|\\}/', '', $elem) . '}'; }, $linkModel->getInsertableAttributeTokens())); } } X2Model::$getInsertableAttributeTokensDepth--; return $tokens; }
/** * Deletes a particular model. * If deletion is successful, the browser will be redirected to the 'admin' page. * @param integer $id the ID of the model to be deleted */ public function actionDelete($id) { if (Yii::app()->request->isPostRequest) { // we only allow deletion via POST request $links = GroupToUser::model()->findAllByAttributes(array('groupId' => $id)); foreach ($links as $link) { $link->delete(); } $contacts = X2Model::model('Contacts')->findAllByAttributes(array('assignedTo' => $id)); foreach ($contacts as $contact) { $contact->assignedTo = 'Anyone'; $contact->save(); } $this->loadModel($id)->delete(); // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser if (!isset($_GET['ajax'])) { $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index')); } } else { throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.'); } }
/** * Echo a list of model attributes as a dropdown. * * This method is called via AJAX as a part of creating notification criteria. * It takes the model or module name as POST data and returns a list of dropdown * options consisting of the fields available to that model. */ public function actionGetAttributes() { $data = array(); $type = null; if (isset($_POST['Criteria']['modelType'])) { $type = ucfirst($_POST['Criteria']['modelType']); } if (isset($_POST['Fields']['modelName'])) { $type = $_POST['Fields']['modelName']; } if (isset($type)) { if ($type == 'Marketing') { $type = 'Campaign'; } elseif ($type == 'Quotes') { $type = 'Quote'; } elseif ($type == 'Products') { $type = 'Product'; } elseif ($type == 'Opportunities') { $type = 'Opportunity'; } foreach (X2Model::model('Fields')->findAllByAttributes(array('modelName' => $type)) as $field) { if ($field->fieldName != 'id') { if (isset($_POST['Criteria'])) { $data[$field->fieldName] = $field->attributeLabel; } else { $data[$field->id] = $field->attributeLabel; } } } } asort($data); $data = array('' => '-') + $data; $htmlOptions = array(); echo CHtml::listOptions('', $data, $htmlOptions); }
public static function editContactsInverse($arr) { $data = array(); foreach ($arr as $id) { if ($id != '') { $data[] = X2Model::model('Contacts')->findByPk($id); } } $temp = array(); foreach ($data as $item) { $temp[$item->id] = $item->firstName . ' ' . $item->lastName; } return $temp; }