예제 #1
0
 /**
  * Test subscribing and then receiving data:
  */
 public function testSubscription()
 {
     // 1: Request to subscribe:
     $hookName = 'ContactsCreate';
     $hook = array('event' => 'RecordCreateTrigger', 'target_url' => TEST_WEBROOT_URL . '/api2HooksTest.php?name=' . $hookName);
     $ch = $this->getCurlHandle('POST', array('{suffix}' => ''), 'admin', $hook, array(CURLOPT_HEADER => 1));
     $response = curl_exec($ch);
     $this->assertResponseCodeIs(201, $ch, VERBOSE_MODE ? $response : '');
     $trigger = ApiHook::model()->findByAttributes($hook);
     // 2. Create a contact
     $contact = array('firstName' => 'Walter', 'lastName' => 'White', 'email' => '*****@*****.**', 'visibility' => 1);
     $ch = curl_init(TEST_BASE_URL . 'api2/Contacts');
     $options = array(CURLOPT_POSTFIELDS => json_encode($contact), CURLOPT_HTTPHEADER => array('Content-Type: application/json'), CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => true);
     foreach ($this->authCurlOpts() as $opt => $optVal) {
         $options[$opt] = $optVal;
     }
     curl_setopt_array($ch, $options);
     $response = curl_exec($ch);
     $c = Contacts::model()->findByAttributes($contact);
     $this->assertResponseCodeIs(201, $ch);
     $this->assertNotEmpty($c);
     // 3. Test that the receiving end got the payload
     $outputDir = implode(DIRECTORY_SEPARATOR, array(Yii::app()->basePath, 'tests', 'data', 'output'));
     $this->assertFileExists($outputDir . DIRECTORY_SEPARATOR . "hook_{$hookName}.json");
     $contactPulled = json_decode(file_get_contents($outputDir . DIRECTORY_SEPARATOR . "hook_pulled_{$hookName}.json"), 1);
     foreach ($contact as $field => $value) {
         $this->assertEquals($value, $contactPulled[$field]);
     }
 }
예제 #2
0
 private function fetchSpecificContact()
 {
     $con_model = Contacts::model()->findAllByAttributes($this->contacts);
     foreach ($con_model as $data) {
         $this->data[] = $data->attributes;
     }
 }
예제 #3
0
 /**
  * Ensure that update and create trigger appropriate flows
  */
 public function testContacts()
 {
     X2FlowTestingAuxLib::clearLogs($this);
     $this->action = 'model';
     $this->assertEquals(array(), TriggerLog::model()->findAll());
     // Create
     $contact = array('firstName' => 'Walt', 'lastName' => 'White', 'email' => '*****@*****.**', 'visibility' => 1, 'trackingKey' => '1234');
     $ch = $this->getCurlHandle('POST', array('{modelAction}' => 'Contacts'), 'admin', $contact);
     $response = json_decode(curl_exec($ch), 1);
     $id = $response['id'];
     $this->assertResponseCodeIs(201, $ch);
     $this->assertTrue((bool) ($newContact = Contacts::model()->findBySql('SELECT * FROM x2_contacts
             WHERE firstName="Walt" 
             AND lastName="White" 
             AND email="*****@*****.**"
             AND trackingKey="1234"')));
     $logs = TriggerLog::model()->findAll();
     $this->assertEquals(1, count($logs));
     $trace = X2FlowTestingAuxLib::getTraceByFlowId($this->flows('flow1')->id);
     $this->assertTrue(is_array($trace));
     $this->assertTrue(X2FlowTestingAuxLib::checkTrace($trace));
     // Update
     $contact['firstName'] = 'Walter';
     $ch = $this->getCurlHandle('PUT', array('{modelAction}' => "Contacts/{$id}.json"), 'admin', $contact);
     $response = json_decode(curl_exec($ch), 1);
     $this->assertResponseCodeIs(200, $ch);
     $newContact->refresh();
     $this->assertEquals($contact['firstName'], $newContact['firstName']);
     $logs = TriggerLog::model()->findAll();
     $this->assertEquals(2, count($logs));
     $trace = X2FlowTestingAuxLib::getTraceByFlowId($this->flows('flow2')->id);
     $this->assertTrue(is_array($trace));
     $this->assertTrue(X2FlowTestingAuxLib::checkTrace($trace));
 }
예제 #4
0
 public function run()
 {
     $actionParams = Yii::app()->controller->getActionParams();
     $address = '';
     if (Yii::app()->controller->module != null && Yii::app()->controller->module->id == 'contacts' && Yii::app()->controller->action->id == 'view' && isset($actionParams['id'])) {
         // must have an actual ID value
         $currentRecord = Contacts::model()->findByPk($actionParams['id']);
         if (!empty($currentRecord->city)) {
             if (!empty($currentRecord->address)) {
                 $address .= $currentRecord->address . ', ';
             }
             $address .= $currentRecord->city . ', ';
         }
         if (!empty($currentRecord->state)) {
             $address .= $currentRecord->state . ' ';
         }
         if (!empty($currentRecord->zipcode)) {
             $address .= $currentRecord->zipcode . ' ';
         }
         if (!empty($currentRecord->country)) {
             $address .= $currentRecord->country;
         }
     }
     $this->render('googleMaps', array('address' => $address));
 }
예제 #5
0
 private static function setRecipients()
 {
     if (self::$model->recipients_source === MsgSmsOutbox::RECIPIENTS_SOURCE_GROUPS) {
         if (empty(self::$model->group_id)) {
             throw new CException("group_id cannot be empty");
         }
         self::$model->recipients = ContactsInGroupView::model()->getPhoneNumbers(self::$model->group_id);
     } else {
         if (self::$model->recipients_source === MsgSmsOutbox::RECIPIENTS_SOURCE_PHONEBOOK) {
             self::$model->recipients = Contacts::model()->getAllPhoneNumbers(self::$model->org_id);
         }
     }
 }
예제 #6
0
 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 = Contacts::model()->findByPk($actionParams['id']);
         if (!empty($currentRecord->twitter)) {
             $twitter = $currentRecord->twitter;
         }
     }
     $this->render('twitterFeed', array('twitter' => $twitter));
 }
예제 #7
0
 private function deleteContact($con)
 {
     //var_dump($con);
     //exit;
     $con_model = \Contacts::model()->findAllByAttributes($con);
     foreach ($con_model as $data) {
         try {
             if (!$data->delete()) {
                 new \Error(5, null, json_encode($data->getErrors()));
             }
         } catch (Exception $e) {
             new \Error(5, null, $e->getMessage());
         }
     }
 }
예제 #8
0
 public function actionWhatsNew()
 {
     if (!Yii::app()->user->isGuest) {
         $user = User::model()->findByPk(Yii::app()->user->getId());
         $lastLogin = $user->lastLogin;
         $contacts = Contacts::model()->findAll("lastUpdated > {$lastLogin} ORDER BY lastUpdated DESC LIMIT 50");
         $actions = Actions::model()->findAll("lastUpdated > {$lastLogin} AND (assignedTo='" . Yii::app()->user->getName() . "' OR assignedTo='Anyone') ORDER BY lastUpdated DESC LIMIT 50");
         $sales = Sales::model()->findAll("lastUpdated > {$lastLogin} ORDER BY lastUpdated DESC LIMIT 50");
         $accounts = Accounts::model()->findAll("lastUpdated > {$lastLogin} ORDER BY lastUpdated DESC LIMIT 50");
         $arr = array_merge($contacts, $actions, $sales, $accounts);
         $records = Record::convert($arr);
         $dataProvider = new CArrayDataProvider($records, array('id' => 'id', 'pagination' => array('pageSize' => ProfileChild::getResultsPerPage()), 'sort' => array('attributes' => array('lastUpdated', 'name'))));
         $this->render('whatsNew', array('records' => $records, 'dataProvider' => $dataProvider));
     } else {
         $this->redirect('login');
     }
 }
예제 #9
0
 public function actionIndex()
 {
     //$this->render('index');
     $this->prepareContacts();
     $this->prepareNewContacts();
     $con_model = \Contacts::model()->findAllByAttributes($this->contacts);
     if (count($con_model) == 0) {
         new \Error(5, null, "no such contacts");
     }
     foreach ($con_model as $data) {
         $data->attributes = $this->newContacts;
         try {
             if (!$data->save()) {
                 new \Error(5, null, json_encode($data->getErrors()));
             }
         } catch (Exception $e) {
             new \Error(5, null, $e->getMessage());
         }
     }
     new \Error(1);
 }
예제 #10
0
 public function run()
 {
     $contact = array();
     $address = '';
     $array = array();
     $lat = '';
     //For Profile
     $lang = Yii::app()->language;
     $actionParams = Yii::app()->controller->getActionParams();
     if (Yii::app()->controller->module != null && Yii::app()->controller->module->id == 'contacts' && Yii::app()->controller->action->id == 'view' && isset($actionParams['id'])) {
         // must have an actual ID value
         $currentRecord = Contacts::model()->findByPk($actionParams['id']);
         if (empty($currentRecord->timezone)) {
             //Compose an address to be appended to google maps URL to be
             //implemented through the google api.
             if (!empty($currentRecord->city)) {
                 if (!empty($currentRecord->address)) {
                     $address .= $currentRecord->address . ',+';
                 }
                 $address .= $currentRecord->city . ',+';
             }
             if (!empty($currentRecord->state)) {
                 $address .= $currentRecord->state;
             }
             $address = str_replace(" ", "+", $address);
             $address .= "&sensor=true";
             //Necessary to obtain privilege to see results.
             $address .= "&region=" . $lang;
             //If contact isn't in the US, find location.
             $url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $address;
             //Set up a way to obtain results from URL
             $ch = curl_init();
             $timeout = 5;
             curl_setopt($ch, CURLOPT_URL, $url);
             curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
             curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
             $data = curl_exec($ch);
             $array = CJSON::decode($data, false);
             //Get latitude and longitude from results.
             if (isset($array->results[0])) {
                 $long = $array->results[0]->geometry->location->lng;
                 $lat = $array->results[0]->geometry->location->lat;
                 //Use of earth tools api to obtain time zone.
                 $url = "http://www.earthtools.org/timezone/" . $lat . "/" . $long;
                 curl_setopt($ch, CURLOPT_URL, $url);
                 $data = curl_exec($ch);
                 $contact = (array) simplexml_load_string($data);
                 $offset = $contact["offset"];
                 $retVL = strstr($offset, ".");
                 if ($retVL == FALSE) {
                     $value = intval($offset);
                     if ($value < 12) {
                         $currentRecord->timezone = "UTC-0" . $offset . ":00";
                     } else {
                         $currentRecord->timezone = "UTC-" . $offset . ":00";
                     }
                     $currentRecord->save();
                 } else {
                     $retVLFIRST = strstr($offset, ".", true);
                     $valueFIRST = intval($retVLFIRST);
                     $valueSEC = intval($retVL);
                     $append = "";
                     if ($retVL == 50) {
                         $append = "30";
                     } else {
                         if ($retVL == 66) {
                             $append = "45";
                         }
                     }
                     if ($valueFIRST < 12) {
                         $currentRecord->timezone = "UTC-0" . $valueFIRST . ":" . $append;
                     } else {
                         $currentRecord->timezone = "UTC-" . $valueSEC . ":" . $append;
                     }
                 }
                 $contact = $currentRecord->timezone;
             }
         } else {
             $contact = $currentRecord->timezone;
         }
     }
     $this->render('timeZone', array('contact' => $contact));
 }
예제 #11
0
 /**
  * To be called after submitWebForm to assert that contact was created by web form submission 
  * @return Contact the contact that was created
  */
 protected function assertContactCreated()
 {
     $contact = Contacts::model()->findByAttributes(array('firstName' => 'test', 'lastName' => 'test', 'email' => '*****@*****.**'));
     $this->assertTrue($contact !== null);
     X2_TEST_DEBUG_LEVEL > 1 && println('contact created. new contact\'s tracking key = ' . $contact->trackingKey);
     return $contact;
 }
예제 #12
0
파일: X2List.php 프로젝트: xl602/X2CRM
 /**
  * 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();
         }
     }
 }
예제 #13
0
 protected function Getorgan()
 {
     //获取自身机构ID
     $organID = Yii::app()->user->getOrganID();
     $businessContacts = Contacts::model()->findAll('OrganID=:organID and Status=:stu', array(':organID' => $organID, ':stu' => '0'));
     foreach ($businessContacts as $val) {
         if ($val['ContactID']) {
             $ids[] = $val['ContactID'];
         }
     }
     //新增的联系人不能是本人
     $ids[] = $organID;
     $ids = implode(',', $ids);
     $result = Organ::model()->findAll("ID not in({$ids}) and !ISNULL(OrganName)");
     return $result;
 }
예제 #14
0
파일: Docs.php 프로젝트: keyeMyria/CRM
 /**
  * Replace tokens with model attribute values.
  *
  * @param type $str Input text
  * @param X2Model $model Model to use for replacement
  * @param array $vars List of extra variables to replace
  * @param bool $encode Encode replacement values if true; use renderAttribute otherwise.
  * @return string
  */
 public static function replaceVariables($str, $model, $vars = array(), $encode = false, $renderFlag = true)
 {
     if ($encode) {
         foreach (array_keys($vars) as $key) {
             $vars[$key] = CHtml::encode($vars[$key]);
         }
     }
     $str = strtr($str, $vars);
     // replace any manually set variables
     if ($model instanceof X2Model) {
         if (get_class($model) !== 'Quote') {
             $str = Formatter::replaceVariables($str, $model, '', $renderFlag, false);
         } else {
             // Specialized, separate method for quotes that can use details from
             // either accounts or quotes.
             // There may still be some stray quotes with 2+ contacts on it, so
             // explode and pick the first to be on the safe side. The most
             // common use case by far is to have only one contact on the quote.
             $accountId = $model->accountName;
             $staticModels = array('Contact' => Contacts::model(), 'Account' => Accounts::model(), 'Quote' => Quote::model());
             $models = array('Contact' => $model->contact, 'Account' => empty($accountId) ? null : $staticModels['Account']->findByAttributes(array('nameId' => $accountId)), 'Quote' => $model);
             $attributes = array();
             foreach ($models as $name => $modelObj) {
                 $moduleRef = Modules::displayName(false, $name . "s");
                 if (empty($modelObj)) {
                     // Model will be blank
                     foreach ($staticModels[$name]->fields as $field) {
                         $attributes['{' . $moduleRef . '.' . $field->fieldName . '}'] = '';
                     }
                 } else {
                     // Insert attributes
                     foreach ($modelObj->attributes as $fieldName => $value) {
                         if ($renderFlag) {
                             $attributes['{' . $moduleRef . '.' . $fieldName . '}'] = $modelObj->renderAttribute($fieldName, false, true, $encode);
                         } else {
                             $attributes['{' . $moduleRef . '.' . $fieldName . '}'] = $modelObj->getAttribute($fieldName);
                         }
                     }
                 }
             }
             $quoteTitle = Modules::displayName(false, "Quotes");
             $quoteParams = array('{' . $quoteTitle . '.lineItems}' => $model->productTable(true), '{' . $quoteTitle . '.dateNow}' => date("F d, Y", time()), '{' . $quoteTitle . '.quoteOrInvoice}' => Yii::t('quotes', $model->type == 'invoice' ? 'Invoice' : $quoteTitle));
             // Run the replacement:
             $str = strtr($str, array_merge($attributes, $quoteParams));
             return $str;
         }
     }
     return $str;
 }
예제 #15
0
 public function run()
 {
     $preview = false;
     $emailBody = '';
     $signature = '';
     $template = null;
     if (!isset($this->model)) {
         $this->model = new InlineEmail();
     }
     if (isset($_POST['InlineEmail'])) {
         if (isset($_GET['preview']) || isset($_POST['InlineEmail']['submit']) && $_POST['InlineEmail']['submit'] == Yii::t('app', 'Preview')) {
             $preview = true;
         }
         $this->model->attributes = $_POST['InlineEmail'];
         // if the user specified a template, look it up and use it for the message
         if ($this->model->template != 0) {
             $matches = array();
             if (preg_match('/<!--BeginSig-->(.*)<!--EndSig-->/u', $this->model->message, $matches) && count($matches) > 1) {
                 // extract signature
                 $signature = $matches[1];
             }
             $this->model->message = preg_replace('/<!--BeginSig-->(.*)<!--EndSig-->/u', '', $this->model->message);
             // remove signatures
             $matches = array();
             if (preg_match('/<!--BeginMsg-->(.*)<!--EndMsg-->/u', $this->model->message, $matches) && count($matches) > 1) {
                 $this->model->message = $matches[1];
             }
             if (empty($signature)) {
                 $signature = Yii::app()->params->profile->getSignature(true);
             }
             // load default signature if empty
             $template = CActiveRecord::model('Docs')->findByPk($this->model->template);
             if (isset($template)) {
                 $this->model->message = str_replace('\\\\', '\\\\\\', $this->model->message);
                 $this->model->message = str_replace('$', '\\$', $this->model->message);
                 $emailBody = preg_replace('/{content}/u', '<!--BeginMsg-->' . $this->model->message . '<!--EndMsg-->', $template->text);
                 $emailBody = preg_replace('/{signature}/u', '<!--BeginSig-->' . $signature . '<!--EndSig-->', $emailBody);
                 // check if subject is empty, or is from another template
                 if (empty($this->model->subject) || CActiveRecord::model('Docs')->countByAttributes(array('type' => 'email', 'title' => $this->model->subject))) {
                     $this->model->subject = $template->title;
                 }
                 if (isset($this->model->modelName, $this->model->modelId)) {
                     // if there is a model name/id available, look it up and use its attributes
                     $targetModel = CActiveRecord::model($this->model->modelName)->findByPk($this->model->modelId);
                     if (isset($targetModel)) {
                         $attributes = $targetModel->getAttributes();
                         $attributeNames = array_keys($attributes);
                         $attributeNames[] = 'content';
                         $attributes = array_values($attributes);
                         $attributes[] = $this->model->message;
                         foreach ($attributeNames as &$name) {
                             $name = '/{' . $name . '}/';
                         }
                         unset($name);
                         $emailBody = preg_replace($attributeNames, $attributes, $emailBody);
                     }
                 }
                 // $this->model->template = 0;
                 $this->model->message = $emailBody;
             }
         } elseif (!empty($this->model->message)) {
             // if no template, use the user's custom message, and include a signature
             $emailBody = $this->model->message;
             // } elseif(!empty($this->model->message)) {	// if no template, use the user's custom message, and include a signature
             // $emailBody = $this->model->message.'<br><br>'.Yii::app()->params->profile->getSignature(true);
         }
         if ($this->model->template == 0) {
             $this->model->setScenario('custom');
         }
         if ($this->model->validate() && !$preview) {
             $this->model->status = $this->controller->sendUserEmail($this->model->mailingList, $this->model->subject, $emailBody);
             if (in_array('200', $this->model->status)) {
                 foreach ($this->model->mailingList['to'] as &$target) {
                     $contact = Contacts::model()->findByAttributes(array('email' => $target[1]));
                     if (isset($contact)) {
                         $action = new Actions();
                         $action->associationType = 'contacts';
                         $action->associationId = $contact->id;
                         $action->associationName = $contact->name;
                         $action->visibility = $contact->visibility;
                         $action->complete = 'Yes';
                         $action->type = 'email';
                         $action->completedBy = Yii::app()->user->getName();
                         $action->assignedTo = $contact->assignedTo;
                         $action->createDate = time();
                         $action->dueDate = time();
                         $action->completeDate = time();
                         if ($template == null) {
                             $action->actionDescription = '<b>' . $this->model->subject . "</b>\n\n" . $this->model->message;
                         } else {
                             $action->actionDescription = CHtml::link($template->title, array('/docs/' . $template->id));
                         }
                         if ($action->save()) {
                         }
                         // $message="2";
                         // $email=$toEmail;
                         // $id=$contact['id'];
                         // $note.="\n\nSent to Contact";
                     }
                 }
             }
         }
     }
     echo $this->controller->renderPartial('application.components.views.inlineEmailForm', array('model' => $this->model, 'preview' => $preview ? $emailBody : null));
     // }
 }
예제 #16
0
 public function testAfterSave()
 {
     $contact = $this->contact('testAnyone');
     $account = $this->account('account1');
     $account2 = $this->account('account2');
     $this->assertFalse($contact->relationships->hasRelationship($account));
     $contact->company = Fields::nameId($account->name, $account->id);
     $this->assertSaves($contact);
     $this->assertTrue($contact->relationships->hasRelationship($account));
     //Contact needs to be reloaded to refresh oldAttributes for afterSave
     $contact = Contacts::model()->findByPk($contact->id);
     $contact->company = Fields::nameId($account2->name, $account2->id);
     $this->assertSaves($contact);
     $this->assertFalse($contact->relationships->hasRelationship($account));
     $this->assertTrue($contact->relationships->hasRelationship($account2));
     $contact = Contacts::model()->findByPk($contact->id);
     $contact->company = NULL;
     $this->assertSaves($contact);
     $this->assertFalse($contact->relationships->hasRelationship($account));
     $this->assertFalse($contact->relationships->hasRelationship($account2));
 }
예제 #17
0
 public function testCustom()
 {
     $contact = Contacts::model()->findByPk(12345);
     $fields = $this->getAllFieldsOfType($contact, 'custom');
     foreach ($fields as $field) {
         $fieldName = $field->fieldName;
         if ($field->linkType === 'display') {
             $contact->{$fieldName} = '<b>{firstName}</b>';
         } elseif ($field->linkType === 'formula') {
             $contact->{$fieldName} = '={dealValue} + 5';
         } else {
             $contact->{$fieldName} = '';
         }
         $this->assertRender($contact, $fieldName);
     }
 }
예제 #18
0
 /**
  * @return bool false if any one of the recipient contacts has their doNotEmail field set to 
  *  true, true otherwise
  */
 public function checkDoNotEmailFields()
 {
     $allRecipientContacts = array();
     foreach ($this->recipients as $target) {
         foreach (Contacts::model()->findAllByAttributes(array('email' => $target[1]), 'visibility!=:private OR assignedTo!="Anyone"', array(':private' => X2PermissionsBehavior::VISIBILITY_PRIVATE)) as $contact) {
             $allRecipientContacts[] = $contact;
         }
     }
     if (array_reduce($allRecipientContacts, function ($carry, $item) {
         return $carry || $item->doNotEmail;
     }, false)) {
         return false;
     }
     return true;
 }
예제 #19
0
 public function loadModel($id)
 {
     $model = Contacts::model()->findByPk((int) $id);
     if ($model === null) {
         throw new CHttpException(404, 'The requested page does not exist.');
     }
     return $model;
 }
예제 #20
0
파일: webForm.php 프로젝트: keyeMyria/CRM
function renderFields($fieldList, $type, $form, $model, $contactFields = null)
{
    foreach ($fieldList as $field) {
        if (!isset($field['type']) || $field['type'] === 'normal') {
            if (isset($field['label']) && $field['label'] != '') {
                $label = '<label>' . $field['label'] . '</label>';
            } else {
                if ($type === 'service' && in_array($field['fieldName'], $contactFields)) {
                    $label = Contacts::model()->getAttributeLabel($field['fieldName']);
                } else {
                    $label = $form->labelEx($model, $field['fieldName']);
                }
            }
            // label already has a '*' to indicate it is required
            $starred = strpos($label, '*') !== false;
            ?>
            <div class="row">
                    <?php 
            echo $label;
            echo $field['required'] && !$starred ? '<span class="asterisk"> *</span>' : '';
            ?>
                <?php 
            if ($field['position'] == 'top') {
                ?>
                <br />
            <?php 
            }
            echo $form->error($model, $field['fieldName']);
            if ($type === 'service' && in_array($field['fieldName'], $contactFields)) {
                ?>
                <input type="text" name="Services[<?php 
                echo $field['fieldName'];
                ?>
]"
                value="<?php 
                echo isset($_POST['Services'][$field['fieldName']]) ? $_POST['Services'][$field['fieldName']] : '';
                ?>
" />
            <?php 
            } else {
                echo $model->renderInput($field['fieldName']);
            }
            ?>
            </div>
<?php 
        } elseif ($field['type'] === 'tags') {
            ?>
            <input type="hidden" name="tags" value="<?php 
            echo $field['label'];
            ?>
" />
            <?php 
        } elseif ($field['type'] === 'hidden') {
            $model->{$field['fieldName']} = $field['label'];
            echo $form->hiddenField($model, $field['fieldName']);
        }
    }
}
예제 #21
0
파일: _form.php 프로젝트: tymiles003/X2CRM
Yii::app()->clientScript->registerCss('docFormCss', "\n\n#doc-name,\n#email-to-field,\n#doc-subject {\n    width: 260px;\n}\n\n#create-button-container {\n    width: auto !important;\n    margin-top: 6px;\n}\n\n");
Yii::app()->clientScript->registerResponsiveCss('responsiveDocFormCss', "\n\n@media (max-width: 657px) {\n    #doc-name,\n    #email-to-field,\n    #doc-subject {\n        width:160px;\n    }\n}\n\n");
$modTitles = array('contact' => Modules::displayName(false, "Contacts"), 'account' => Modules::displayName(false, "Accounts"), 'quote' => Modules::displayName(false, "Quotes"));
$autosaveUrl = $this->createUrl('autosave') . '?id=' . $model->id;
$js = '';
if ($model->type === 'email' || $model->type === 'quote') {
    $attributes = array();
    if ($model->type === 'email') {
        foreach (X2Model::model('Contacts')->getAttributeLabels() as $fieldName => $label) {
            $attributes[$label] = '{' . $fieldName . '}';
        }
    } else {
        $accountAttributes = array();
        $contactAttributes = array();
        $quoteAttributes = array();
        foreach (Contacts::model()->getAttributeLabels() as $fieldName => $label) {
            AuxLib::debugLog('Iterating over contact attributes ' . $fieldName . '=>' . $label);
            $index = Yii::t('contacts', "{contact}", array('{contact}' => $modTitles['contact'])) . ": {$label}";
            $contactAttributes[$index] = "{associatedContacts.{$fieldName}}";
        }
        foreach (Accounts::model()->getAttributeLabels() as $fieldName => $label) {
            AuxLib::debugLog('Iterating over account attributes ' . $fieldName . '=>' . $label);
            $index = Yii::t('accounts', "{account}", array('{account}' => $modTitles['account'])) . ": {$label}";
            $accountAttributes[$index] = "{accountName.{$fieldName}}";
        }
        $Quote = Yii::t('quotes', "{quote}: ", array('{quote}' => $modTitles['quote']));
        $quoteAttributes[$Quote . Yii::t('quotes', "Item Table")] = '{lineItems}';
        $quoteAttributes[$Quote . Yii::t('quotes', "Date printed/emailed")] = '{dateNow}';
        $quoteAttributes[$Quote . Yii::t('quotes', '{quote} or Invoice', array('{quote}' => $modTitles['quote']))] = '{quoteOrInvoice}';
        foreach (Quote::model()->getAttributeLabels() as $fieldName => $label) {
            $index = $Quote . "{$label}";
예제 #22
0
 public function actionDelete()
 {
     switch ($_GET['model']) {
         // Load the respective model
         case 'Contacts':
             $model = Contacts::model()->findByPk($_GET['id']);
             break;
         case 'Actions':
             $model = Actions::model()->findByPk($_GET['id']);
             break;
         case 'Accounts':
             $model = Accounts::model()->findByPk($_GET['id']);
             break;
         default:
             $this->_sendResponse(501, sprintf('Error: Mode <b>delete</b> is not implemented for model <b>%s</b>', $_GET['model']));
             exit;
     }
     // Was a model found? If not, raise an error
     if (is_null($model)) {
         $this->_sendResponse(400, sprintf("Error: Didn't find any model <b>%s</b> with ID <b>%s</b>.", $_GET['model'], $_GET['id']));
     }
     // Delete the model
     $num = $model->delete();
     if ($num > 0) {
         $this->_sendResponse(200, sprintf("Model <b>%s</b> with ID <b>%s</b> has been deleted.", $_GET['model'], $_GET['id']));
     } else {
         $this->_sendResponse(500, sprintf("Error: Couldn't delete model <b>%s</b> with ID <b>%s</b>.", $_GET['model'], $_GET['id']));
     }
 }
예제 #23
0
 * 
 * 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".
 *****************************************************************************************/
$staticLinkModel = Contacts::model();
$this->widget('InlineEmailForm', array('attributes' => array('subject' => $model->subject, 'message' => $model->content, 'modelName' => 'Contacts', 'modelId' => null, 'credId' => $model->sendAs), 'postReplace' => 1, 'skipEvent' => 1, 'template' => Fields::id($model->template), 'insertableAttributes' => array(), 'startHidden' => true, 'associationType' => 'Contacts', 'type' => 'testCampaignEmail', 'specialFields' => '<div class="row">' . CHtml::hiddenField('InlineEmail[campaignId]', $model->id) . CHtml::label(Yii::t('contacts', '{module}', array('{module}' => Modules::displayName(false, "Contacts"))), 'Contacts[name]', array('class' => 'x2-email-label')) . $this->widget('zii.widgets.jui.CJuiAutoComplete', array('model' => Contacts::model(), 'attribute' => 'name', 'source' => $linkSource = Yii::app()->controller->createUrl($staticLinkModel->autoCompleteSource), 'options' => array('minLength' => '1', 'select' => 'js:function( event, ui ) {
                            $("#InlineEmail_modelId").val(ui.item.id);
                            $(this).val(ui.item.value);
                            $(this).data ("prev-val", $(this).val ());
                            return false;
                        }', 'change' => 'js:function (evt, ui) {
                            if ($(this).data ("prev-val") !== $(this).val ()) {
                                $("#InlineEmail_modelId").val("");
                            }
                            $(this).data ("prev-val", $(this).val ());
                        }', 'create' => 'js:function(event, ui) {
                            $(this).data( "uiAutocomplete" )._renderItem = function(ul,item) {
                                $(ul).addClass ("test-email-contact-ai");
                                return $("<li>").data("item.autocomplete",item).append(x2.forms.renderContactLookup(item)).appendTo(ul);
                            };
                        }'), 'htmlOptions' => array('style' => 'max-width:200px;', 'name' => 'InlineEmail[recordName]')), true) . X2Html::hint2(Yii::t('marketing', 'The {contact} you enter here will be used for variable replacement, ' . 'i.e. for "John Doe" the token {firstName} will get replaced with ' . '"John"', array('{contact}' => Modules::displayName(false, "Contacts")))) . '</div>'));
예제 #24
0
 * - Neither the name of X2Engine or X2CRM nor the names of its contributors may be 
 *   used to endorse or promote products derived from this software without 
 *   specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 ********************************************************************************/
$attributeLabels = Contacts::model()->attributeLabels();
$showSocialMedia = Yii::app()->params->profile->showSocialMedia;
Yii::app()->clientScript->registerScript('detailVewFields', "\n\nvar socialMediaOpen = true;\nvar socialMediaHeight = 0;\nfunction hideSocialMedia() {\n\tsocialMediaHeight = \$('#social-media').height();\n\t//\$('#social-media').hide();\n\t\$('#social-media').css('height',0);\n\t\$('#social-media').css('padding-bottom',0);\n\t\$('#social-media').css('border-bottom-width',0);\n\t\$('#social-media-minimize').html('[+]');\n\t//\$('#social-media-toggle').css('z-index','0');\n\t//\$('#social-media-toggle').css('border-bottom','1px solid #ddd');\n\tsocialMediaOpen = false;\n}\nfunction toggleSocialMedia() {\n\tvar button = \$('#social-media-minimize');\n\n\tif(socialMediaOpen) {\n\t\t\$('#social-media').stop();\n\t\t\$('#social-media').animate({height:0,paddingBottom:0},400,'swing', function() {\n\t\t\t\$('#social-media').hide();\n\t\t\t\$('#social-media-toggle').css('border-bottom-width','1px');\n\t\t});\n\t\t\n\t\tbutton.html('[+]');\n\t} else {\n\t\t\$('#social-media').show();\n\t\t\$('#social-media').stop();\n\t\t\$('#social-media').animate({height:socialMediaHeight,paddingBottom:5},400,'swing');\n\t\t\$('#social-media-toggle').css('border-bottom-width','0');\n\t\t\n\t\tbutton.html('[&ndash;]');\n\t}\n\n\tsocialMediaOpen = !socialMediaOpen;\n}\n" . ($showSocialMedia ? "\$(function() {socialMediaHeight = \$('#social-media').css('height'); });" : "\$(function(){hideSocialMedia();});"), CClientScript::POS_HEAD);
Yii::app()->clientScript->registerScript('stopEdit', '
	$(document).ready(function(){
		$("td#background a").click(function(e){
			e.stopPropagation();
		});
	});
');
function cleanupUrl($url)
{
    if (!preg_match('/(http)s?:\\/\\//i', $url)) {
        $url = 'http://' . $url;
    }
    return $url;
예제 #25
0
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 ********************************************************************************/
Yii::app()->clientScript->registerScript('updateWorkflow', "\n\nfunction startWorkflowStage(workflowId,stageNumber) {\n\t\$.ajax({\n\t\turl: '" . CHtml::normalizeUrl(array('workflow/startStage')) . "',\n\t\ttype: 'GET',\n\t\tdata: 'workflowId='+workflowId+'&stageNumber='+stageNumber+'&modelId=" . $model->id . "&type=quotes',\n\t\tsuccess: function(response) {\n\t\t\tif(response!='')\n\t\t\t\t\$('#workflow-diagram').html(response);\n\t\t}\n\t});\n}\n\nfunction completeWorkflowStage(workflowId,stageNumber) {\n\t\$.ajax({\n\t\turl: '" . CHtml::normalizeUrl(array('workflow/completeStage')) . "',\n\t\ttype: 'GET',\n\t\tdata: 'workflowId='+workflowId+'&stageNumber='+stageNumber+'&modelId=" . $model->id . "&type=quotes',\n\t\tsuccess: function(response) {\n\t\t\tif(response!='')\n\t\t\t\t\$('#workflow-diagram').html(response);\n\t\t}\n\t});\n}\n\nfunction revertWorkflowStage(workflowId,stageNumber) {\n\t\$.ajax({\n\t\turl: '" . CHtml::normalizeUrl(array('workflow/revertStage')) . "',\n\t\ttype: 'GET',\n\t\tdata: 'workflowId='+workflowId+'&stageNumber='+stageNumber+'&modelId=" . $model->id . "&type=quotes',\n\t\tsuccess: function(response) {\n\t\t\tif(response!='')\n\t\t\t\t\$('#workflow-diagram').html(response);\n\t\t}\n\t});\n}\n", CClientScript::POS_HEAD);
Yii::app()->clientScript->registerScript('detailVewFields', "\nfunction showField(field,focus){\n\t// \$(field).css('background','red');\n\t\$(field).find('.detail-field').hide();\n\t\$(field).find('.detail-form').show();\n\tif(focus)\n\t\t\$(field).find('input').focus();\n\thighlightSave();\n}\nfunction highlightSave() {\n\t\$('#save-changes').css('background','yellow');\n}\n", CClientScript::POS_HEAD);
Yii::app()->clientScript->registerScript('stopEdit', '
	$(document).ready(function(){
		$("td#description a").click(function(e){
			e.stopPropagation();
		});
	});
');
$relationships = Relationships::model()->findAllByAttributes(array('firstType' => 'quotes', 'firstId' => $model->id, 'secondType' => 'contacts'));
$associatedContacts = array();
foreach ($relationships as $relationship) {
    $contact = Contacts::model()->findByPk($relationship->secondId);
    $associatedContacts[] = CHtml::link($contact->name, array('contacts/view', 'id' => $contact->id));
}
$associatedContacts = implode(', ', $associatedContacts);
?>


<div class="x2-layout">
	<div class="formSection">
		<div class="formSectionHeader">
			<span class="sectionTitle">Basic Information</span>
		</div>
		<div class="tableWrapper">
			<tbody>
				<tr class="formSectionRow">
					<td style="width:300px">
예제 #26
0
 /**
  * Track when an email is viewed, a link is clicked, or the recipient unsubscribes
  *
  * Campaign emails include an img tag to a blank image to track when the message was opened,
  * an unsubscribe link, and converted links to track when a recipient clicks a link.
  * All those links are handled by this action.
  *
  * @param integer $uid The unique id of the recipient
  * @param string $type 'open', 'click', or 'unsub'
  * @param string $url For click types, this is the urlencoded URL to redirect to
  * @param string $email For unsub types, this is the urlencoded email address
  *  of the person unsubscribing
  */
 public function actionClick($uid, $type, $url = null, $email = null)
 {
     $now = time();
     $item = CActiveRecord::model('X2ListItem')->with('contact', 'list')->findByAttributes(array('uniqueId' => $uid));
     // It should never happen that we have a list item without a campaign,
     // but it WILL happen on any old db where x2_list_items does not cascade on delete
     // we can't track anything if the listitem was deleted, but at least prevent breaking links
     if ($item === null || $item->list->campaign === null) {
         if ($type == 'click') {
             // campaign redirect link click
             $this->redirect(urldecode($url));
         } elseif ($type == 'open') {
             //return a one pixel transparent gif
             header('Content-Type: image/gif');
             echo base64_decode('R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==');
         } elseif ($type == 'unsub' && !empty($email)) {
             Contacts::model()->updateAll(array('doNotEmail' => true), 'email=:email', array(':email' => $email));
             X2ListItem::model()->updateAll(array('unsubscribed' => time()), 'emailAddress=:email AND unsubscribed=0', array('email' => $email));
             $message = Yii::t('marketing', 'You have been unsubscribed');
             echo '<html><head><title>' . $message . '</title></head><body>' . $message . '</body></html>';
         }
         return;
     }
     $contact = $item->contact;
     $list = $item->list;
     $event = new Events();
     $notif = new Notification();
     $action = new Actions();
     $action->completeDate = $now;
     $action->complete = 'Yes';
     $action->updatedBy = 'API';
     $skipActionEvent = true;
     if ($contact !== null) {
         $skipActionEvent = false;
         if ($email === null) {
             $email = $contact->email;
         }
         $action->associationType = 'contacts';
         $action->associationId = $contact->id;
         $action->associationName = $contact->name;
         $action->visibility = $contact->visibility;
         $action->assignedTo = $contact->assignedTo;
         $event->associationId = $action->associationId;
         $event->associationType = 'Contacts';
         if ($action->assignedTo !== '' && $action->assignedTo !== 'Anyone') {
             $notif->user = $contact->assignedTo;
             $notif->modelType = 'Contacts';
             $notif->modelId = $contact->id;
             $notif->createDate = $now;
             $notif->value = $item->list->campaign->getLink();
         }
     } elseif ($list !== null) {
         $action = new Actions();
         $action->type = 'note';
         $action->createDate = $now;
         $action->lastUpdated = $now;
         $action->completeDate = $now;
         $action->complete = 'Yes';
         $action->updatedBy = 'admin';
         $action->associationType = 'X2List';
         $action->associationId = $list->id;
         $action->associationName = $list->name;
         $action->visibility = $list->visibility;
         $action->assignedTo = $list->assignedTo;
     }
     if ($type == 'unsub') {
         $item->unsubscribe();
         // find any weblists associated with the email address and create unsubscribe actions
         // for each of them
         $sql = 'SELECT t.* 
             FROM x2_lists as t 
             JOIN x2_list_items as li ON t.id=li.listId 
             WHERE li.emailAddress=:email AND t.type="weblist";';
         $weblists = Yii::app()->db->createCommand($sql)->queryAll(true, array('email' => $email));
         foreach ($weblists as $weblist) {
             $weblistAction = new Actions();
             $weblistAction->disableBehavior('changelog');
             //$weblistAction->id = 0; // this causes primary key contraint violation errors
             $weblistAction->isNewRecord = true;
             $weblistAction->type = 'email_unsubscribed';
             $weblistAction->associationType = 'X2List';
             $weblistAction->associationId = $weblist['id'];
             $weblistAction->associationName = $weblist['name'];
             $weblistAction->visibility = $weblist['visibility'];
             $weblistAction->assignedTo = $weblist['assignedTo'];
             $weblistAction->actionDescription = Yii::t('marketing', 'Campaign') . ': ' . $item->list->campaign->name . "\n\n" . $email . " " . Yii::t('marketing', 'has unsubscribed') . ".";
             $weblistAction->save();
         }
         $action->type = 'email_unsubscribed';
         $notif->type = 'email_unsubscribed';
         if ($contact === null) {
             $action->actionDescription = Yii::t('marketing', 'Campaign') . ': ' . $item->list->campaign->name . "\n\n" . $item->emailAddress . ' ' . Yii::t('marketing', 'has unsubscribed') . ".";
         } else {
             $action->actionDescription = Yii::t('marketing', 'Campaign') . ': ' . $item->list->campaign->name . "\n\n" . Yii::t('marketing', 'Contact has unsubscribed') . ".\n" . Yii::t('marketing', '\'Do Not Email\' has been set') . ".";
         }
         $message = Yii::t('marketing', 'You have been unsubscribed');
         echo '<html><head><title>' . $message . '</title></head><body>' . $message . '</body></html>';
     } elseif ($type == 'open') {
         //return a one pixel transparent gif
         header('Content-Type: image/gif');
         echo base64_decode('R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==');
         // Check if it has been marked as opened already, or if the contact
         // no longer exists. If so, exit; nothing more need be done.
         if ($item->opened != 0) {
             Yii::app()->end();
         }
         // This needs to happen before the skip option to accomodate the case of newsletters
         $item->markOpened();
         if ($skipActionEvent) {
             Yii::app()->end();
         }
         $action->disableBehavior('changelog');
         $action->type = 'campaignEmailOpened';
         $event->type = 'email_opened';
         $notif->type = 'email_opened';
         $event->save();
         if ($contact === null) {
             $action->actionDescription = Yii::t('marketing', 'Campaign') . ': ' . $item->list->campaign->name . "\n\n" . $item->emailAddress . ' ' . Yii::t('marketing', 'has opened the email') . ".";
         } else {
             $action->actionDescription = Yii::t('marketing', 'Campaign') . ': ' . $item->list->campaign->name . "\n\n" . Yii::t('marketing', 'Contact has opened the email') . ".";
         }
     } elseif ($type == 'click') {
         // redirect link click
         $item->markClicked($url);
         $action->type = 'email_clicked';
         $notif->type = 'email_clicked';
         if ($contact === null) {
             $action->actionDescription = Yii::t('marketing', 'Campaign') . ': ' . $item->list->campaign->name . "\n\n" . Yii::t('marketing', 'Contact has clicked a link') . ":\n" . urldecode($url);
         } else {
             $action->actionDescription = Yii::t('marketing', 'Campaign') . ': ' . $item->list->campaign->name . "\n\n" . $item->emailAddress . ' ' . Yii::t('marketing', 'has clicked a link') . ":\n" . urldecode($url);
         }
         $this->redirect(urldecode($url));
     }
     $action->save();
     // if any of these hasn't been fully configured
     $notif->save();
     // it will simply not validate and not be saved
 }
예제 #27
0
 public function testCompareAttribute()
 {
     $contact1 = $this->contact('testAnyone');
     $contact2 = $this->contact('testUser');
     $contact1->leadSource = 'Google';
     $this->assertSaves($contact1);
     $contact2->leadSource = 'Facebook';
     $this->assertSaves($contact2);
     $criteria = new CDbCriteria();
     $searchModel = new Contacts();
     $searchModel->leadSource = 'Google';
     $compareAttribute = TestingAuxLib::setPublic($searchModel, 'compareAttribute');
     $compareAttribute($criteria, $searchModel->getField('leadSource'));
     $contacts = Contacts::model()->findAll($criteria);
     $this->assertModelArrayEquality(array($contact1), $contacts);
     $criteria = new CDbCriteria();
     $searchModel = new Contacts();
     $searchModel->leadSource = 'Facebook';
     $compareAttribute = TestingAuxLib::setPublic($searchModel, 'compareAttribute');
     $compareAttribute($criteria, $searchModel->getField('leadSource'));
     $contacts = Contacts::model()->findAll($criteria);
     $this->assertModelArrayEquality(array($contact2), $contacts);
     $contact1->leadSource = CJSON::encode(array('Google', 'Facebook'));
     $this->assertSaves($contact1);
     $criteria = new CDbCriteria();
     $searchModel = new Contacts();
     $searchModel->leadSource = array('Google');
     $compareAttribute = TestingAuxLib::setPublic($searchModel, 'compareAttribute');
     $compareAttribute($criteria, $searchModel->getField('leadSource'));
     $contacts = Contacts::model()->findAll($criteria);
     $this->assertModelArrayEquality(array($contact1), $contacts);
     $criteria = new CDbCriteria();
     $searchModel = new Contacts();
     $searchModel->leadSource = array('Facebook');
     $compareAttribute = TestingAuxLib::setPublic($searchModel, 'compareAttribute');
     $compareAttribute($criteria, $searchModel->getField('leadSource'));
     $contacts = Contacts::model()->findAll($criteria);
     $this->assertModelArrayEquality(array($contact1, $contact2), $contacts);
 }
예제 #28
0
 public function actionSendReminder()
 {
     $dataProvider = new CActiveDataProvider('Actions', array('criteria' => array('condition' => '(dueDate<"' . mktime(23, 59, 59) . '" AND dueDate>"' . mktime(0, 0, 0) . '" AND complete="No")')));
     $emails = User::getEmails();
     $actionArray = $dataProvider->getData();
     foreach ($actionArray as $action) {
         if ($action->reminder == 'Yes') {
             if ($action->associationId != 0) {
                 $contact = Contacts::model()->findByPk($action->associationId);
                 $name = $contact->firstName . ' ' . $contact->lastName;
             } else {
                 $name = Yii::t('actions', 'No one');
             }
             $email = $emails[$action->assignedTo];
             if (isset($action->type)) {
                 $type = $action->type;
             } else {
                 $type = Yii::t('actions', 'Not specified');
             }
             $subject = Yii::t('actions', 'Action Reminder:');
             $body = Yii::t('actions', "Reminder, the following action is due today: \n Description: {description}\n Type: {type}.\n Associations: {name}.\nLink to the action: ", array('{description}' => $action->actionDescription, '{type}' => $type, '{name}' => $name)) . 'http://' . Yii::app()->request->getServerName() . Yii::app()->request->baseUrl . '/index.php/actions/' . $action->id;
             $headers = 'From: ' . Yii::app()->params['adminEmail'];
             if ($action->associationType != 'none') {
                 $body .= "\n\n" . Yii::t('actions', 'Link to the {type}', array('{type}' => ucfirst($action->associationType))) . ': http://' . Yii::app()->request->getServerName() . Yii::app()->request->baseUrl . "/index.php/" . $action->associationType . "/" . $action->associationId;
             }
             $body .= "\n\n" . Yii::t('actions', 'Powered by ') . '<a href=http://x2engine.com>X2Engine</a>';
             mail($email, $subject, $body, $headers);
         }
     }
 }
예제 #29
0
 public function testMarkDuplicate()
 {
     // Confirm that markDuplicate field sets all relevant fields correctly
     Yii::app()->params->adminProf = Profile::model()->findByPk(1);
     $contact = $this->contacts('contact1');
     $this->assertEquals(0, $contact->dupeCheck);
     $this->assertEquals(1, $contact->visibility);
     $this->assertEquals('Anyone', $contact->assignedTo);
     $contact->markAsDuplicate();
     $this->assertEquals(1, $contact->dupeCheck);
     $this->assertEquals(0, $contact->visibility);
     $this->assertEquals('Anyone', $contact->assignedTo);
     $contact->markAsDuplicate('delete');
     $contact = Contacts::model()->findByPk(1);
     $this->assertEquals(null, $contact);
     // Same for accounts
     $account = $this->accounts('account1');
     $this->assertEquals(0, $account->dupeCheck);
     $this->assertEquals('Anyone', $account->assignedTo);
     $account->markAsDuplicate();
     $this->assertEquals(1, $account->dupeCheck);
     $this->assertEquals('Anyone', $account->assignedTo);
     $account->markAsDuplicate('delete');
     $account = Accounts::model()->findByPk(1);
     $this->assertEquals(null, $account);
 }
예제 #30
0
 /**
  * Updates a particular model.
  * If update is successful, the browser will be redirected to the 'view' page.
  * @param integer $id the ID of the model to be updated
  */
 public function actionUpdate($id)
 {
     $model = $this->loadModel($id);
     $users = User::getNames();
     $fields = Fields::model()->findAllByAttributes(array('modelName' => "Products"));
     foreach ($fields as $field) {
         if ($field->type == 'link') {
             $fieldName = $field->fieldName;
             $type = ucfirst($field->linkType);
             if (is_numeric($model->{$fieldName}) && $model->{$fieldName} != 0) {
                 eval("\$lookupModel={$type}::model()->findByPk(" . $model->{$fieldName} . ");");
                 if (isset($lookupModel)) {
                     $model->{$fieldName} = $lookupModel->name;
                 }
             }
         }
     }
     if (isset($_POST['Product'])) {
         $temp = $model->attributes;
         foreach ($_POST['Product'] as $name => $value) {
             if ($value == $model->getAttributeLabel($name)) {
                 $_POST['Product'][$name] = '';
             }
         }
         foreach ($_POST as $key => $arr) {
             $pieces = explode("_", $key);
             if (isset($pieces[0]) && $pieces[0] == 'autoselect') {
                 $newKey = $pieces[1];
                 if (isset($_POST[$newKey . "_id"]) && $_POST[$newKey . "_id"] != "") {
                     $val = $_POST[$newKey . "_id"];
                 } else {
                     $field = Fields::model()->findByAttributes(array('fieldName' => $newKey));
                     if (isset($field)) {
                         $type = ucfirst($field->linkType);
                         if ($type != "Contacts") {
                             eval("\$lookupModel={$type}::model()->findByAttributes(array('name'=>'{$arr}'));");
                         } else {
                             $names = explode(" ", $arr);
                             $lookupModel = Contacts::model()->findByAttributes(array('firstName' => $names[0], 'lastName' => $names[1]));
                         }
                         if (isset($lookupModel)) {
                             $val = $lookupModel->id;
                         } else {
                             $val = $arr;
                         }
                     }
                 }
                 $model->{$newKey} = $val;
             }
         }
         foreach (array_keys($model->attributes) as $field) {
             if (isset($_POST['Product'][$field])) {
                 $model->{$field} = $_POST['Product'][$field];
                 $fieldData = Fields::model()->findByAttributes(array('modelName' => 'Products', 'fieldName' => $field));
                 if ($fieldData->type == 'assignment' && $fieldData->linkType == 'multiple') {
                     $model->{$field} = Accounts::parseUsers($model->{$field});
                 } elseif ($fieldData->type == 'date') {
                     $model->{$field} = strtotime($model->{$field});
                 }
             }
         }
         // generate history
         $action = new Actions();
         $action->associationType = 'product';
         $action->associationId = $model->id;
         $action->associationName = $model->name;
         $action->assignedTo = Yii::app()->user->getName();
         $action->completedBy = Yii::app()->user->getName();
         $action->dueDate = time();
         $action->completeDate = time();
         $action->visibility = 1;
         $action->complete = 'Yes';
         $action->actionDescription = "Update: <b>{$model->name}</b>\n\t\t\t\tType: <b>{$model->type}</b>\n\t\t\t\tPrice: <b>{$model->price}</b>\n\t\t\t\tCurrency: <b>{$model->currency}</b>\n\t\t\t\tInventory: <b>{$model->inventory}</b>";
         $action->save();
         parent::update($model, $temp, '0');
     }
     $this->render('update', array('model' => $model, 'users' => $users));
 }