/**
  * called when action is browse.
  *
  */
 public function browse()
 {
     $in = CRM_Contact_BAO_GroupContact::getContactGroup($this->_contactId, 'Added');
     // keep track of all 'added' contact groups so we can remove them from the smart group
     // section
     $staticGroups = array();
     if (!empty($in)) {
         foreach ($in as $group) {
             $staticGroups[$group['group_id']] = 1;
         }
     }
     $allGroup = CRM_Contact_BAO_GroupContactCache::contactGroup($this->_contactId);
     $this->assign('groupSmart', NULL);
     $this->assign('groupParent', NULL);
     if (!empty($allGroup)) {
         $smart = $parent = array();
         foreach ($allGroup['group'] as $group) {
             // delete all smart groups which are also in static groups
             if (isset($staticGroups[$group['id']])) {
                 continue;
             }
             if (empty($group['children'])) {
                 $smart[] = $group;
             } else {
                 $parent[] = $group;
             }
         }
         if (!empty($smart)) {
             $this->assign_by_ref('groupSmart', $smart);
         }
         if (!empty($parent)) {
             $this->assign_by_ref('groupParent', $parent);
         }
     }
 }
Example #2
0
 /**
  * called when action is browse.
  *
  * @return void
  */
 public function browse()
 {
     $count = CRM_Contact_BAO_GroupContact::getContactGroup($this->_contactId, NULL, NULL, TRUE, TRUE, $this->_onlyPublicGroups);
     $in =& CRM_Contact_BAO_GroupContact::getContactGroup($this->_contactId, 'Added', NULL, FALSE, TRUE, $this->_onlyPublicGroups);
     $pending =& CRM_Contact_BAO_GroupContact::getContactGroup($this->_contactId, 'Pending', NULL, FALSE, TRUE, $this->_onlyPublicGroups);
     $out =& CRM_Contact_BAO_GroupContact::getContactGroup($this->_contactId, 'Removed', NULL, FALSE, TRUE, $this->_onlyPublicGroups);
     $this->assign('groupCount', $count);
     $this->assign_by_ref('groupIn', $in);
     $this->assign_by_ref('groupPending', $pending);
     $this->assign_by_ref('groupOut', $out);
 }
Example #3
0
 /**
  * Confirm a pending subscription
  *
  * @param int $contact_id       The id of the contact
  * @param int $subscribe_id     The id of the subscription event
  * @param string $hash          The hash
  *
  * @return boolean              True on success
  * @access public
  * @static
  */
 public static function confirm($contact_id, $subscribe_id, $hash)
 {
     $se =& CRM_Mailing_Event_BAO_Subscribe::verify($contact_id, $subscribe_id, $hash);
     if (!$se) {
         return FALSE;
     }
     // before we proceed lets just check if this contact is already 'Added'
     // if so, we should ignore this request and hence avoid sending multiple
     // emails - CRM-11157
     $details = CRM_Contact_BAO_GroupContact::getMembershipDetail($contact_id, $se->group_id);
     if ($details && $details->status == 'Added') {
         // This contact is already subscribed
         // lets return the group title
         return CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $se->group_id, 'title');
     }
     $transaction = new CRM_Core_Transaction();
     $ce = new CRM_Mailing_Event_BAO_Confirm();
     $ce->event_subscribe_id = $se->id;
     $ce->time_stamp = date('YmdHis');
     $ce->save();
     CRM_Contact_BAO_GroupContact::addContactsToGroup(array($contact_id), $se->group_id, 'Email', 'Added', $ce->id);
     $transaction->commit();
     $config = CRM_Core_Config::singleton();
     $domain = CRM_Core_BAO_Domain::getDomain();
     list($domainEmailName, $_) = CRM_Core_BAO_Domain::getNameAndEmail();
     list($display_name, $email) = CRM_Contact_BAO_Contact_Location::getEmailDetails($se->contact_id);
     $group = new CRM_Contact_DAO_Group();
     $group->id = $se->group_id;
     $group->find(TRUE);
     $component = new CRM_Mailing_BAO_Component();
     $component->is_default = 1;
     $component->is_active = 1;
     $component->component_type = 'Welcome';
     $component->find(TRUE);
     $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
     $html = $component->body_html;
     if ($component->body_text) {
         $text = $component->body_text;
     } else {
         $text = CRM_Utils_String::htmlToText($component->body_html);
     }
     $bao = new CRM_Mailing_BAO_Mailing();
     $bao->body_text = $text;
     $bao->body_html = $html;
     $tokens = $bao->getTokens();
     $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']);
     $html = CRM_Utils_Token::replaceWelcomeTokens($html, $group->title, TRUE);
     $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']);
     $text = CRM_Utils_Token::replaceWelcomeTokens($text, $group->title, FALSE);
     $mailParams = array('groupName' => 'Mailing Event ' . $component->component_type, 'subject' => $component->subject, 'from' => "\"{$domainEmailName}\" <do-not-reply@{$emailDomain}>", 'toEmail' => $email, 'toName' => $display_name, 'replyTo' => "do-not-reply@{$emailDomain}", 'returnPath' => "do-not-reply@{$emailDomain}", 'html' => $html, 'text' => $text);
     // send - ignore errors because the desired status change has already been successful
     $unused_result = CRM_Utils_Mail::send($mailParams);
     return $group->title;
 }
Example #4
0
 /**
  * Process the form after the input has been submitted and validated.
  */
 public function postProcess()
 {
     $groupId = $this->controller->exportValue('RemoveFromGroup', 'group_id');
     $group = CRM_Core_PseudoConstant::group();
     list($total, $removed, $notRemoved) = CRM_Contact_BAO_GroupContact::removeContactsFromGroup($this->_contactIds, $groupId);
     $status = array(ts("%count contact removed from '%2'", array('count' => $removed, 'plural' => "%count contacts removed from '%2'", 2 => $group[$groupId])));
     if ($notRemoved) {
         $status[] = ts('1 contact was already not in this group', array('count' => $notRemoved, 'plural' => '%count contacts were already not in this group'));
     }
     $status = '<ul><li>' . implode('</li><li>', $status) . '</li></ul>';
     CRM_Core_Session::setStatus($status, ts("Removed Contact From Group", array('plural' => "Removed Contacts From Group", 'count' => $removed)), 'success', array('expires' => 0));
 }
 function testForceCiviToMailchimpSyncNullEmail()
 {
     $mailchimp_sync_setting = CRM_CiviMailchimp_BAO_SyncSettingsTest::createTestGroupAndSyncSettings('Test Group testForceCiviToMailchimpSyncNullEmail');
     $params = CRM_CiviMailchimp_UtilsTest::sampleContactParams();
     unset($params['email']);
     $contact = CRM_Contact_BAO_Contact::create($params);
     $contact_ids = array($contact->id);
     CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $mailchimp_sync_setting->civicrm_group_id);
     $contacts = CRM_CiviMailchimp_Form_Sync::forceCiviToMailchimpSync($mailchimp_sync_setting);
     $mailchimp_api_subscribe = civimailchimp_static('mailchimp_api_subscribe');
     $this->assertCount(0, $contacts);
     $this->assertNull($mailchimp_api_subscribe);
 }
 protected function contactIsMemberOfAllGroups($contact_id, $group_ids)
 {
     $isValid = 0;
     foreach ($group_ids as $gid) {
         if (CRM_Contact_BAO_GroupContact::isContactInGroup($contact_id, $gid)) {
             $isValid++;
         }
     }
     if (count($group_ids) == $isValid && count($group_ids) > 0) {
         return true;
     }
     return false;
 }
 /**
  * process the form after the input has been submitted and validated
  *
  * @access public
  * @return None
  */
 function postProcess()
 {
     $groupId = $this->controller->exportValue('RemoveFromGroup', 'group_id');
     $group =& CRM_Core_PseudoConstant::group();
     list($total, $removed, $notRemoved) = CRM_Contact_BAO_GroupContact::removeContactsFromGroup($this->_contactIds, $groupId);
     $status = array(ts('Removed Contact(s) from %1', array(1 => $group[$groupId])), ts('Total Selected Contact(s): %1', array(1 => $total)));
     if ($removed) {
         $status[] = ts('Total Contact(s) removed from group: %1', array(1 => $removed));
     }
     if ($notRemoved) {
         $status[] = ts('Total Contact(s) not in group: %1', array(1 => $notRemoved));
     }
     CRM_Core_Session::setStatus($status);
 }
 function testFindByContactId()
 {
     $expected_mailchimp_sync_setting = self::createTestGroupAndSyncSettings('Test group testFindByContactId');
     $params = CRM_CiviMailchimp_UtilsTest::sampleContactParams();
     $contact = CRM_Contact_BAO_Contact::create($params);
     $contact_ids = array($contact->id);
     CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $expected_mailchimp_sync_setting->civicrm_group_id);
     $mailchimp_sync_settings = CRM_CiviMailchimp_BAO_SyncSettings::findByContactId($contact->id);
     $mailchimp_sync_setting = $mailchimp_sync_settings[$expected_mailchimp_sync_setting->civicrm_group_id];
     $this->assertEquals($expected_mailchimp_sync_setting->id, $mailchimp_sync_setting->id);
     $this->assertEquals($expected_mailchimp_sync_setting->civicrm_group_id, $mailchimp_sync_setting->civicrm_group_id);
     $this->assertEquals($expected_mailchimp_sync_setting->mailchimp_list_id, $mailchimp_sync_setting->mailchimp_list_id);
     $this->assertEquals($expected_mailchimp_sync_setting->mailchimp_interest_groups, $mailchimp_sync_setting->mailchimp_interest_groups);
 }
Example #9
0
 /**
  * Confirm a pending subscription
  *
  * @param int $contact_id       The id of the contact
  * @param int $subscribe_id     The id of the subscription event
  * @param string $hash          The hash
  * @return boolean              True on success
  * @access public
  * @static
  */
 function confirm($contact_id, $subscribe_id, $hash)
 {
     $se =& CRM_Mailing_Event_BAO_Subscribe::verify($contact_id, $subscribe_id, $hash);
     if (!$se) {
         return false;
     }
     CRM_Core_DAO::transaction('BEGIN');
     $ce =& new CRM_Mailing_Event_BAO_Confirm();
     $ce->event_subscribe_id = $se->id;
     $ce->time_stamp = date('YmdHis');
     $ce->save();
     CRM_Contact_BAO_GroupContact::updateGroupMembershipStatus($contact_id, $se->group_id, 'Email', $ce->id);
     CRM_Core_DAO::transaction('COMMIT');
     $config =& CRM_Core_Config::singleton();
     $domain =& CRM_Mailing_Event_BAO_Subscribe::getDomain($subscribe_id);
     list($display_name, $email) = CRM_Contact_BAO_Contact::getEmailDetails($se->contact_id);
     $group =& new CRM_Contact_DAO_Group();
     $group->id = $se->group_id;
     $group->find(true);
     require_once 'CRM/Mailing/BAO/Component.php';
     $component =& new CRM_Mailing_BAO_Component();
     $component->domain_id = $domain->id;
     $component->is_default = 1;
     $component->is_active = 1;
     $component->component_type = 'Welcome';
     $component->find(true);
     $headers = array('Subject' => $component->subject, 'From' => ts('"%1 Administrator" <do-not-reply@%2>', array(1 => $domain->name, 2 => $domain->email_domain)), 'To' => $email, 'Reply-To' => "do-not-reply@{$domain->email_domain}", 'Return-Path' => "do-not-reply@{$domain->email_domain}");
     $html = $component->body_html;
     require_once 'CRM/Utils/Token.php';
     $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, true);
     $html = CRM_Utils_Token::replaceWelcomeTokens($html, $group->name, true);
     $text = $component->body_text;
     $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, false);
     $text = CRM_Utils_Token::replaceWelcomeTokens($text, $group->name, false);
     $message =& new Mail_Mime("\n");
     $message->setHTMLBody($html);
     $message->setTxtBody($text);
     $b = $message->get();
     $h = $message->headers($headers);
     $mailer =& $config->getMailer();
     PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('CRM_Mailing_BAO_Mailing', 'catchSMTP'));
     $mailer->send($email, $h, $b);
     CRM_Core_Error::setCallback();
     return true;
 }
 /**
  * Method to get groups
  *
  * @return array
  * @access protected
  */
 protected function getGroups()
 {
     return array('' => ts('-- please select --')) + CRM_Contact_BAO_GroupContact::getGroupList();
 }
Example #11
0
 /**
  * @param int $groupID
  */
 public function add2group($groupID)
 {
     if (is_numeric($groupID)) {
         $sql = "\n{$this->_select} {$this->_from}  {$this->_where} {$this->_groupBy}\nORDER BY civicrm_contribution_total_amount_sum DESC\n) as abc {$this->_groupLimit}";
         $dao = CRM_Core_DAO::executeQuery($sql);
         $contact_ids = array();
         // Add resulting contacts to group
         while ($dao->fetch()) {
             $contact_ids[$dao->civicrm_contact_id] = $dao->civicrm_contact_id;
         }
         CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID);
         CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
     }
 }
/**
 * Update group contact status.
 *
 * @deprecated - this should be part of create but need to know we aren't missing something
 *
 * @param array $params
 *
 * @return bool
 * @throws \API_Exception
 */
function civicrm_api3_group_contact_update_status($params)
{
    civicrm_api3_verify_mandatory($params, NULL, array('contact_id', 'group_id'));
    CRM_Contact_BAO_GroupContact::addContactsToGroup(array($params['contact_id']), $params['group_id'], CRM_Utils_Array::value('method', $params, 'API'), 'Added', CRM_Utils_Array::value('tracking', $params));
    return TRUE;
}
Example #13
0
 /**  
  * Function to build the array for display the profile fields
  *  
  * @param array $params key value. 
  * @param int $gid profile Id
  * @param array $groupTitle Profile Group Title.
  * @param array $values formatted array of key value
  *
  * @return None  
  * @access public  
  */
 function displayProfile(&$params, $gid, &$groupTitle, &$values)
 {
     if ($gid) {
         require_once 'CRM/Core/BAO/UFGroup.php';
         require_once 'CRM/Profile/Form.php';
         require_once 'CRM/Event/PseudoConstant.php';
         $session = CRM_Core_Session::singleton();
         $contactID = $session->get('userID');
         if ($contactID) {
             if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $contactID)) {
                 $fields = CRM_Core_BAO_UFGroup::getFields($gid, false, CRM_Core_Action::VIEW);
             }
         } else {
             $fields = CRM_Core_BAO_UFGroup::getFields($gid, false, CRM_Core_Action::ADD);
         }
         if (is_array($fields)) {
             // unset any email-* fields since we already collect it, CRM-2888
             foreach (array_keys($fields) as $fieldName) {
                 if (substr($fieldName, 0, 6) == 'email-') {
                     unset($fields[$fieldName]);
                 }
             }
         }
         foreach ($fields as $v) {
             if (CRM_Utils_Array::value('groupTitle', $v)) {
                 $groupTitle['groupTitle'] = $v["groupTitle"];
                 break;
             }
         }
         $config = CRM_Core_Config::singleton();
         require_once 'CRM/Core/PseudoConstant.php';
         $locationTypes = $imProviders = array();
         $locationTypes = CRM_Core_PseudoConstant::locationType();
         $imProviders = CRM_Core_PseudoConstant::IMProvider();
         //start of code to set the default values
         foreach ($fields as $name => $field) {
             $index = $field['title'];
             $customFieldName = null;
             if ($name === 'organization_name') {
                 $values[$index] = $params[$name];
             }
             if ('state_province' == substr($name, 0, 14)) {
                 if ($params[$name]) {
                     $values[$index] = CRM_Core_PseudoConstant::stateProvince($params[$name]);
                 } else {
                     $values[$index] = '';
                 }
             } else {
                 if ('country' == substr($name, 0, 7)) {
                     if ($params[$name]) {
                         $values[$index] = CRM_Core_PseudoConstant::country($params[$name]);
                     } else {
                         $values[$index] = '';
                     }
                 } else {
                     if ('county' == substr($name, 0, 6)) {
                         if ($params[$name]) {
                             $values[$index] = CRM_Core_PseudoConstant::county($params[$name]);
                         } else {
                             $values[$index] = '';
                         }
                     } else {
                         if ('gender' == substr($name, 0, 6)) {
                             $gender = CRM_Core_PseudoConstant::gender();
                             $values[$index] = $gender[$params[$name]];
                         } else {
                             if ('individual_prefix' == substr($name, 0, 17)) {
                                 $prefix = CRM_Core_PseudoConstant::individualPrefix();
                                 $values[$index] = $prefix[$params[$name]];
                             } else {
                                 if ('individual_suffix' == substr($name, 0, 17)) {
                                     $suffix = CRM_Core_PseudoConstant::individualSuffix();
                                     $values[$index] = $suffix[$params[$name]];
                                 } else {
                                     if (in_array($name, array('addressee', 'email_greeting', 'postal_greeting'))) {
                                         $filterCondition = array('greeting_type' => $name);
                                         $greeting =& CRM_Core_PseudoConstant::greeting($filterCondition);
                                         $values[$index] = $greeting[$params[$name]];
                                     } else {
                                         if ($name === 'preferred_communication_method') {
                                             $communicationFields = CRM_Core_PseudoConstant::pcm();
                                             $pref = array();
                                             $compref = array();
                                             $pref = $params[$name];
                                             if (is_array($pref)) {
                                                 foreach ($pref as $k => $v) {
                                                     if ($v) {
                                                         $compref[] = $communicationFields[$k];
                                                     }
                                                 }
                                             }
                                             $values[$index] = implode(",", $compref);
                                         } else {
                                             if ($name == 'group') {
                                                 require_once 'CRM/Contact/BAO/GroupContact.php';
                                                 $groups = CRM_Contact_BAO_GroupContact::getGroupList();
                                                 $title = array();
                                                 foreach ($params[$name] as $gId => $dontCare) {
                                                     if ($dontCare) {
                                                         $title[] = $groups[$gId];
                                                     }
                                                 }
                                                 $values[$index] = implode(', ', $title);
                                             } else {
                                                 if ($name == 'tag') {
                                                     require_once 'CRM/Core/BAO/EntityTag.php';
                                                     $entityTags = $params[$name];
                                                     $allTags =& CRM_Core_PseudoConstant::tag();
                                                     $title = array();
                                                     if (is_array($entityTags)) {
                                                         foreach ($entityTags as $tagId => $dontCare) {
                                                             $title[] = $allTags[$tagId];
                                                         }
                                                     }
                                                     $values[$index] = implode(', ', $title);
                                                 } else {
                                                     if ('participant_role_id' == $name) {
                                                         $roles = CRM_Event_PseudoConstant::participantRole();
                                                         $values[$index] = $roles[$params[$name]];
                                                     } else {
                                                         if ('participant_status_id' == $name) {
                                                             $status = CRM_Event_PseudoConstant::participantStatus();
                                                             $values[$index] = $status[$params[$name]];
                                                         } else {
                                                             if (strpos($name, '-') !== false) {
                                                                 list($fieldName, $id) = CRM_Utils_System::explode('-', $name, 2);
                                                                 $detailName = str_replace(' ', '_', $name);
                                                                 if (in_array($fieldName, array('state_province', 'country', 'county'))) {
                                                                     $values[$index] = $params[$detailName];
                                                                     $idx = $detailName . '_id';
                                                                     $values[$index] = $params[$idx];
                                                                 } else {
                                                                     if ($fieldName == 'im') {
                                                                         $providerName = null;
                                                                         if ($providerId = $detailName . '-provider_id') {
                                                                             $providerName = CRM_Utils_Array::value($params[$providerId], $imProviders);
                                                                         }
                                                                         if ($providerName) {
                                                                             $values[$index] = $params[$detailName] . " (" . $providerName . ")";
                                                                         } else {
                                                                             $values[$index] = $params[$detailName];
                                                                         }
                                                                     } else {
                                                                         $values[$index] = $params[$detailName];
                                                                     }
                                                                 }
                                                             } else {
                                                                 if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
                                                                     if ($params[$name]) {
                                                                         $values[$index] = '[ x ]';
                                                                     }
                                                                 } else {
                                                                     require_once 'CRM/Core/BAO/CustomField.php';
                                                                     if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                                                                         $query = "\nSELECT html_type, data_type\nFROM   civicrm_custom_field\nWHERE  id = {$cfID}\n";
                                                                         $dao = CRM_Core_DAO::executeQuery($query, CRM_Core_DAO::$_nullArray);
                                                                         $dao->fetch();
                                                                         $htmlType = $dao->html_type;
                                                                         $dataType = $dao->data_type;
                                                                         if ($htmlType == 'File') {
                                                                             //$fileURL = CRM_Core_BAO_CustomField::getFileURL( $contactID, $cfID );
                                                                             //$params[$index] = $values[$index] = $fileURL['file_url'];
                                                                             $values[$index] = $params[$index];
                                                                         } else {
                                                                             if ($dao->data_type == 'Int' || $dao->data_type == 'Boolean') {
                                                                                 $customVal = (int) $params[$name];
                                                                             } else {
                                                                                 if ($dao->data_type == 'Float') {
                                                                                     $customVal = (double) $params[$name];
                                                                                 } else {
                                                                                     if ($dao->data_type == 'Date') {
                                                                                         $date = CRM_Utils_Date::format($params[$name], null, 'invalidDate');
                                                                                         if ($date != 'invalidDate') {
                                                                                             $customVal = $date;
                                                                                         }
                                                                                     } else {
                                                                                         $customVal = $params[$name];
                                                                                     }
                                                                                 }
                                                                             }
                                                                             //take the custom field options
                                                                             $returnProperties = array($name => 1);
                                                                             require_once 'CRM/Contact/BAO/Query.php';
                                                                             $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
                                                                             $options =& $query->_options;
                                                                             $displayValue = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options);
                                                                             //Hack since we dont have function to check empty.
                                                                             //FIXME in 2.3 using crmIsEmptyArray()
                                                                             $customValue = true;
                                                                             if (is_array($customVal) && is_array($displayValue)) {
                                                                                 $customValue = array_diff($customVal, $displayValue);
                                                                             }
                                                                             //use difference of arrays
                                                                             if (empty($customValue) || !$customValue) {
                                                                                 $values[$index] = '';
                                                                             } else {
                                                                                 $values[$index] = $displayValue;
                                                                             }
                                                                             if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $cfID, 'is_search_range')) {
                                                                                 $customFieldName = "{$name}_from";
                                                                             }
                                                                         }
                                                                     } else {
                                                                         if ($name == 'home_URL' && !empty($params[$name])) {
                                                                             $url = CRM_Utils_System::fixURL($params[$name]);
                                                                             $values[$index] = "<a href=\"{$url}\">{$params[$name]}</a>";
                                                                         } else {
                                                                             if (in_array($name, array('birth_date', 'deceased_date', 'participant_register_date'))) {
                                                                                 require_once 'CRM/Utils/Date.php';
                                                                                 $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::format($params[$name]));
                                                                             } else {
                                                                                 $values[$index] = $params[$name];
                                                                             }
                                                                         }
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
 }
Example #14
0
 /**
  * Run the page.
  *
  * This method is called after the page is created. It checks for the
  * type of action and executes that action.
  *
  * @return void
  */
 public function run()
 {
     $template = CRM_Core_Smarty::singleton();
     if ($this->_id && $this->_gid) {
         // first check that id is part of the limit group id, CRM-4822
         $limitListingsGroupsID = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'limit_listings_group_id');
         $config = CRM_Core_Config::singleton();
         if ($limitListingsGroupsID) {
             if (!CRM_Contact_BAO_GroupContact::isContactInGroup($this->_id, $limitListingsGroupsID)) {
                 CRM_Utils_System::setTitle(ts('Profile View - Permission Denied'));
                 return CRM_Core_Session::setStatus(ts('You do not have permission to view this contact record. Contact the site administrator if you need assistance.'), ts('Permission Denied'), 'error');
             }
         }
         $session = CRM_Core_Session::singleton();
         $userID = $session->get('userID');
         $this->_isPermissionedChecksum = $allowPermission = FALSE;
         $permissionType = CRM_Core_Permission::VIEW;
         if (CRM_Core_Permission::check('administer users') || CRM_Core_Permission::check('view all contacts') || CRM_Contact_BAO_Contact_Permission::allow($this->_id)) {
             $allowPermission = TRUE;
         }
         if ($this->_id != $userID) {
             // do not allow edit for anon users in joomla frontend, CRM-4668, unless u have checksum CRM-5228
             if ($config->userFrameworkFrontend) {
                 $this->_isPermissionedChecksum = CRM_Contact_BAO_Contact_Permission::validateOnlyChecksum($this->_id, $this, FALSE);
                 if (!$this->_isPermissionedChecksum) {
                     $this->_isPermissionedChecksum = $allowPermission;
                 }
             } else {
                 $this->_isPermissionedChecksum = CRM_Contact_BAO_Contact_Permission::validateChecksumContact($this->_id, $this, FALSE);
             }
         }
         // CRM-10853
         // Users with create or edit permission should be allowed to view their own profile
         if ($this->_id == $userID || $this->_isPermissionedChecksum) {
             if (!CRM_Core_Permission::check('profile view')) {
                 if (CRM_Core_Permission::check('profile create') || CRM_Core_Permission::check('profile edit')) {
                     $this->_skipPermission = TRUE;
                 }
             }
         }
         // make sure we dont expose all fields based on permission
         $admin = FALSE;
         if (!$config->userFrameworkFrontend && $allowPermission || $this->_id == $userID || $this->_isPermissionedChecksum) {
             $admin = TRUE;
         }
         $values = array();
         $fields = CRM_Core_BAO_UFGroup::getFields($this->_profileIds, FALSE, CRM_Core_Action::VIEW, NULL, NULL, FALSE, $this->_restrict, $this->_skipPermission, NULL, $permissionType);
         if ($this->_multiRecord & CRM_Core_Action::VIEW && $this->_recordId && !$this->_allFields) {
             CRM_Core_BAO_UFGroup::shiftMultiRecordFields($fields, $multiRecordFields);
             $fields = $multiRecordFields;
         }
         if ($this->_isContactActivityProfile && $this->_gid) {
             $errors = CRM_Profile_Form::validateContactActivityProfile($this->_activityId, $this->_id, $this->_gid);
             if (!empty($errors)) {
                 CRM_Core_Error::fatal(array_pop($errors));
             }
         }
         //reformat fields array
         foreach ($fields as $name => $field) {
             // also eliminate all formatting fields
             if (CRM_Utils_Array::value('field_type', $field) == 'Formatting') {
                 unset($fields[$name]);
             }
             // make sure that there is enough permission to expose this field
             if (!$admin && $field['visibility'] == 'User and User Admin Only') {
                 unset($fields[$name]);
             }
         }
         if ($this->_isContactActivityProfile) {
             $contactFields = $activityFields = array();
             foreach ($fields as $fieldName => $field) {
                 if (CRM_Utils_Array::value('field_type', $field) == 'Activity') {
                     $activityFields[$fieldName] = $field;
                 } else {
                     $contactFields[$fieldName] = $field;
                 }
             }
             CRM_Core_BAO_UFGroup::getValues($this->_id, $contactFields, $values);
             if ($this->_activityId) {
                 CRM_Core_BAO_UFGroup::getValues(NULL, $activityFields, $values, TRUE, array(array('activity_id', '=', $this->_activityId, 0, 0)));
             }
         } else {
             $customWhereClause = NULL;
             if ($this->_multiRecord & CRM_Core_Action::VIEW && $this->_recordId) {
                 if ($this->_allFields) {
                     $copyFields = $fields;
                     CRM_Core_BAO_UFGroup::shiftMultiRecordFields($copyFields, $multiRecordFields);
                     $fieldKey = key($multiRecordFields);
                 } else {
                     $fieldKey = key($fields);
                 }
                 if ($fieldID = CRM_Core_BAO_CustomField::getKeyID($fieldKey)) {
                     $tableColumnGroup = CRM_Core_BAO_CustomField::getTableColumnGroup($fieldID);
                     $columnName = "{$tableColumnGroup[0]}.id";
                     $customWhereClause = $columnName . ' = ' . $this->_recordId;
                 }
             }
             CRM_Core_BAO_UFGroup::getValues($this->_id, $fields, $values, TRUE, NULL, FALSE, $customWhereClause);
         }
         // $profileFields array can be used for customized display of field labels and values in Profile/View.tpl
         $profileFields = array();
         $labels = array();
         foreach ($fields as $name => $field) {
             //CRM-14338
             // Create a unique, non-empty index for each field.
             $index = $field['title'];
             if ($index === '') {
                 $index = ' ';
             }
             while (array_key_exists($index, $labels)) {
                 $index .= ' ';
             }
             $labels[$index] = preg_replace('/\\s+|\\W+/', '_', $name);
         }
         foreach ($values as $title => $value) {
             $profileFields[$labels[$title]] = array('label' => $title, 'value' => $value);
         }
         $template->assign_by_ref('row', $values);
         $template->assign_by_ref('profileFields', $profileFields);
     }
     $name = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'name');
     $this->assign('ufGroupName', $name);
     CRM_Utils_Hook::viewProfile($name);
     if (strtolower($name) == 'summary_overlay') {
         $template->assign('overlayProfile', TRUE);
     }
     if ($this->_multiRecord & CRM_Core_Action::VIEW && $this->_recordId && !$this->_allFields) {
         $fieldDetail = reset($fields);
         $fieldId = CRM_Core_BAO_CustomField::getKeyID($fieldDetail['name']);
         $customGroupDetails = CRM_Core_BAO_CustomGroup::getGroupTitles(array($fieldId));
         $multiRecTitle = $customGroupDetails[$fieldId]['groupTitle'];
     } else {
         $title = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $this->_gid, 'title');
     }
     //CRM-4131.
     $displayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $this->_id, 'display_name');
     if ($displayName) {
         $session = CRM_Core_Session::singleton();
         $config = CRM_Core_Config::singleton();
         if ($session->get('userID') && CRM_Core_Permission::check('access CiviCRM') && CRM_Contact_BAO_Contact_Permission::allow($session->get('userID'), CRM_Core_Permission::VIEW) && !$config->userFrameworkFrontend) {
             $contactViewUrl = CRM_Utils_System::url('civicrm/contact/view', "action=view&reset=1&cid={$this->_id}", TRUE);
             $this->assign('displayName', $displayName);
             $displayName = "<a href=\"{$contactViewUrl}\">{$displayName}</a>";
         }
         $title .= ' - ' . $displayName;
     }
     $title = isset($multiRecTitle) ? ts('View %1 Record', array(1 => $multiRecTitle)) : $title;
     CRM_Utils_System::setTitle($title);
     // invoke the pagRun hook, CRM-3906
     CRM_Utils_Hook::pageRun($this);
     return trim($template->fetch($this->getHookedTemplateFileName()));
 }
Example #15
0
 /**
  * Process the mapped fields and map it into the uploaded file
  * preview the file and extract some summary statistics
  *
  * @return void
  * @access public
  */
 public function postProcessOld()
 {
     $doGeocodeAddress = $this->controller->exportValue('DataSource', 'doGeocodeAddress');
     $invalidRowCount = $this->get('invalidRowCount');
     $conflictRowCount = $this->get('conflictRowCount');
     $onDuplicate = $this->get('onDuplicate');
     $newGroupName = $this->controller->exportValue($this->_name, 'newGroupName');
     $newGroupDesc = $this->controller->exportValue($this->_name, 'newGroupDesc');
     $groups = $this->controller->exportValue($this->_name, 'groups');
     $allGroups = $this->get('groups');
     $newTagName = $this->controller->exportValue($this->_name, 'newTagName');
     $newTagDesc = $this->controller->exportValue($this->_name, 'newTagDesc');
     $tag = $this->controller->exportValue($this->_name, 'tag');
     $allTags = $this->get('tag');
     $mapper = $this->controller->exportValue('MapField', 'mapper');
     $mapperKeys = array();
     $mapperLocTypes = array();
     $mapperPhoneTypes = array();
     $mapperRelated = array();
     $mapperRelatedContactType = array();
     $mapperRelatedContactDetails = array();
     $mapperRelatedContactLocType = array();
     $mapperRelatedContactPhoneType = array();
     foreach ($mapper as $key => $value) {
         $mapperKeys[$key] = $mapper[$key][0];
         if (is_numeric($mapper[$key][1])) {
             $mapperLocTypes[$key] = $mapper[$key][1];
         } else {
             $mapperLocTypes[$key] = NULL;
         }
         if (CRM_Utils_Array::value($key, $mapperKeys) == 'phone') {
             $mapperPhoneTypes[$key] = $mapper[$key][2];
         } else {
             $mapperPhoneTypes[$key] = NULL;
         }
         list($id, $first, $second) = explode('_', $mapper[$key][0]);
         if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
             $relationType = new CRM_Contact_DAO_RelationshipType();
             $relationType->id = $id;
             $relationType->find(TRUE);
             $fieldName = "contact_type_{$second}";
             $mapperRelatedContactType[$key] = $relationType->{$fieldName};
             $mapperRelated[$key] = $mapper[$key][0];
             $mapperRelatedContactDetails[$key] = $mapper[$key][1];
             $mapperRelatedContactLocType[$key] = $mapper[$key][2];
             $mapperRelatedContactPhoneType[$key] = $mapper[$key][3];
         } else {
             $mapperRelated[$key] = NULL;
             $mapperRelatedContactType[$key] = NULL;
             $mapperRelatedContactDetails[$key] = NULL;
             $mapperRelatedContactLocType[$key] = NULL;
             $mapperRelatedContactPhoneType[$key] = NULL;
         }
     }
     $parser = new CRM_Contact_Import_Parser_Contact($mapperKeys, $mapperLocTypes, $mapperPhoneTypes, $mapperRelated, $mapperRelatedContactType, $mapperRelatedContactDetails, $mapperRelatedContactLocType, $mapperRelatedContactPhoneType);
     $mapFields = $this->get('fields');
     $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
     $phoneTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id');
     foreach ($mapper as $key => $value) {
         $header = array();
         list($id, $first, $second) = explode('_', $mapper[$key][0]);
         if ($first == 'a' && $second == 'b' || $first == 'b' && $second == 'a') {
             $relationType = new CRM_Contact_DAO_RelationshipType();
             $relationType->id = $id;
             $relationType->find(TRUE);
             $header[] = $relationType->name_a_b;
             $header[] = ucwords(str_replace("_", " ", $mapper[$key][1]));
             if (isset($mapper[$key][2])) {
                 $header[] = $locationTypes[$mapper[$key][2]];
             }
             if (isset($mapper[$key][3])) {
                 $header[] = $phoneTypes[$mapper[$key][3]];
             }
         } else {
             if (isset($mapFields[$mapper[$key][0]])) {
                 $header[] = $mapFields[$mapper[$key][0]];
                 if (isset($mapper[$key][1])) {
                     $header[] = $locationTypes[$mapper[$key][1]];
                 }
                 if (isset($mapper[$key][2])) {
                     $header[] = $phoneTypes[$mapper[$key][2]];
                 }
             }
         }
         $mapperFields[] = implode(' - ', $header);
     }
     $tableName = $this->get('importTableName');
     //print "Running parser on table: $tableName<br/>";
     $parser->run($tableName, $mapperFields, CRM_Import_Parser::MODE_IMPORT, $this->get('contactType'), $this->get('primaryKeyName'), $this->get('statusFieldName'), $onDuplicate, $this->get('statusID'), $this->get('totalRowCount'), $doGeocodeAddress, CRM_Contact_Import_Parser::DEFAULT_TIMEOUT, $this->get('contactSubType'), $this->get('dedupe'));
     // add the new contacts to selected groups
     $contactIds =& $parser->getImportedContacts();
     // add the new related contacts to selected groups
     $relatedContactIds =& $parser->getRelatedImportedContacts();
     $this->set('relatedCount', count($relatedContactIds));
     $newGroupId = NULL;
     //changed below if-statement "if ($newGroup) {" to "if ($newGroupName) {"
     if ($newGroupName) {
         /* Create a new group */
         $gParams = array('name' => $newGroupName, 'title' => $newGroupName, 'description' => $newGroupDesc, 'is_active' => TRUE);
         $group = CRM_Contact_BAO_Group::create($gParams);
         $groups[] = $newGroupId = $group->id;
     }
     if (is_array($groups)) {
         $groupAdditions = array();
         foreach ($groups as $groupId) {
             $addCount = CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $groupId);
             if (!empty($relatedContactIds)) {
                 $addRelCount = CRM_Contact_BAO_GroupContact::addContactsToGroup($relatedContactIds, $groupId);
             }
             $totalCount = $addCount[1] + $addRelCount[1];
             if ($groupId == $newGroupId) {
                 $name = $newGroupName;
                 $new = TRUE;
             } else {
                 $name = $allGroups[$groupId];
                 $new = FALSE;
             }
             $groupAdditions[] = array('url' => CRM_Utils_System::url('civicrm/group/search', 'reset=1&force=1&context=smog&gid=' . $groupId), 'name' => $name, 'added' => $totalCount, 'notAdded' => $addCount[2] + $addRelCount[2], 'new' => $new);
         }
         $this->set('groupAdditions', $groupAdditions);
     }
     $newTagId = NULL;
     if ($newTagName) {
         /* Create a new Tag */
         $tagParams = array('name' => $newTagName, 'title' => $newTagName, 'description' => $newTagDesc, 'is_active' => TRUE);
         $id = array();
         $addedTag = CRM_Core_BAO_Tag::add($tagParams, $id);
         $tag[$addedTag->id] = 1;
     }
     //add Tag to Import
     if (is_array($tag)) {
         $tagAdditions = array();
         foreach ($tag as $tagId => $val) {
             $addTagCount = CRM_Core_BAO_EntityTag::addContactsToTag($contactIds, $tagId);
             if (!empty($relatedContactIds)) {
                 $addRelTagCount = CRM_Core_BAO_EntityTag::addContactsToTag($relatedContactIds, $tagId);
             }
             $totalTagCount = $addTagCount[1] + $addRelTagCount[1];
             if ($tagId == $addedTag->id) {
                 $tagName = $newTagName;
                 $new = TRUE;
             } else {
                 $tagName = $allTags[$tagId];
                 $new = FALSE;
             }
             $tagAdditions[] = array('url' => CRM_Utils_System::url('civicrm/contact/search', 'reset=1&force=1&context=smog&id=' . $tagId), 'name' => $tagName, 'added' => $totalTagCount, 'notAdded' => $addTagCount[2] + $addRelTagCount[2], 'new' => $new);
         }
         $this->set('tagAdditions', $tagAdditions);
     }
     // add all the necessary variables to the form
     $parser->set($this, CRM_Import_Parser::MODE_IMPORT);
     // check if there is any error occured
     $errorStack = CRM_Core_Error::singleton();
     $errors = $errorStack->getErrors();
     $errorMessage = array();
     if (is_array($errors)) {
         foreach ($errors as $key => $value) {
             $errorMessage[] = $value['message'];
         }
         // there is no fileName since this is a sql import
         // so fudge it
         $config = CRM_Core_Config::singleton();
         $errorFile = $config->uploadDir . "sqlImport.error.log";
         if ($fd = fopen($errorFile, 'w')) {
             fwrite($fd, implode('\\n', $errorMessage));
         }
         fclose($fd);
         $this->set('errorFile', $errorFile);
         $urlParams = 'type=' . CRM_Import_Parser::ERROR . '&parser=CRM_Contact_Import_Parser';
         $this->set('downloadErrorRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlparams));
         $urlParams = 'type=' . CRM_Import_Parser::CONFLICT . '&parser=CRM_Contact_Import_Parser';
         $this->set('downloadConflictRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
         $urlParams = 'type=' . CRM_Import_Parser::NO_MATCH . '&parser=CRM_Contact_Import_Parser';
         $this->set('downloadMismatchRecordsUrl', CRM_Utils_System::url('civicrm/export', $urlParams));
     }
 }
Example #16
0
 /**
  * Given a contact id and a field set, return the values from the db
  * for this contact
  *
  * @param int $cid
  * @param array $fields
  *   The profile fields of interest.
  * @param array $values
  *   The values for the above fields.
  * @param bool $searchable
  *   Searchable or not.
  * @param array $componentWhere
  *   Component condition.
  * @param bool $absolute
  *   Return urls in absolute form (useful when sending an email).
  * @param null $additionalWhereClause
  */
 public static function getValues($cid, &$fields, &$values, $searchable = TRUE, $componentWhere = NULL, $absolute = FALSE, $additionalWhereClause = NULL)
 {
     if (empty($cid) && empty($componentWhere)) {
         return NULL;
     }
     // get the contact details (hier)
     $returnProperties = CRM_Contact_BAO_Contact::makeHierReturnProperties($fields);
     $params = $cid ? array(array('contact_id', '=', $cid, 0, 0)) : array();
     // add conditions specified by components. eg partcipant_id etc
     if (!empty($componentWhere)) {
         $params = array_merge($params, $componentWhere);
     }
     $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
     $options =& $query->_options;
     $details = $query->searchQuery(0, 0, NULL, FALSE, FALSE, FALSE, FALSE, FALSE, $additionalWhereClause);
     if (!$details->fetch()) {
         return;
     }
     $query->convertToPseudoNames($details);
     $config = CRM_Core_Config::singleton();
     $locationTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id');
     $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
     $websiteTypes = CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id');
     $multipleFields = array('url');
     //start of code to set the default values
     foreach ($fields as $name => $field) {
         // fix for CRM-3962
         if ($name == 'id') {
             $name = 'contact_id';
         }
         // skip fields that should not be displayed separately
         if (!empty($field['skipDisplay'])) {
             continue;
         }
         // Create a unique, non-empty index for each field.
         $index = $field['title'];
         if ($index === '') {
             $index = ' ';
         }
         while (array_key_exists($index, $values)) {
             $index .= ' ';
         }
         $params[$index] = $values[$index] = '';
         $customFieldName = NULL;
         // hack for CRM-665
         if (isset($details->{$name}) || $name == 'group' || $name == 'tag') {
             // to handle gender / suffix / prefix
             if (in_array(substr($name, 0, -3), array('gender', 'prefix', 'suffix'))) {
                 $params[$index] = $details->{$name};
                 $values[$index] = $details->{$name};
             } elseif (in_array($name, CRM_Contact_BAO_Contact::$_greetingTypes)) {
                 $dname = $name . '_display';
                 $values[$index] = $details->{$dname};
                 $name = $name . '_id';
                 $params[$index] = $details->{$name};
             } elseif (in_array($name, array('state_province', 'country', 'county'))) {
                 $values[$index] = $details->{$name};
                 $idx = $name . '_id';
                 $params[$index] = $details->{$idx};
             } elseif ($name === 'preferred_communication_method') {
                 $communicationFields = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
                 $compref = array();
                 $pref = explode(CRM_Core_DAO::VALUE_SEPARATOR, $details->{$name});
                 foreach ($pref as $k) {
                     if ($k) {
                         $compref[] = $communicationFields[$k];
                     }
                 }
                 $params[$index] = $details->{$name};
                 $values[$index] = implode(',', $compref);
             } elseif ($name === 'preferred_language') {
                 $params[$index] = $details->{$name};
                 $values[$index] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', 'preferred_language', $details->{$name});
             } elseif ($name == 'group') {
                 $groups = CRM_Contact_BAO_GroupContact::getContactGroup($cid, 'Added', NULL, FALSE, TRUE);
                 $title = $ids = array();
                 foreach ($groups as $g) {
                     // CRM-8362: User and User Admin visibility groups should be included in display if user has
                     // VIEW permission on that group
                     $groupPerm = CRM_Contact_BAO_Group::checkPermission($g['group_id'], $g['title']);
                     if ($g['visibility'] != 'User and User Admin Only' || CRM_Utils_Array::key(CRM_Core_Permission::VIEW, $groupPerm)) {
                         $title[] = $g['title'];
                         if ($g['visibility'] == 'Public Pages') {
                             $ids[] = $g['group_id'];
                         }
                     }
                 }
                 $values[$index] = implode(', ', $title);
                 $params[$index] = implode(',', $ids);
             } elseif ($name == 'tag') {
                 $entityTags = CRM_Core_BAO_EntityTag::getTag($cid);
                 $allTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
                 $title = array();
                 foreach ($entityTags as $tagId) {
                     $title[] = $allTags[$tagId];
                 }
                 $values[$index] = implode(', ', $title);
                 $params[$index] = implode(',', $entityTags);
             } elseif ($name == 'activity_status_id') {
                 $activityStatus = CRM_Core_PseudoConstant::activityStatus();
                 $values[$index] = $activityStatus[$details->{$name}];
                 $params[$index] = $details->{$name};
             } elseif ($name == 'activity_date_time') {
                 $values[$index] = CRM_Utils_Date::customFormat($details->{$name});
                 $params[$index] = $details->{$name};
             } elseif ($name == 'contact_sub_type') {
                 $contactSubTypeNames = explode(CRM_Core_DAO::VALUE_SEPARATOR, $details->{$name});
                 if (!empty($contactSubTypeNames)) {
                     $contactSubTypeLabels = array();
                     // get all contact subtypes
                     $allContactSubTypes = CRM_Contact_BAO_ContactType::subTypeInfo();
                     // build contact subtype labels array
                     foreach ($contactSubTypeNames as $cstName) {
                         if ($cstName) {
                             $contactSubTypeLabels[] = $allContactSubTypes[$cstName]['label'];
                         }
                     }
                     $values[$index] = implode(',', $contactSubTypeLabels);
                 }
                 $params[$index] = $details->{$name};
             } else {
                 if (substr($name, 0, 7) === 'do_not_' || substr($name, 0, 3) === 'is_') {
                     if ($details->{$name}) {
                         $values[$index] = '[ x ]';
                     }
                 } else {
                     if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                         $htmlType = $field['html_type'];
                         // field_type is only set when we are retrieving profile values
                         // when sending email, we call the same function to get custom field
                         // values etc, i.e. emulating a profile
                         $fieldType = CRM_Utils_Array::value('field_type', $field);
                         if ($htmlType == 'File') {
                             $entityId = $cid;
                             if (!$cid && $fieldType == 'Activity' && !empty($componentWhere[0][2])) {
                                 $entityId = $componentWhere[0][2];
                             }
                             $fileURL = CRM_Core_BAO_CustomField::getFileURL($entityId, $cfID, NULL, $absolute, $additionalWhereClause);
                             $params[$index] = $values[$index] = $fileURL['file_url'];
                         } else {
                             $customVal = NULL;
                             if (isset($dao) && property_exists($dao, 'data_type') && ($dao->data_type == 'Int' || $dao->data_type == 'Boolean')) {
                                 $customVal = (int) $details->{$name};
                             } elseif (isset($dao) && property_exists($dao, 'data_type') && $dao->data_type == 'Float') {
                                 $customVal = (double) $details->{$name};
                             } elseif (!CRM_Utils_System::isNull(explode(CRM_Core_DAO::VALUE_SEPARATOR, $details->{$name}))) {
                                 $customVal = $details->{$name};
                             }
                             //CRM-4582
                             if (CRM_Utils_System::isNull($customVal)) {
                                 continue;
                             }
                             $params[$index] = $customVal;
                             $values[$index] = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options);
                             if ($field['data_type'] == 'ContactReference') {
                                 $params[$index] = $values[$index];
                             }
                             if (CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', $cfID, 'is_search_range')) {
                                 $customFieldName = "{$name}_from";
                             }
                         }
                     } elseif ($name == 'image_URL') {
                         list($width, $height) = getimagesize(CRM_Utils_String::unstupifyUrl($details->{$name}));
                         list($thumbWidth, $thumbHeight) = CRM_Contact_BAO_Contact::getThumbSize($width, $height);
                         $image_URL = '<img src="' . $details->{$name} . '" height= ' . $thumbHeight . ' width= ' . $thumbWidth . '  />';
                         $values[$index] = "<a href='#' onclick='contactImagePopUp(\"{$details->{$name}}\", {$width}, {$height});'>{$image_URL}</a>";
                     } elseif (in_array($name, array('birth_date', 'deceased_date', 'membership_start_date', 'membership_end_date', 'join_date'))) {
                         $values[$index] = CRM_Utils_Date::customFormat($details->{$name});
                         $params[$index] = CRM_Utils_Date::isoToMysql($details->{$name});
                     } else {
                         $dao = '';
                         if ($index == 'Campaign') {
                             $dao = 'CRM_Campaign_DAO_Campaign';
                         } elseif ($index == 'Contribution Page') {
                             $dao = 'CRM_Contribute_DAO_ContributionPage';
                         }
                         if ($dao) {
                             $value = CRM_Core_DAO::getFieldValue($dao, $details->{$name}, 'title');
                         } else {
                             $value = $details->{$name};
                         }
                         $values[$index] = $value;
                     }
                 }
             }
         } elseif (strpos($name, '-') !== FALSE) {
             list($fieldName, $id, $type) = CRM_Utils_System::explode('-', $name, 3);
             if (!in_array($fieldName, $multipleFields)) {
                 if ($id == 'Primary') {
                     // fix for CRM-1543
                     // not sure why we'd every use Primary location type id
                     // we need to fix the source if we are using it
                     // $locationTypeName = CRM_Contact_BAO_Contact::getPrimaryLocationType( $cid );
                     $locationTypeName = 1;
                 } else {
                     $locationTypeName = CRM_Utils_Array::value($id, $locationTypes);
                 }
                 if (!$locationTypeName) {
                     continue;
                 }
                 $detailName = "{$locationTypeName}-{$fieldName}";
                 $detailName = str_replace(' ', '_', $detailName);
                 if (in_array($fieldName, array('phone', 'im', 'email', 'openid'))) {
                     if ($type) {
                         $detailName .= "-{$type}";
                     }
                 }
                 if (in_array($fieldName, array('state_province', 'country', 'county'))) {
                     $values[$index] = $details->{$detailName};
                     $idx = $detailName . '_id';
                     $params[$index] = $details->{$idx};
                 } elseif ($fieldName == 'im') {
                     $providerId = $detailName . '-provider_id';
                     if (isset($imProviders[$details->{$providerId}])) {
                         $values[$index] = $details->{$detailName} . " (" . $imProviders[$details->{$providerId}] . ")";
                     } else {
                         $values[$index] = $details->{$detailName};
                     }
                     $params[$index] = $details->{$detailName};
                 } elseif ($fieldName == 'phone') {
                     $phoneExtField = str_replace('phone', 'phone_ext', $detailName);
                     if (isset($details->{$phoneExtField})) {
                         $values[$index] = $details->{$detailName} . " (" . $details->{$phoneExtField} . ")";
                     } else {
                         $values[$index] = $details->{$detailName};
                     }
                     $params[$index] = $details->{$detailName};
                 } else {
                     $values[$index] = $params[$index] = $details->{$detailName};
                 }
             } else {
                 $detailName = "website-{$id}-{$fieldName}";
                 $url = CRM_Utils_System::fixURL($details->{$detailName});
                 if ($details->{$detailName}) {
                     $websiteTypeId = "website-{$id}-website_type_id";
                     $websiteType = $websiteTypes[$details->{$websiteTypeId}];
                     $values[$index] = "<a href=\"{$url}\">{$details->{$detailName}} ( {$websiteType} )</a>";
                 } else {
                     $values[$index] = '';
                 }
             }
         }
         if (CRM_Utils_Array::value('visibility', $field) == 'Public Pages and Listings' && CRM_Core_Permission::check('profile listings and forms')) {
             if (CRM_Utils_System::isNull($params[$index])) {
                 $params[$index] = $values[$index];
             }
             if (!isset($params[$index])) {
                 continue;
             }
             if (!$customFieldName) {
                 $fieldName = $field['name'];
             } else {
                 $fieldName = $customFieldName;
             }
             $url = NULL;
             if (CRM_Core_BAO_CustomField::getKeyID($field['name'])) {
                 $htmlType = $field['html_type'];
                 if ($htmlType == 'Link') {
                     $url = $params[$index];
                 } elseif (in_array($htmlType, array('CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Multi-Select State/Province', 'Multi-Select Country'))) {
                     $valSeperator = CRM_Core_DAO::VALUE_SEPARATOR;
                     $selectedOptions = explode($valSeperator, $params[$index]);
                     foreach ($selectedOptions as $key => $multiOption) {
                         if ($multiOption) {
                             $url[] = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($multiOption));
                         }
                     }
                 } else {
                     $url = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($params[$index]));
                 }
             } else {
                 $url = CRM_Utils_System::url('civicrm/profile', 'reset=1&force=1&gid=' . $field['group_id'] . '&' . urlencode($fieldName) . '=' . urlencode($params[$index]));
             }
             if ($url && !empty($values[$index]) && $searchable) {
                 if (is_array($url) && !empty($url)) {
                     $links = array();
                     $eachMultiValue = explode(', ', $values[$index]);
                     foreach ($eachMultiValue as $key => $valueLabel) {
                         $links[] = '<a href="' . $url[$key] . '">' . $valueLabel . '</a>';
                     }
                     $values[$index] = implode(', ', $links);
                 } else {
                     $values[$index] = '<a href="' . $url . '">' . $values[$index] . '</a>';
                 }
             }
         }
     }
 }
 /**
  * Get all of the ACLs for a contact through ACL groups owned by Contact
  * groups.
  *
  * @param int $contact_id   -   ID of a contact to search for
  *
  * @return array            -   Array of assoc. arrays of ACL rules
  * @access public
  * @static
  */
 public static function &getGroupACLRoles($contact_id)
 {
     $contact_id = CRM_Utils_Type::escape($contact_id, 'Integer');
     $rule = new CRM_ACL_BAO_ACL();
     $acl = self::getTableName();
     $aclRole = 'civicrm_acl_role';
     $aclER = CRM_ACL_DAO_EntityRole::getTableName();
     $c2g = CRM_Contact_BAO_GroupContact::getTableName();
     $group = CRM_Contact_BAO_Group::getTableName();
     $query = "   SELECT          {$acl}.*\n                        FROM            {$acl}\n                        INNER JOIN      civicrm_option_group og\n                                ON      og.name = 'acl_role'\n                        INNER JOIN      civicrm_option_value ov\n                                ON      {$acl}.entity_table   = '{$aclRole}'\n                                AND     ov.option_group_id  = og.id\n                                AND     {$acl}.entity_id      = ov.value\n                                AND     ov.is_active        = 1\n                        INNER JOIN      {$aclER}\n                                ON      {$aclER}.acl_role_id = {$acl}.entity_id\n                                AND     {$aclER}.is_active    = 1\n                        INNER JOIN  {$c2g}\n                                ON      {$aclER}.entity_id      = {$c2g}.group_id\n                                AND     {$aclER}.entity_table   = 'civicrm_group'\n                        WHERE       {$acl}.entity_table       = '{$aclRole}'\n                            AND     {$acl}.is_active          = 1\n                            AND     {$c2g}.contact_id         = {$contact_id}\n                            AND     {$c2g}.status             = 'Added'";
     $results = array();
     $rule->query($query);
     while ($rule->fetch()) {
         $results[$rule->id] =& $rule->toArray();
     }
     // also get all acls for "Any Role" case
     // and authenticated User Role if present
     $roles = "0";
     $session = CRM_Core_Session::singleton();
     if ($session->get('ufID') > 0) {
         $roles .= ",2";
     }
     $query = "\nSELECT {$acl}.*\n  FROM {$acl}\n WHERE {$acl}.entity_id      IN ( {$roles} )\n   AND {$acl}.entity_table   = 'civicrm_acl_role'\n";
     $rule->query($query);
     while ($rule->fetch()) {
         $results[$rule->id] =& $rule->toArray();
     }
     return $results;
 }
Example #18
0
 /**
  * Form submission of new/edit contact is processed.
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     // check if dedupe button, if so return.
     $buttonName = $this->controller->getButtonName();
     if ($buttonName == $this->_dedupeButtonName) {
         return;
     }
     //get the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     //get the related id for shared / current employer
     if (CRM_Utils_Array::value('shared_household_id', $params)) {
         $params['shared_household'] = $params['shared_household_id'];
     }
     if (is_numeric(CRM_Utils_Array::value('current_employer_id', $params)) && CRM_Utils_Array::value('current_employer', $params)) {
         $params['current_employer'] = $params['current_employer_id'];
     }
     // don't carry current_employer_id field,
     // since we don't want to directly update DAO object without
     // handling related business logic ( eg related membership )
     if (isset($params['current_employer_id'])) {
         unset($params['current_employer_id']);
     }
     $params['contact_type'] = $this->_contactType;
     if ($this->_contactId) {
         $params['contact_id'] = $this->_contactId;
     }
     //make deceased date null when is_deceased = false
     if ($this->_contactType == 'Individual' && CRM_Utils_Array::value('Demographics', $this->_editOptions) && !CRM_Utils_Array::value('is_deceased', $params)) {
         $params['is_deceased'] = false;
         $params['deceased_date'] = null;
     }
     if ($this->_contactSubType && $this->_action & CRM_Core_Action::ADD) {
         $params['contact_sub_type'] = $this->_contactSubType;
     }
     // action is taken depending upon the mode
     require_once 'CRM/Utils/Hook.php';
     if ($this->_action & CRM_Core_Action::UPDATE) {
         CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params);
     } else {
         CRM_Utils_Hook::pre('create', $params['contact_type'], null, $params);
     }
     require_once 'CRM/Core/BAO/CustomField.php';
     $customFields = CRM_Core_BAO_CustomField::getFields($params['contact_type'], false, true);
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $customFields, $this->_contactId, $params['contact_type'], true);
     if (array_key_exists('CommunicationPreferences', $this->_editOptions)) {
         // this is a chekbox, so mark false if we dont get a POST value
         $params['is_opt_out'] = CRM_Utils_Array::value('is_opt_out', $params, false);
     }
     // copy household address, if use_household_address option (for individual form) is checked
     if ($this->_contactType == 'Individual') {
         if (CRM_Utils_Array::value('use_household_address', $params) && CRM_Utils_Array::value('shared_household', $params)) {
             if (is_numeric($params['shared_household'])) {
                 CRM_Contact_Form_Edit_Individual::copyHouseholdAddress($params);
             }
             CRM_Contact_Form_Edit_Individual::createSharedHousehold($params);
         } else {
             $params['mail_to_household_id'] = 'null';
         }
     } else {
         $params['mail_to_household_id'] = 'null';
     }
     if (!array_key_exists('TagsAndGroups', $this->_editOptions)) {
         unset($params['group']);
     }
     if (CRM_Utils_Array::value('contact_id', $params) && $this->_action & CRM_Core_Action::UPDATE) {
         // cleanup unwanted location blocks
         require_once 'CRM/Core/BAO/Location.php';
         CRM_Core_BAO_Location::cleanupContactLocations($params);
         // figure out which all groups are intended to be removed
         if (!empty($params['group'])) {
             $contactGroupList =& CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'], 'Added');
             if (is_array($contactGroupList)) {
                 foreach ($contactGroupList as $key) {
                     if ($params['group'][$key['group_id']] != 1) {
                         $params['group'][$key['group_id']] = -1;
                     }
                 }
             }
         }
     }
     require_once 'CRM/Contact/BAO/Contact.php';
     $contact =& CRM_Contact_BAO_Contact::create($params, true, false);
     if ($this->_contactType == 'Individual' && CRM_Utils_Array::value('use_household_address', $params) && CRM_Utils_Array::value('mail_to_household_id', $params)) {
         // add/edit/delete the relation of individual with household, if use-household-address option is checked/unchecked.
         CRM_Contact_Form_Edit_Individual::handleSharedRelation($contact->id, $params);
     }
     if ($this->_contactType == 'Household' && $this->_action & CRM_Core_Action::UPDATE) {
         //TO DO: commented because of schema changes
         require_once 'CRM/Contact/Form/Edit/Household.php';
         CRM_Contact_Form_Edit_Household::synchronizeIndividualAddresses($contact->id);
     }
     if (array_key_exists('TagsAndGroups', $this->_editOptions)) {
         //add contact to tags
         require_once 'CRM/Core/BAO/EntityTag.php';
         CRM_Core_BAO_EntityTag::create($params['tag'], $params['contact_id']);
     }
     // here we replace the user context with the url to view this contact
     $session =& CRM_Core_Session::singleton();
     CRM_Core_Session::setStatus(ts('Your %1 contact record has been saved.', array(1 => $contact->contact_type_display)));
     $buttonName = $this->controller->getButtonName();
     if ($buttonName == $this->getButtonName('next', 'new') || $buttonName == $this->getButtonName('upload', 'new')) {
         require_once 'CRM/Utils/Recent.php';
         // add the recently viewed contact
         $displayName = CRM_Contact_BAO_Contact::displayName($contact->id);
         CRM_Utils_Recent::add($displayName, CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id), $contact->id, $this->_contactType, $contact->id, $displayName);
         $resetStr = "reset=1&ct={$contact->contact_type}";
         $resetStr .= $this->_contactSubType ? "&cst={$this->_contactSubType}" : '';
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/add', $resetStr));
     } else {
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id));
     }
     // now invoke the post hook
     if ($this->_action & CRM_Core_Action::UPDATE) {
         CRM_Utils_Hook::post('edit', $params['contact_type'], $contact->id, $contact);
     } else {
         CRM_Utils_Hook::post('create', $params['contact_type'], $contact->id, $contact);
     }
 }
 /**
  * Takes an associative array and creates / removes
  * contacts from the groups
  *
  *
  * @param array $params
  *   (reference ) an assoc array of name/value pairs.
  * @param array $contactId
  *   Contact id.
  *
  * @param bool $visibility
  * @param string $method
  *
  * @return void
  */
 public static function create(&$params, $contactId, $visibility = FALSE, $method = 'Admin')
 {
     $contactIds = array();
     $contactIds[] = $contactId;
     //if $visibility is true we are coming in via profile mean $method = 'Web'
     $ignorePermission = FALSE;
     if ($visibility) {
         $ignorePermission = TRUE;
     }
     if ($contactId) {
         $contactGroupList =& CRM_Contact_BAO_GroupContact::getContactGroup($contactId, 'Added', NULL, FALSE, $ignorePermission);
         if (is_array($contactGroupList)) {
             foreach ($contactGroupList as $key) {
                 $groupId = $key['group_id'];
                 $contactGroup[$groupId] = $groupId;
             }
         }
     }
     // get the list of all the groups
     $allGroup = CRM_Contact_BAO_GroupContact::getGroupList(0, $visibility);
     // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
     if (!is_array($params)) {
         $params = array();
     }
     // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
     if (!isset($contactGroup) || !is_array($contactGroup)) {
         $contactGroup = array();
     }
     // check which values has to be add/remove contact from group
     foreach ($allGroup as $key => $varValue) {
         if (!empty($params[$key]) && !array_key_exists($key, $contactGroup)) {
             // add contact to group
             CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $key, $method);
         } elseif (empty($params[$key]) && array_key_exists($key, $contactGroup)) {
             // remove contact from group
             CRM_Contact_BAO_GroupContact::removeContactsFromGroup($contactIds, $key, $method);
         }
     }
 }
Example #20
0
 /**
  * Function to build the array for display the profile fields
  *
  * @param array $params key value.
  * @param int $gid profile Id
  * @param array $groupTitle Profile Group Title.
  * @param array $values formatted array of key value
  *
  * @param array $profileFields
  *
  * @return void
  * @access public
  * @static
  */
 static function displayProfile(&$params, $gid, &$groupTitle, &$values, &$profileFields = array())
 {
     if ($gid) {
         $config = CRM_Core_Config::singleton();
         $session = CRM_Core_Session::singleton();
         $contactID = $session->get('userID');
         if ($contactID) {
             if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $contactID)) {
                 $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::VIEW);
             }
         } else {
             $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::ADD);
         }
         foreach ($fields as $v) {
             if (!empty($v['groupTitle'])) {
                 $groupTitle['groupTitle'] = $v['groupTitle'];
                 break;
             }
         }
         $customVal = '';
         $imProviders = CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id');
         //start of code to set the default values
         foreach ($fields as $name => $field) {
             $skip = FALSE;
             // skip fields that should not be displayed separately
             if ($field['skipDisplay']) {
                 continue;
             }
             $index = $field['title'];
             if ($name === 'organization_name') {
                 $values[$index] = $params[$name];
             }
             if ('state_province' == substr($name, 0, 14)) {
                 if ($params[$name]) {
                     $values[$index] = CRM_Core_PseudoConstant::stateProvince($params[$name]);
                 } else {
                     $values[$index] = '';
                 }
             } elseif ('date' == substr($name, -4)) {
                 $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::processDate($params[$name]), $config->dateformatFull);
             } elseif ('country' == substr($name, 0, 7)) {
                 if ($params[$name]) {
                     $values[$index] = CRM_Core_PseudoConstant::country($params[$name]);
                 } else {
                     $values[$index] = '';
                 }
             } elseif ('county' == substr($name, 0, 6)) {
                 if ($params[$name]) {
                     $values[$index] = CRM_Core_PseudoConstant::county($params[$name]);
                 } else {
                     $values[$index] = '';
                 }
             } elseif (in_array(substr($name, 0, -3), array('gender', 'prefix', 'suffix', 'communication_style'))) {
                 $values[$index] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_DAO_Contact', $name, $params[$name]);
             } elseif (in_array($name, array('addressee', 'email_greeting', 'postal_greeting'))) {
                 $filterCondition = array('greeting_type' => $name);
                 $greeting = CRM_Core_PseudoConstant::greeting($filterCondition);
                 $values[$index] = $greeting[$params[$name]];
             } elseif ($name === 'preferred_communication_method') {
                 $communicationFields = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
                 $compref = array();
                 $pref = $params[$name];
                 if (is_array($pref)) {
                     foreach ($pref as $k => $v) {
                         if ($v) {
                             $compref[] = $communicationFields[$k];
                         }
                     }
                 }
                 $values[$index] = implode(',', $compref);
             } elseif ($name == 'contact_sub_type') {
                 $values[$index] = implode(', ', $params[$name]);
             } elseif ($name == 'group') {
                 $groups = CRM_Contact_BAO_GroupContact::getGroupList();
                 $title = array();
                 foreach ($params[$name] as $gId => $dontCare) {
                     if ($dontCare) {
                         $title[] = $groups[$gId];
                     }
                 }
                 $values[$index] = implode(', ', $title);
             } elseif ($name == 'tag') {
                 $entityTags = $params[$name];
                 $allTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', array('onlyActive' => FALSE));
                 $title = array();
                 if (is_array($entityTags)) {
                     foreach ($entityTags as $tagId => $dontCare) {
                         $title[] = $allTags[$tagId];
                     }
                 }
                 $values[$index] = implode(', ', $title);
             } elseif ('participant_role_id' == $name or 'participant_role' == $name) {
                 $roles = CRM_Event_PseudoConstant::participantRole();
                 $values[$index] = $roles[$params[$name]];
             } elseif ('participant_status_id' == $name or 'participant_status' == $name) {
                 $status = CRM_Event_PseudoConstant::participantStatus();
                 $values[$index] = $status[$params[$name]];
             } elseif (substr($name, -11) == 'campaign_id') {
                 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($params[$name]);
                 $values[$index] = CRM_Utils_Array::value($params[$name], $campaigns);
             } elseif (strpos($name, '-') !== FALSE) {
                 list($fieldName, $id) = CRM_Utils_System::explode('-', $name, 2);
                 $detailName = str_replace(' ', '_', $name);
                 if (in_array($fieldName, array('state_province', 'country', 'county'))) {
                     $values[$index] = $params[$detailName];
                     $idx = $detailName . '_id';
                     $values[$index] = $params[$idx];
                 } elseif ($fieldName == 'im') {
                     $providerName = NULL;
                     if ($providerId = $detailName . '-provider_id') {
                         $providerName = CRM_Utils_Array::value($params[$providerId], $imProviders);
                     }
                     if ($providerName) {
                         $values[$index] = $params[$detailName] . " (" . $providerName . ")";
                     } else {
                         $values[$index] = $params[$detailName];
                     }
                 } elseif ($fieldName == 'phone') {
                     $phoneExtField = str_replace('phone', 'phone_ext', $detailName);
                     if (isset($params[$phoneExtField])) {
                         $values[$index] = $params[$detailName] . " (" . $params[$phoneExtField] . ")";
                     } else {
                         $values[$index] = $params[$detailName];
                     }
                 } else {
                     $values[$index] = $params[$detailName];
                 }
             } else {
                 if (substr($name, 0, 7) === 'do_not_' or substr($name, 0, 3) === 'is_') {
                     if ($params[$name]) {
                         $values[$index] = '[ x ]';
                     }
                 } else {
                     if ($cfID = CRM_Core_BAO_CustomField::getKeyID($name)) {
                         $query = "\nSELECT html_type, data_type\nFROM   civicrm_custom_field\nWHERE  id = {$cfID}\n";
                         $dao = CRM_Core_DAO::executeQuery($query);
                         $dao->fetch();
                         $htmlType = $dao->html_type;
                         if ($htmlType == 'File') {
                             $values[$index] = $params[$index];
                         } else {
                             if ($dao->data_type == 'Int' || $dao->data_type == 'Boolean') {
                                 $v = $params[$name];
                                 if (!CRM_Utils_System::isNull($v)) {
                                     $customVal = (int) $v;
                                 }
                             } elseif ($dao->data_type == 'Float') {
                                 $customVal = (double) $params[$name];
                             } elseif ($dao->data_type == 'Date') {
                                 //@todo note the currently we are using default date time formatting. Since you can select/set
                                 // different date and time format specific to custom field we should consider fixing this
                                 // sometime in the future
                                 $customVal = $displayValue = CRM_Utils_Date::customFormat(CRM_Utils_Date::processDate($params[$name]), $config->dateformatFull);
                                 if (!empty($params[$name . '_time'])) {
                                     $customVal = $displayValue = CRM_Utils_Date::customFormat(CRM_Utils_Date::processDate($params[$name], $params[$name . '_time']), $config->dateformatDatetime);
                                 }
                                 $skip = TRUE;
                             } else {
                                 $customVal = $params[$name];
                             }
                             //take the custom field options
                             $returnProperties = array($name => 1);
                             $query = new CRM_Contact_BAO_Query($params, $returnProperties, $fields);
                             $options =& $query->_options;
                             if (!$skip) {
                                 $displayValue = CRM_Core_BAO_CustomField::getDisplayValue($customVal, $cfID, $options);
                             }
                             //Hack since we dont have function to check empty.
                             //FIXME in 2.3 using crmIsEmptyArray()
                             $customValue = TRUE;
                             if (is_array($customVal) && is_array($displayValue)) {
                                 $customValue = array_diff($customVal, $displayValue);
                             }
                             //use difference of arrays
                             if (empty($customValue) || !$customValue) {
                                 $values[$index] = '';
                             } else {
                                 $values[$index] = $displayValue;
                             }
                         }
                     } elseif ($name == 'home_URL' && !empty($params[$name])) {
                         $url = CRM_Utils_System::fixURL($params[$name]);
                         $values[$index] = "<a href=\"{$url}\">{$params[$name]}</a>";
                     } elseif (in_array($name, array('birth_date', 'deceased_date', 'participant_register_date'))) {
                         $values[$index] = CRM_Utils_Date::customFormat(CRM_Utils_Date::format($params[$name]));
                     } else {
                         $values[$index] = $params[$name];
                     }
                 }
             }
             $profileFields[$name] = $field;
         }
     }
 }
Example #21
0
 /**
  * Add contact to group.
  *
  * @param int $groupID
  */
 public function add2group($groupID)
 {
     if (is_numeric($groupID) && isset($this->_aliases['civicrm_contact'])) {
         $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
         // here are we are prepending / adding  contact id field that could be used for adding group
         // so first check for "SELECT SQL_CALC_FOUND_ROWS" and if does not exist replace "SELECT"
         if (preg_match('/^SELECT SQL_CALC_FOUND_ROWS/', $this->_select)) {
             $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select);
         } else {
             $select = str_ireplace('SELECT ', $select, $this->_select);
         }
         $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
         $sql = str_replace('WITH ROLLUP', '', $sql);
         $dao = CRM_Core_DAO::executeQuery($sql);
         $contact_ids = array();
         // Add resulting contacts to group
         while ($dao->fetch()) {
             if ($dao->addtogroup_contact_id) {
                 $contact_ids[$dao->addtogroup_contact_id] = $dao->addtogroup_contact_id;
             }
         }
         if (!empty($contact_ids)) {
             CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID);
             CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
         } else {
             CRM_Core_Session::setStatus(ts("The listed records(s) cannot be added to the group."));
         }
     }
 }
Example #22
0
 /**
  * Unsubscribe a contact from all groups that received this mailing
  *
  * @param int $job_id       The job ID
  * @param int $queue_id     The Queue Event ID of the recipient
  * @param string $hash      The hash
  * @param boolean $return   If true return the list of groups.
  * @return array|null $groups    Array of all groups from which the contact was removed, or null if the queue event could not be found.
  * @access public
  * @static
  */
 public static function &unsub_from_mailing($job_id, $queue_id, $hash, $return = false)
 {
     /* First make sure there's a matching queue event */
     $q =& CRM_Mailing_Event_BAO_Queue::verify($job_id, $queue_id, $hash);
     if (!$q) {
         return null;
     }
     $contact_id = $q->contact_id;
     require_once 'CRM/Core/Transaction.php';
     $transaction = new CRM_Core_Transaction();
     $do =& new CRM_Core_DAO();
     $mg = CRM_Mailing_DAO_Group::getTableName();
     $job = CRM_Mailing_BAO_Job::getTableName();
     $mailing = CRM_Mailing_BAO_Mailing::getTableName();
     $group = CRM_Contact_BAO_Group::getTableName();
     $gc = CRM_Contact_BAO_GroupContact::getTableName();
     $do->query("\n            SELECT      {$mg}.entity_table as entity_table,\n                        {$mg}.entity_id as entity_id\n            FROM        {$mg}\n            INNER JOIN  {$job}\n                ON      {$job}.mailing_id = {$mg}.mailing_id\n            WHERE       {$job}.id = " . CRM_Utils_Type::escape($job_id, 'Integer') . "\n                AND     {$mg}.group_type = 'Include'");
     /* Make a list of groups and a list of prior mailings that received 
      * this mailing */
     $groups = array();
     $mailings = array();
     while ($do->fetch()) {
         if ($do->entity_table == $group) {
             //$groups[$do->entity_id] = true;
             $groups[$do->entity_id] = null;
         } else {
             if ($do->entity_table == $mailing) {
                 $mailings[] = $do->entity_id;
             }
         }
     }
     /* As long as we have prior mailings, find their groups and add to the
      * list */
     while (!empty($mailings)) {
         $do->query("\n                SELECT      {$mg}.entity_table as entity_table,\n                            {$mg}.entity_id as entity_id\n                FROM        {$mg}\n                WHERE       {$mg}.mailing_id IN (" . implode(', ', $mailings) . ")\n                    AND     {$mg}.group_type = 'Include'");
         $mailings = array();
         while ($do->fetch()) {
             if ($do->entity_table == $group) {
                 $groups[$do->entity_id] = true;
             } else {
                 if ($do->entity_table == $mailing) {
                     $mailings[] = $do->entity_id;
                 }
             }
         }
     }
     /* Now we have a complete list of recipient groups.  Filter out all
      * those except smart groups and those that the contact belongs to */
     $do->query("\n            SELECT      {$group}.id as group_id,\n                        {$group}.title as title,\n                        {$group}.description as description\n            FROM        {$group}\n            LEFT JOIN   {$gc}\n                ON      {$gc}.group_id = {$group}.id\n            WHERE       {$group}.id IN (" . implode(', ', array_keys($groups)) . ")\n                AND     ({$group}.saved_search_id is not null\n                            OR  ({$gc}.contact_id = {$contact_id}\n                                AND {$gc}.status = 'Added')\n                        )");
     if ($return) {
         while ($do->fetch()) {
             $groups[$do->group_id] = array('title' => $do->title, 'description' => $do->description);
         }
         return $groups;
     } else {
         while ($do->fetch()) {
             $groups[$do->group_id] = $do->title;
         }
     }
     $contacts = array($contact_id);
     foreach ($groups as $group_id => $group_name) {
         $notremoved = false;
         if ($group_name) {
             list($total, $removed, $notremoved) = CRM_Contact_BAO_GroupContact::removeContactsFromGroup($contacts, $group_id, 'Email');
         }
         if ($notremoved) {
             unset($groups[$group_id]);
         }
     }
     $ue =& new CRM_Mailing_Event_BAO_Unsubscribe();
     $ue->event_queue_id = $queue_id;
     $ue->org_unsubscribe = 0;
     $ue->time_stamp = date('YmdHis');
     $ue->save();
     $transaction->commit();
     return $groups;
 }
 /**
  * Get options for a given contact field.
  *
  * @see CRM_Core_DAO::buildOptions
  *
  * TODO: Should we always assume chainselect? What fn should be responsible for controlling that flow?
  * TODO: In context of chainselect, what to return if e.g. a country has no states?
  *
  * @param string $fieldName
  * @param string $context
  * @see CRM_Core_DAO::buildOptionsContext
  * @param array $props
  *   whatever is known about this dao object.
  *
  * @return array|bool
  */
 public static function buildOptions($fieldName, $context = NULL, $props = array())
 {
     $params = array();
     // Special logic for fields whose options depend on context or properties
     switch ($fieldName) {
         case 'contact_sub_type':
             if (!empty($props['contact_type'])) {
                 $params['condition'] = "parent_id = (SELECT id FROM civicrm_contact_type WHERE name='{$props['contact_type']}')";
             }
             break;
         case 'contact_type':
             if ($context == 'search') {
                 // CRM-15495 - EntityRef filters and basic search forms expect this format
                 // FIXME: Search builder does not
                 return CRM_Contact_BAO_ContactType::getSelectElements();
             }
             break;
             // The contact api supports some related entities so we'll honor that by fetching their options
         // The contact api supports some related entities so we'll honor that by fetching their options
         case 'group_id':
         case 'group':
             return CRM_Contact_BAO_GroupContact::buildOptions('group_id', $context, $props);
         case 'tag_id':
         case 'tag':
             $props['entity_table'] = 'civicrm_contact';
             return CRM_Core_BAO_EntityTag::buildOptions('tag_id', $context, $props);
     }
     return CRM_Core_PseudoConstant::get(__CLASS__, $fieldName, $params, $context);
 }
Example #24
0
 /**
  * Register a subscription event.  Create a new contact if one does not
  * already exist.
  *
  * @param int $group_id
  *   The group id to subscribe to.
  * @param string $email
  *   The email address of the (new) contact.
  * @param int $contactId
  *   Currently used during event registration/contribution.
  *   Specifically to avoid linking group to wrong duplicate contact
  *   during event registration.
  * @param string $context
  *
  * @return int|null
  *   $se_id      The id of the subscription event, null on failure
  */
 public static function &subscribe($group_id, $email, $contactId = NULL, $context = NULL)
 {
     // CRM-1797 - allow subscription only to public groups
     $params = array('id' => (int) $group_id);
     $defaults = array();
     $contact_id = NULL;
     $success = NULL;
     $bao = CRM_Contact_BAO_Group::retrieve($params, $defaults);
     if ($bao && substr($bao->visibility, 0, 6) != 'Public' && $context != 'profile') {
         return $success;
     }
     $strtolower = function_exists('mb_strtolower') ? 'mb_strtolower' : 'strtolower';
     $email = $strtolower($email);
     // process the query only if no contactId
     if ($contactId) {
         $contact_id = $contactId;
     } else {
         /* First, find out if the contact already exists */
         $query = "\n   SELECT DISTINCT contact_a.id as contact_id\n     FROM civicrm_contact contact_a\nLEFT JOIN civicrm_email      ON contact_a.id = civicrm_email.contact_id\n    WHERE civicrm_email.email = %1 AND contact_a.is_deleted = 0";
         $params = array(1 => array($email, 'String'));
         $dao = CRM_Core_DAO::executeQuery($query, $params);
         $id = array();
         // lets just use the first contact id we got
         if ($dao->fetch()) {
             $contact_id = $dao->contact_id;
         }
         $dao->free();
     }
     $transaction = new CRM_Core_Transaction();
     if (!$contact_id) {
         require_once 'CRM/Utils/DeprecatedUtils.php';
         /* If the contact does not exist, create one. */
         $formatted = array('contact_type' => 'Individual', 'version' => 3);
         $locationType = CRM_Core_BAO_LocationType::getDefault();
         $value = array('email' => $email, 'location_type_id' => $locationType->id);
         _civicrm_api3_deprecated_add_formatted_param($value, $formatted);
         $formatted['onDuplicate'] = CRM_Import_Parser::DUPLICATE_SKIP;
         $formatted['fixAddress'] = TRUE;
         require_once 'api/api.php';
         $contact = civicrm_api('contact', 'create', $formatted);
         if (civicrm_error($contact)) {
             return $success;
         }
         $contact_id = $contact['id'];
     } elseif (!is_numeric($contact_id) && (int) $contact_id > 0) {
         // make sure contact_id is numeric
         return $success;
     }
     /* Get the primary email id from the contact to use as a hash input */
     $dao = new CRM_Core_DAO();
     $query = "\nSELECT     civicrm_email.id as email_id\n  FROM     civicrm_email\n     WHERE civicrm_email.email = %1\n       AND civicrm_email.contact_id = %2";
     $params = array(1 => array($email, 'String'), 2 => array($contact_id, 'Integer'));
     $dao = CRM_Core_DAO::executeQuery($query, $params);
     if (!$dao->fetch()) {
         CRM_Core_Error::fatal('Please file an issue with the backtrace');
         return $success;
     }
     $se = new CRM_Mailing_Event_BAO_Subscribe();
     $se->group_id = $group_id;
     $se->contact_id = $contact_id;
     $se->time_stamp = date('YmdHis');
     $se->hash = substr(sha1("{$group_id}:{$contact_id}:{$dao->email_id}:" . time()), 0, 16);
     $se->save();
     $contacts = array($contact_id);
     CRM_Contact_BAO_GroupContact::addContactsToGroup($contacts, $group_id, 'Email', 'Pending', $se->id);
     $transaction->commit();
     return $se;
 }
 public function postProcess()
 {
     $values = $this->controller->exportValues($this->_name);
     //build hidden smart group. when user want to send  mailing
     //through search contact-> more action -> send Mailing. CRM-3711
     $groups = array();
     if ($this->_searchBasedMailing && $this->_contactIds) {
         $session = CRM_Core_Session::singleton();
         if ($this->_resultSelectOption == 'ts_sel') {
             // create a static grp if only a subset of result set was selected:
             $randID = md5(time());
             $grpTitle = "Hidden Group {$randID}";
             $grpID = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Group', $grpTitle, 'id', 'title');
             if (!$grpID) {
                 $groupParams = array('title' => $grpTitle, 'is_active' => 1, 'is_hidden' => 1, 'group_type' => array('2' => 1));
                 $group = CRM_Contact_BAO_Group::create($groupParams);
                 $grpID = $group->id;
                 CRM_Contact_BAO_GroupContact::addContactsToGroup($this->_contactIds, $group->id);
                 $newGroupTitle = "Hidden Group {$grpID}";
                 $groupParams = array('id' => $grpID, 'name' => CRM_Utils_String::titleToVar($newGroupTitle), 'title' => $newGroupTitle);
                 $group = CRM_Contact_BAO_Group::create($groupParams);
             }
             // note at this point its a static group
             $smartGroupId = $grpID;
         } else {
             //get the hidden smart group id.
             $ssId = $this->get('ssID');
             $hiddenSmartParams = array('group_type' => array('2' => 1), 'form_values' => $this->get('formValues'), 'saved_search_id' => $ssId, 'search_custom_id' => $this->get('customSearchID'), 'search_context' => $this->get('context'));
             list($smartGroupId, $savedSearchId) = CRM_Contact_BAO_Group::createHiddenSmartGroup($hiddenSmartParams);
             //set the saved search id.
             if (!$ssId) {
                 if ($savedSearchId) {
                     $this->set('ssID', $savedSearchId);
                 } else {
                     CRM_Core_Error::fatal();
                 }
             }
         }
         //get the base group for this mailing, CRM-3711
         $groups['base'] = array($values['baseGroup']);
         $values['includeGroups'][] = $smartGroupId;
     }
     foreach (array('name', 'group_id', 'search_id', 'search_args', 'campaign_id', 'dedupe_email') as $n) {
         if (CRM_Utils_Array::value($n, $values)) {
             $params[$n] = $values[$n];
         }
     }
     $qf_Group_submit = $this->controller->exportValue($this->_name, '_qf_Group_submit');
     $this->set('name', $params['name']);
     $inGroups = $values['includeGroups'];
     $outGroups = $values['excludeGroups'];
     $inMailings = $values['includeMailings'];
     $outMailings = $values['excludeMailings'];
     if (is_array($inGroups)) {
         foreach ($inGroups as $key => $id) {
             if ($id) {
                 $groups['include'][] = $id;
             }
         }
     }
     if (is_array($outGroups)) {
         foreach ($outGroups as $key => $id) {
             if ($id) {
                 $groups['exclude'][] = $id;
             }
         }
     }
     $mailings = array();
     if (is_array($inMailings)) {
         foreach ($inMailings as $key => $id) {
             if ($id) {
                 $mailings['include'][] = $id;
             }
         }
     }
     if (is_array($outMailings)) {
         foreach ($outMailings as $key => $id) {
             if ($id) {
                 $mailings['exclude'][] = $id;
             }
         }
     }
     $session = CRM_Core_Session::singleton();
     $params['groups'] = $groups;
     $params['mailings'] = $mailings;
     if ($this->get('mailing_id')) {
         $ids = array();
         // don't create a new mailing if already exists
         $ids['mailing_id'] = $this->get('mailing_id');
         $groupTableName = CRM_Contact_BAO_Group::getTableName();
         $mailingTableName = CRM_Mailing_BAO_Mailing::getTableName();
         // delete previous includes/excludes, if mailing already existed
         foreach (array('groups', 'mailings') as $entity) {
             $mg = new CRM_Mailing_DAO_Group();
             $mg->mailing_id = $ids['mailing_id'];
             $mg->entity_table = $entity == 'groups' ? $groupTableName : $mailingTableName;
             $mg->find();
             while ($mg->fetch()) {
                 $mg->delete();
             }
         }
     } else {
         // new mailing, so lets set the created_id
         $session = CRM_Core_Session::singleton();
         $params['created_id'] = $session->get('userID');
         $params['created_date'] = date('YmdHis');
     }
     $mailing = CRM_Mailing_BAO_Mailing::create($params, $ids);
     $this->set('mailing_id', $mailing->id);
     $dedupeEmail = FALSE;
     if (isset($params['dedupe_email'])) {
         $dedupeEmail = $params['dedupe_email'];
     }
     // also compute the recipients and store them in the mailing recipients table
     CRM_Mailing_BAO_Mailing::getRecipients($mailing->id, $mailing->id, NULL, NULL, TRUE, $dedupeEmail);
     $count = CRM_Mailing_BAO_Recipients::mailingSize($mailing->id);
     $this->set('count', $count);
     $this->assign('count', $count);
     $this->set('groups', $groups);
     $this->set('mailings', $mailings);
     if ($qf_Group_submit) {
         //when user perform mailing from search context
         //redirect it to search result CRM-3711.
         $ssID = $this->get('ssID');
         $context = $this->get('context');
         if ($ssID && $this->_searchBasedMailing) {
             if ($this->_action == CRM_Core_Action::BASIC) {
                 $fragment = 'search';
             } elseif ($this->_action == CRM_Core_Action::PROFILE) {
                 $fragment = 'search/builder';
             } elseif ($this->_action == CRM_Core_Action::ADVANCED) {
                 $fragment = 'search/advanced';
             } else {
                 $fragment = 'search/custom';
             }
             $context = $this->get('context');
             if (!CRM_Contact_Form_Search::isSearchContext($context)) {
                 $context = 'search';
             }
             $urlParams = "force=1&reset=1&ssID={$ssID}&context={$context}";
             $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
             if (CRM_Utils_Rule::qfKey($qfKey)) {
                 $urlParams .= "&qfKey={$qfKey}";
             }
             $draftURL = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             $status = ts("Your mailing has been saved. You can continue later by clicking the 'Continue' action to resume working on it.<br /> From <a href='%1'>Draft and Unscheduled Mailings</a>.", array(1 => $draftURL));
             CRM_Core_Session::setStatus($status);
             //replace user context to search.
             $url = CRM_Utils_System::url('civicrm/contact/' . $fragment, $urlParams);
             return $this->controller->setDestination($url);
         } else {
             $status = ts("Your mailing has been saved. Click the 'Continue' action to resume working on it.");
             CRM_Core_Session::setStatus($status);
             $url = CRM_Utils_System::url('civicrm/mailing/browse/unscheduled', 'scheduled=false&reset=1');
             return $this->controller->setDestination($url);
         }
     }
 }
 /**
  *
  * @return void
  */
 public function postProcess()
 {
     $contactID = array($this->_contactId);
     $groupId = $this->controller->exportValue('GroupContact', 'group_id');
     $method = $this->_context == 'user' ? 'Web' : 'Admin';
     $session = CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     if ($userID == $this->_contactId) {
         $method = 'Web';
     }
     $groupContact = CRM_Contact_BAO_GroupContact::addContactsToGroup($contactID, $groupId, $method);
     if ($groupContact && $this->_context != 'user') {
         $groups = CRM_Core_PseudoConstant::group();
         CRM_Core_Session::setStatus(ts("Contact has been added to '%1'.", array(1 => $groups[$groupId])), ts('Added to Group'), 'success');
     }
 }
Example #27
0
 /**
 * takes an associative array and sends a thank you or email verification email
 *
 * @param array $params (reference ) an assoc array of name/value pairs
 *
 * @param $sendEmailMode
 *
 * @throws Exception
 * @return void
   @access public
 * @static
 */
 public static function sendEmail($params, $sendEmailMode)
 {
     /* sendEmailMode
      * CRM_Campaign_Form_Petition_Signature::EMAIL_THANK
      *   connected user via login/pwd - thank you
      *    or dedupe contact matched who doesn't have a tag CIVICRM_TAG_UNCONFIRMED - thank you
      *   or login using fb connect - thank you + click to add msg to fb wall
      *
      * CRM_Campaign_Form_Petition_Signature::EMAIL_CONFIRM
      *  send a confirmation request email
      */
     // check if the group defined by CIVICRM_PETITION_CONTACTS exists, else create it
     $petitionGroupName = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'petition_contacts', NULL, 'Petition Contacts');
     $dao = new CRM_Contact_DAO_Group();
     $dao->title = $petitionGroupName;
     if (!$dao->find(TRUE)) {
         $dao->is_active = 1;
         $dao->visibility = 'User and User Admin Only';
         $dao->save();
     }
     $group_id = $dao->id;
     // get petition info
     $petitionParams['id'] = $params['sid'];
     $petitionInfo = array();
     CRM_Campaign_BAO_Survey::retrieve($petitionParams, $petitionInfo);
     if (empty($petitionInfo)) {
         CRM_Core_Error::fatal('Petition doesn\'t exist.');
     }
     //get the default domain email address.
     list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
     $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
     $toName = CRM_Contact_BAO_Contact::displayName($params['contactId']);
     $replyTo = "do-not-reply@{$emailDomain}";
     // set additional general message template params (custom tokens to use in email msg templates)
     // tokens then available in msg template as {$petition.title}, etc
     $petitionTokens['title'] = $petitionInfo['title'];
     $petitionTokens['petitionId'] = $params['sid'];
     $tplParams['petition'] = $petitionTokens;
     switch ($sendEmailMode) {
         case CRM_Campaign_Form_Petition_Signature::EMAIL_THANK:
             // add this contact to the CIVICRM_PETITION_CONTACTS group
             // Cannot pass parameter 1 by reference
             $p = array($params['contactId']);
             CRM_Contact_BAO_GroupContact::addContactsToGroup($p, $group_id, 'API');
             if ($params['email-Primary']) {
                 CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_petition', 'valueName' => 'petition_sign', 'contactId' => $params['contactId'], 'tplParams' => $tplParams, 'from' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'toName' => $toName, 'toEmail' => $params['email-Primary'], 'replyTo' => $replyTo, 'petitionId' => $params['sid'], 'petitionTitle' => $petitionInfo['title']));
             }
             break;
         case CRM_Campaign_Form_Petition_Signature::EMAIL_CONFIRM:
             // create mailing event subscription record for this contact
             // this will allow using a hash key to confirm email address by sending a url link
             $se = CRM_Mailing_Event_BAO_Subscribe::subscribe($group_id, $params['email-Primary'], $params['contactId'], 'profile');
             //    require_once 'CRM/Core/BAO/Domain.php';
             //    $domain = CRM_Core_BAO_Domain::getDomain();
             $config = CRM_Core_Config::singleton();
             $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
             $replyTo = implode($config->verpSeparator, array($localpart . 'c', $se->contact_id, $se->id, $se->hash)) . "@{$emailDomain}";
             $confirmUrl = CRM_Utils_System::url('civicrm/petition/confirm', "reset=1&cid={$se->contact_id}&sid={$se->id}&h={$se->hash}&a={$params['activityId']}&p={$params['sid']}", TRUE);
             $confirmUrlPlainText = CRM_Utils_System::url('civicrm/petition/confirm', "reset=1&cid={$se->contact_id}&sid={$se->id}&h={$se->hash}&a={$params['activityId']}&p={$params['sid']}", TRUE, NULL, FALSE);
             // set email specific message template params and assign to tplParams
             $petitionTokens['confirmUrl'] = $confirmUrl;
             $petitionTokens['confirmUrlPlainText'] = $confirmUrlPlainText;
             $tplParams['petition'] = $petitionTokens;
             if ($params['email-Primary']) {
                 CRM_Core_BAO_MessageTemplate::sendTemplate(array('groupName' => 'msg_tpl_workflow_petition', 'valueName' => 'petition_confirmation_needed', 'contactId' => $params['contactId'], 'tplParams' => $tplParams, 'from' => "\"{$domainEmailName}\" <{$domainEmailAddress}>", 'toName' => $toName, 'toEmail' => $params['email-Primary'], 'replyTo' => $replyTo, 'petitionId' => $params['sid'], 'petitionTitle' => $petitionInfo['title'], 'confirmUrl' => $confirmUrl));
             }
             break;
     }
 }
 /**
  *
  * @access public
  * @return None
  */
 public function postProcess()
 {
     $contactID = array($this->_contactId);
     $groupId = $this->controller->exportValue('GroupContact', 'group_id');
     $method = 'Admin';
     $method = $this->_context == 'user' ? 'Web' : 'Admin';
     $session = CRM_Core_Session::singleton();
     $userID = $session->get('userID');
     if ($userID == $this->_contactId) {
         $method = 'Web';
     }
     $groupContact = CRM_Contact_BAO_GroupContact::addContactsToGroup($contactID, $groupId, $method);
     if ($groupContact && $this->_context != 'user') {
         CRM_Core_Session::setStatus(ts('Contact has been added to the selected group.'));
     }
 }
Example #29
0
 /**
  * Form submission of new/edit contact is processed.
  */
 public function postProcess()
 {
     // check if dedupe button, if so return.
     $buttonName = $this->controller->getButtonName();
     if ($buttonName == $this->_dedupeButtonName) {
         return;
     }
     //get the submitted values in an array
     $params = $this->controller->exportValues($this->_name);
     $group = CRM_Utils_Array::value('group', $params);
     if (!empty($group) && is_array($group)) {
         unset($params['group']);
         foreach ($group as $key => $value) {
             $params['group'][$value] = 1;
         }
     }
     CRM_Contact_BAO_Contact_Optimizer::edit($params, $this->_preEditValues);
     if (!empty($params['image_URL'])) {
         CRM_Contact_BAO_Contact::processImageParams($params);
     }
     if (is_numeric(CRM_Utils_Array::value('current_employer_id', $params)) && !empty($params['current_employer'])) {
         $params['current_employer'] = $params['current_employer_id'];
     }
     // don't carry current_employer_id field,
     // since we don't want to directly update DAO object without
     // handling related business logic ( eg related membership )
     if (isset($params['current_employer_id'])) {
         unset($params['current_employer_id']);
     }
     $params['contact_type'] = $this->_contactType;
     if (empty($params['contact_sub_type']) && $this->_isContactSubType) {
         $params['contact_sub_type'] = array($this->_contactSubType);
     }
     if ($this->_contactId) {
         $params['contact_id'] = $this->_contactId;
     }
     //make deceased date null when is_deceased = false
     if ($this->_contactType == 'Individual' && !empty($this->_editOptions['Demographics']) && empty($params['is_deceased'])) {
         $params['is_deceased'] = FALSE;
         $params['deceased_date'] = NULL;
     }
     if (isset($params['contact_id'])) {
         // process membership status for deceased contact
         $deceasedParams = array('contact_id' => CRM_Utils_Array::value('contact_id', $params), 'is_deceased' => CRM_Utils_Array::value('is_deceased', $params, FALSE), 'deceased_date' => CRM_Utils_Array::value('deceased_date', $params, NULL));
         $updateMembershipMsg = $this->updateMembershipStatus($deceasedParams);
     }
     // action is taken depending upon the mode
     if ($this->_action & CRM_Core_Action::UPDATE) {
         CRM_Utils_Hook::pre('edit', $params['contact_type'], $params['contact_id'], $params);
     } else {
         CRM_Utils_Hook::pre('create', $params['contact_type'], NULL, $params);
     }
     $customFields = CRM_Core_BAO_CustomField::getFields($params['contact_type'], FALSE, TRUE);
     //CRM-5143
     //if subtype is set, send subtype as extend to validate subtype customfield
     $customFieldExtends = CRM_Utils_Array::value('contact_sub_type', $params) ? $params['contact_sub_type'] : $params['contact_type'];
     $params['custom'] = CRM_Core_BAO_CustomField::postProcess($params, $this->_contactId, $customFieldExtends, TRUE);
     if ($this->_contactId && !empty($this->_oldSubtypes)) {
         CRM_Contact_BAO_ContactType::deleteCustomSetForSubtypeMigration($this->_contactId, $params['contact_type'], $this->_oldSubtypes, $params['contact_sub_type']);
     }
     if (array_key_exists('CommunicationPreferences', $this->_editOptions)) {
         // this is a chekbox, so mark false if we dont get a POST value
         $params['is_opt_out'] = CRM_Utils_Array::value('is_opt_out', $params, FALSE);
     }
     // process shared contact address.
     CRM_Contact_BAO_Contact_Utils::processSharedAddress($params['address']);
     if (!array_key_exists('TagsAndGroups', $this->_editOptions) && !empty($params['group'])) {
         unset($params['group']);
     }
     if (!empty($params['contact_id']) && $this->_action & CRM_Core_Action::UPDATE && !empty($params['group'])) {
         // figure out which all groups are intended to be removed
         $contactGroupList = CRM_Contact_BAO_GroupContact::getContactGroup($params['contact_id'], 'Added');
         if (is_array($contactGroupList)) {
             foreach ($contactGroupList as $key) {
                 if ((!array_key_exists($key['group_id'], $params['group']) || $params['group'][$key['group_id']] != 1) && empty($key['is_hidden'])) {
                     $params['group'][$key['group_id']] = -1;
                 }
             }
         }
     }
     // parse street address, CRM-5450
     $parseStatusMsg = NULL;
     if ($this->_parseStreetAddress) {
         $parseResult = self::parseAddress($params);
         $parseStatusMsg = self::parseAddressStatusMsg($parseResult);
     }
     // Allow un-setting of location info, CRM-5969
     $params['updateBlankLocInfo'] = TRUE;
     $contact = CRM_Contact_BAO_Contact::create($params, TRUE, FALSE, TRUE);
     // status message
     if ($this->_contactId) {
         $message = ts('%1 has been updated.', array(1 => $contact->display_name));
     } else {
         $message = ts('%1 has been created.', array(1 => $contact->display_name));
     }
     // set the contact ID
     $this->_contactId = $contact->id;
     if (array_key_exists('TagsAndGroups', $this->_editOptions)) {
         //add contact to tags
         CRM_Core_BAO_EntityTag::create($params['tag'], 'civicrm_contact', $params['contact_id']);
         //save free tags
         if (isset($params['contact_taglist']) && !empty($params['contact_taglist'])) {
             CRM_Core_Form_Tag::postProcess($params['contact_taglist'], $params['contact_id'], 'civicrm_contact', $this);
         }
     }
     if (!empty($parseStatusMsg)) {
         $message .= "<br />{$parseStatusMsg}";
     }
     if (!empty($updateMembershipMsg)) {
         $message .= "<br />{$updateMembershipMsg}";
     }
     $session = CRM_Core_Session::singleton();
     $session->setStatus($message, ts('Contact Saved'), 'success');
     // add the recently viewed contact
     $recentOther = array();
     if ($session->get('userID') == $contact->id || CRM_Contact_BAO_Contact_Permission::allow($contact->id, CRM_Core_Permission::EDIT)) {
         $recentOther['editUrl'] = CRM_Utils_System::url('civicrm/contact/add', 'reset=1&action=update&cid=' . $contact->id);
     }
     if ($session->get('userID') != $this->_contactId && CRM_Core_Permission::check('delete contacts')) {
         $recentOther['deleteUrl'] = CRM_Utils_System::url('civicrm/contact/view/delete', 'reset=1&delete=1&cid=' . $contact->id);
     }
     CRM_Utils_Recent::add($contact->display_name, CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $contact->id), $contact->id, $this->_contactType, $contact->id, $contact->display_name, $recentOther);
     // here we replace the user context with the url to view this contact
     $buttonName = $this->controller->getButtonName();
     if ($buttonName == $this->getButtonName('upload', 'new')) {
         $contactSubTypes = array_filter(explode(CRM_Core_DAO::VALUE_SEPARATOR, $this->_contactSubType));
         $resetStr = "reset=1&ct={$contact->contact_type}";
         $resetStr .= count($contactSubTypes) == 1 ? "&cst=" . array_pop($contactSubTypes) : '';
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/add', $resetStr));
     } else {
         $context = CRM_Utils_Request::retrieve('context', 'String', $this);
         $qfKey = CRM_Utils_Request::retrieve('key', 'String', $this);
         //validate the qfKey
         $urlParams = 'reset=1&cid=' . $contact->id;
         if ($context) {
             $urlParams .= "&context={$context}";
         }
         if (CRM_Utils_Rule::qfKey($qfKey)) {
             $urlParams .= "&key={$qfKey}";
         }
         $session->replaceUserContext(CRM_Utils_System::url('civicrm/contact/view', $urlParams));
     }
     // now invoke the post hook
     if ($this->_action & CRM_Core_Action::UPDATE) {
         CRM_Utils_Hook::post('edit', $params['contact_type'], $contact->id, $contact);
     } else {
         CRM_Utils_Hook::post('create', $params['contact_type'], $contact->id, $contact);
     }
 }
Example #30
0
 /**
  * takes an associative array and creates / removes
  * contacts from the groups
  *
  *
  * @param array $params (reference ) an assoc array of name/value pairs
  * @param array $contactId    contact id
  *
  * @return none
  * @access public
  * @static
  */
 static function create(&$params, $contactId, $visibility = false, $method = 'Admin')
 {
     $contactIds = array();
     $contactIds[] = $contactId;
     if ($contactId) {
         $contactGroupList =& CRM_Contact_BAO_GroupContact::getContactGroup($contactId, 'Added');
         if (is_array($contactGroupList)) {
             foreach ($contactGroupList as $key) {
                 $groupId = $key['group_id'];
                 $contactGroup[$groupId] = $groupId;
             }
         }
     }
     // get the list of all the groups
     $allGroup =& CRM_Contact_BAO_GroupContact::getGroupList(0, $visibility);
     // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
     if (!is_array($params)) {
         $params = array();
     }
     // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input
     if (!isset($contactGroup) || !is_array($contactGroup)) {
         $contactGroup = array();
     }
     // check which values has to be add/remove contact from group
     foreach ($allGroup as $key => $varValue) {
         if (CRM_Utils_Array::value($key, $params) && !array_key_exists($key, $contactGroup)) {
             // add contact to group
             CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $key, $method);
         } else {
             if (!CRM_Utils_Array::value($key, $params) && array_key_exists($key, $contactGroup)) {
                 // remove contact from group
                 CRM_Contact_BAO_GroupContact::removeContactsFromGroup($contactIds, $key, $method);
             }
         }
     }
 }