Example #1
0
 /**
  * Class constructor.
  *
  * @param int $id
  *   The contact id.
  * @param int $gid
  *   The group id.
  *
  * @param $restrict
  * @param bool $skipPermission
  * @param null $profileIds
  *
  * @return \CRM_Profile_Page_Dynamic
  */
 public function __construct($id, $gid, $restrict, $skipPermission = FALSE, $profileIds = NULL)
 {
     parent::__construct();
     $this->_id = $id;
     $this->_gid = $gid;
     $this->_restrict = $restrict;
     $this->_skipPermission = $skipPermission;
     if (!array_key_exists('multiRecord', $_GET)) {
         $this->set('multiRecord', NULL);
     }
     if (!array_key_exists('recordId', $_GET)) {
         $this->set('recordId', NULL);
     }
     if (!array_key_exists('allFields', $_GET)) {
         $this->set('allFields', NULL);
     }
     //specifies the action being done on a multi record field
     $multiRecordAction = CRM_Utils_Request::retrieve('multiRecord', 'String', $this);
     $this->_multiRecord = !is_numeric($multiRecordAction) ? CRM_Core_Action::resolve($multiRecordAction) : $multiRecordAction;
     if ($this->_multiRecord) {
         $this->set('multiRecord', $this->_multiRecord);
     }
     if ($this->_multiRecord & CRM_Core_Action::VIEW) {
         $this->_recordId = CRM_Utils_Request::retrieve('recordId', 'Positive', $this);
         $this->_allFields = CRM_Utils_Request::retrieve('allFields', 'Integer', $this);
     }
     if ($profileIds) {
         $this->_profileIds = $profileIds;
     } else {
         $this->_profileIds = array($gid);
     }
     $this->_activityId = CRM_Utils_Request::retrieve('aid', 'Positive', $this, FALSE, 0, 'GET');
     if (is_numeric($this->_activityId)) {
         $latestRevisionId = CRM_Activity_BAO_Activity::getLatestActivityId($this->_activityId);
         if ($latestRevisionId) {
             $this->_activityId = $latestRevisionId;
         }
     }
     $this->_isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($this->_gid);
 }
Example #2
0
 /**
  * Get all the fields that belong to the group with the name title,
  * and format for use with buildProfile. This is the SQL analog of
  * formatUFFields().
  *
  * @param mix $id
  *   The id of the UF group or ids of ufgroup.
  * @param bool|int $register are we interested in registration fields
  * @param int $action
  *   What action are we doing.
  * @param int $visibility
  *   Visibility of fields we are interested in.
  * @param $searchable
  * @param bool $showAll
  * @param string $restrict
  *   Should we restrict based on a specified profile type.
  * @param bool $skipPermission
  * @param null $ctype
  * @param int $permissionType
  * @param string $orderBy
  * @param null $orderProfiles
  *
  * @return array
  *   the fields that belong to this ufgroup(s)
  */
 public static function getFields($id, $register = FALSE, $action = NULL, $visibility = NULL, $searchable = NULL, $showAll = FALSE, $restrict = NULL, $skipPermission = FALSE, $ctype = NULL, $permissionType = CRM_Core_Permission::CREATE, $orderBy = 'field_name', $orderProfiles = NULL, $eventProfile = FALSE)
 {
     if (!is_array($id)) {
         $id = CRM_Utils_Type::escape($id, 'Positive');
         $profileIds = array($id);
     } else {
         $profileIds = $id;
     }
     $gids = implode(',', $profileIds);
     $params = array();
     if ($restrict) {
         $query = "SELECT g.* from civicrm_uf_group g\n                LEFT JOIN civicrm_uf_join j ON (j.uf_group_id = g.id)\n                WHERE g.id IN ( {$gids} )\n                AND ((j.uf_group_id IN ( {$gids} ) AND j.module = %1) OR g.is_reserved = 1 )\n                ";
         $params = array(1 => array($restrict, 'String'));
     } else {
         $query = "SELECT g.* from civicrm_uf_group g WHERE g.id IN ( {$gids} ) ";
     }
     if (!$showAll) {
         $query .= " AND g.is_active = 1";
     }
     $checkPermission = array(array('administer CiviCRM', 'manage event profiles'));
     if ($eventProfile && CRM_Core_Permission::check($checkPermission)) {
         $skipPermission = TRUE;
     }
     // add permissioning for profiles only if not registration
     if (!$skipPermission) {
         $permissionClause = CRM_Core_Permission::ufGroupClause($permissionType, 'g.');
         $query .= " AND {$permissionClause} ";
     }
     if ($orderProfiles and count($profileIds) > 1) {
         $query .= " ORDER BY FIELD(  g.id, {$gids} )";
     }
     $group = CRM_Core_DAO::executeQuery($query, $params);
     $fields = array();
     $validGroup = FALSE;
     while ($group->fetch()) {
         $validGroup = TRUE;
         $query = self::createUFFieldQuery($group->id, $searchable, $showAll, $visibility, $orderBy);
         $field = CRM_Core_DAO::executeQuery($query);
         $profileType = CRM_Core_BAO_UFField::getProfileType($group->id);
         $contactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($group->id);
         $importableFields = self::getImportableFields($showAll, $profileType, $contactActivityProfile);
         list($customFields, $addressCustomFields) = self::getCustomFields($ctype);
         while ($field->fetch()) {
             list($name, $formattedField) = self::formatUFField($group, $field, $customFields, $addressCustomFields, $importableFields, $permissionType);
             if ($formattedField !== NULL) {
                 $fields[$name] = $formattedField;
             }
         }
         $field->free();
     }
     if (empty($fields) && !$validGroup) {
         CRM_Core_Error::fatal(ts('The requested Profile (gid=%1) is disabled OR it is not configured to be used for \'Profile\' listings in its Settings OR there is no Profile with that ID OR you do not have permission to access this profile. Please contact the site administrator if you need assistance.', array(1 => implode(',', $profileIds))));
     } else {
         self::reformatProfileFields($fields);
     }
     return $fields;
 }
Example #3
0
 /**
  * Pre processing work done here.
  *
  * gets session variables for table name, id of entity in table, type of entity and stores them.
  *
  * @param
  *
  * @return void
  */
 public function preProcess()
 {
     $this->_id = $this->get('id');
     $this->_profileIds = $this->get('profileIds');
     $this->_grid = CRM_Utils_Request::retrieve('grid', 'Integer', $this);
     $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
     //unset from session when $_GET doesn't have it
     //except when the form is submitted
     if (empty($_POST)) {
         if (!array_key_exists('multiRecord', $_GET)) {
             $this->set('multiRecord', NULL);
         }
         if (!array_key_exists('recordId', $_GET)) {
             $this->set('recordId', NULL);
         }
     }
     $this->_session = CRM_Core_Session::singleton();
     $this->_currentUserID = $this->_session->get('userID');
     if ($this->_mode == self::MODE_EDIT) {
         //specifies the action being done on a multi record field
         $multiRecordAction = CRM_Utils_Request::retrieve('multiRecord', 'String', $this);
         $this->_multiRecord = !is_numeric($multiRecordAction) ? CRM_Core_Action::resolve($multiRecordAction) : $multiRecordAction;
         if ($this->_multiRecord) {
             $this->set('multiRecord', $this->_multiRecord);
         }
         if ($this->_multiRecord && !in_array($this->_multiRecord, array(CRM_Core_Action::UPDATE, CRM_Core_Action::ADD, CRM_Core_Action::DELETE))) {
             CRM_Core_Error::fatal(ts('Proper action not specified for this custom value record profile'));
         }
     }
     $this->_duplicateButtonName = $this->getButtonName('upload', 'duplicate');
     $gids = explode(',', CRM_Utils_Request::retrieve('gid', 'String', CRM_Core_DAO::$_nullObject, FALSE, 0));
     if (count($gids) > 1 && !$this->_profileIds && empty($this->_profileIds)) {
         if (!empty($gids)) {
             foreach ($gids as $pfId) {
                 $this->_profileIds[] = CRM_Utils_Type::escape($pfId, 'Positive');
             }
         }
         // check if we are rendering mixed profiles
         if (CRM_Core_BAO_UFGroup::checkForMixProfiles($this->_profileIds)) {
             CRM_Core_Error::fatal(ts('You cannot combine profiles of multiple types.'));
         }
         // for now consider 1'st profile as primary profile and validate it
         // i.e check for profile type etc.
         // FIX ME: validations for other than primary
         $this->_gid = $this->_profileIds[0];
         $this->set('gid', $this->_gid);
         $this->set('profileIds', $this->_profileIds);
     }
     if (!$this->_gid) {
         $this->_gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, FALSE, 0);
         $this->set('gid', $this->_gid);
     }
     $this->_activityId = CRM_Utils_Request::retrieve('aid', 'Positive', $this, FALSE, 0, 'GET');
     if (is_numeric($this->_activityId)) {
         $latestRevisionId = CRM_Activity_BAO_Activity::getLatestActivityId($this->_activityId);
         if ($latestRevisionId) {
             $this->_activityId = $latestRevisionId;
         }
     }
     $this->_isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($this->_gid);
     //get values for ufGroupName, captch and dupe update.
     if ($this->_gid) {
         $dao = new CRM_Core_DAO_UFGroup();
         $dao->id = $this->_gid;
         if ($dao->find(TRUE)) {
             $this->_isUpdateDupe = $dao->is_update_dupe;
             $this->_isAddCaptcha = $dao->add_captcha;
             $this->_ufGroup = (array) $dao;
         }
         $dao->free();
         if (!CRM_Utils_Array::value('is_active', $this->_ufGroup)) {
             CRM_Core_Error::fatal(ts('The requested profile (gid=%1) is inactive or does not exist.', array(1 => $this->_gid)));
         }
     }
     $this->assign('ufGroupName', $this->_ufGroup['name']);
     $gids = empty($this->_profileIds) ? $this->_gid : $this->_profileIds;
     // if we dont have a gid use the default, else just use that specific gid
     if (($this->_mode == self::MODE_REGISTER || $this->_mode == self::MODE_CREATE) && !$this->_gid) {
         $this->_ctype = CRM_Utils_Request::retrieve('ctype', 'String', $this, FALSE, 'Individual', 'REQUEST');
         $this->_fields = CRM_Core_BAO_UFGroup::getRegistrationFields($this->_action, $this->_mode, $this->_ctype);
     } elseif ($this->_mode == self::MODE_SEARCH) {
         $this->_fields = CRM_Core_BAO_UFGroup::getListingFields($this->_action, CRM_Core_BAO_UFGroup::PUBLIC_VISIBILITY | CRM_Core_BAO_UFGroup::LISTINGS_VISIBILITY, FALSE, $gids, TRUE, NULL, $this->_skipPermission, CRM_Core_Permission::SEARCH);
     } else {
         $this->_fields = CRM_Core_BAO_UFGroup::getFields($gids, FALSE, NULL, NULL, NULL, FALSE, NULL, $this->_skipPermission, NULL, $this->_action == CRM_Core_Action::ADD ? CRM_Core_Permission::CREATE : CRM_Core_Permission::EDIT);
         $multiRecordFieldListing = FALSE;
         //using selector for listing of multirecord fields
         if ($this->_mode == self::MODE_EDIT && $this->_gid) {
             CRM_Core_BAO_UFGroup::shiftMultiRecordFields($this->_fields, $this->_multiRecordFields);
             if ($this->_multiRecord) {
                 if ($this->_multiRecord != CRM_Core_Action::ADD) {
                     $this->_recordId = CRM_Utils_Request::retrieve('recordId', 'Positive', $this);
                 } else {
                     $this->_recordId = NULL;
                     $this->set('recordId', NULL);
                 }
                 //record id is necessary for _multiRecord view and update/edit action
                 if (!$this->_recordId && ($this->_multiRecord == CRM_Core_Action::UPDATE || $this->_multiRecord == CRM_Core_Action::DELETE)) {
                     CRM_Core_Error::fatal(ts('The requested Profile (gid=%1) requires record id while performing this action', array(1 => $this->_gid)));
                 } elseif (empty($this->_multiRecordFields)) {
                     CRM_Core_Error::fatal(ts('No Multi-Record Fields configured for this profile (gid=%1)', array(1 => $this->_gid)));
                 }
                 $fieldId = CRM_Core_BAO_CustomField::getKeyID(key($this->_multiRecordFields));
                 $customGroupDetails = CRM_Core_BAO_CustomGroup::getGroupTitles(array($fieldId));
                 $this->_customGroupTitle = $customGroupDetails[$fieldId]['groupTitle'];
                 $this->_customGroupId = $customGroupDetails[$fieldId]['groupID'];
                 if ($this->_multiRecord == CRM_Core_Action::UPDATE || $this->_multiRecord == CRM_Core_Action::DELETE) {
                     //record exists check
                     foreach ($this->_multiRecordFields as $key => $field) {
                         $fieldIds[] = CRM_Core_BAO_CustomField::getKeyID($key);
                     }
                     $getValues = CRM_Core_BAO_CustomValueTable::getEntityValues($this->_id, NULL, $fieldIds, TRUE);
                     if (array_key_exists($this->_recordId, $getValues)) {
                         $this->_recordExists = TRUE;
                     } else {
                         $this->_recordExists = FALSE;
                         if ($this->_multiRecord & CRM_Core_Action::UPDATE) {
                             CRM_Core_Session::setStatus(ts('Note: The record %1 doesnot exists. Upon save a new record will be create', array(1 => $this->_recordId)), ts('Record doesnot exist'), 'alert');
                         }
                     }
                 }
                 if ($this->_multiRecord & CRM_Core_Action::ADD) {
                     $this->_maxRecordLimit = CRM_Core_BAO_CustomGroup::hasReachedMaxLimit($customGroupDetails[$fieldId]['groupID'], $this->_id);
                     if ($this->_maxRecordLimit) {
                         CRM_Core_Session::setStatus(ts('You cannot add a new record as  maximum allowed limit is reached'), ts('Sorry'), 'error');
                     }
                 }
             } elseif (!empty($this->_multiRecordFields) && (!$this->_multiRecord || !in_array($this->_multiRecord, array(CRM_Core_Action::DELETE, CRM_Core_Action::UPDATE)))) {
                 CRM_Core_Resources::singleton()->addScriptFile('civicrm', 'js/crm.livePage.js', 1, 'html-header');
                 //multirecord listing page
                 $multiRecordFieldListing = TRUE;
                 $page = new CRM_Profile_Page_MultipleRecordFieldsListing();
                 $cs = $this->get('cs');
                 $page->set('pageCheckSum', $cs);
                 $page->set('contactId', $this->_id);
                 $page->set('profileId', $this->_gid);
                 $page->set('action', CRM_Core_Action::BROWSE);
                 $page->set('multiRecordFieldListing', $multiRecordFieldListing);
                 $page->run();
             }
         }
         $this->assign('multiRecordFieldListing', $multiRecordFieldListing);
         // is profile double-opt in?
         if (!empty($this->_fields['group']) && CRM_Core_BAO_UFGroup::isProfileDoubleOptin()) {
             $emailField = FALSE;
             foreach ($this->_fields as $name => $values) {
                 if (substr($name, 0, 6) == 'email-') {
                     $emailField = TRUE;
                 }
             }
             if (!$emailField) {
                 $status = ts("Email field should be included in profile if you want to use Group(s) when Profile double-opt in process is enabled.");
                 $this->_session->setStatus($status);
             }
         }
         //transferring all the multi-record custom fields in _fields
         if ($this->_multiRecord && !empty($this->_multiRecordFields)) {
             $this->_fields = $this->_multiRecordFields;
             $this->_multiRecordProfile = TRUE;
         } elseif ($this->_multiRecord && empty($this->_multiRecordFields)) {
             CRM_Core_Session::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
             CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm', 'reset=1'));
         }
     }
     if (!is_array($this->_fields)) {
         CRM_Core_Session::setStatus(ts('This feature is not currently available.'), ts('Sorry'), 'error');
         CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm', 'reset=1'));
     }
 }
Example #4
0
/**
 * Submit a set of fields against a profile.
 *
 * Note choice of submit versus create is discussed CRM-13234 & related to the fact
 * 'profile' is being treated as a data-entry entity
 *
 * @param array $params
 *
 * @throws API_Exception
 * @return array
 *   API result array
 */
function civicrm_api3_profile_submit($params)
{
    $profileID = _civicrm_api3_profile_getProfileID($params['profile_id']);
    if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'is_active')) {
        //@todo declare pseudoconstant & let api do this
        throw new API_Exception('Invalid value for profile_id');
    }
    $isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($profileID);
    if (!empty($params['id']) && CRM_Core_BAO_UFField::checkProfileType($profileID) && !$isContactActivityProfile) {
        throw new API_Exception('Update profiles including more than one entity not currently supported');
    }
    $contactParams = $activityParams = $missingParams = array();
    $profileFields = civicrm_api3('Profile', 'getfields', array('action' => 'submit', 'profile_id' => $profileID));
    $profileFields = $profileFields['values'];
    if ($isContactActivityProfile) {
        civicrm_api3_verify_mandatory($params, NULL, array('activity_id'));
        $errors = CRM_Profile_Form::validateContactActivityProfile($params['activity_id'], $params['contact_id'], $profileID);
        if (!empty($errors)) {
            throw new API_Exception(array_pop($errors));
        }
    }
    foreach ($profileFields as $fieldName => $field) {
        if (!isset($params[$fieldName])) {
            continue;
        }
        $value = $params[$fieldName];
        if ($params[$fieldName] && isset($params[$fieldName . '_id'])) {
            $value = $params[$fieldName . '_id'];
        }
        $contactEntities = array('contact', 'individual', 'organization', 'household');
        $locationEntities = array('email', 'address', 'phone', 'website', 'im');
        $entity = strtolower(CRM_Utils_Array::value('entity', $field));
        if ($entity && !in_array($entity, array_merge($contactEntities, $locationEntities))) {
            $contactParams['api.' . $entity . '.create'][$fieldName] = $value;
            //@todo we are not currently declaring this option
            if (isset($params['batch_id']) && strtolower($entity) == 'contribution') {
                $contactParams['api.' . $entity . '.create']['batch_id'] = $params['batch_id'];
            }
            if (isset($params[$entity . '_id'])) {
                //todo possibly declare $entity_id in getfields ?
                $contactParams['api.' . $entity . '.create']['id'] = $params[$entity . '_id'];
            }
        } else {
            $contactParams[_civicrm_api3_profile_translate_fieldnames_for_bao($fieldName)] = $value;
        }
    }
    if (isset($contactParams['api.contribution.create']) && isset($contactParams['api.membership.create'])) {
        $contactParams['api.membership_payment.create'] = array('contribution_id' => '$value.api.contribution.create.id', 'membership_id' => '$value.api.membership.create.id');
    }
    if (isset($contactParams['api.contribution.create']) && isset($contactParams['api.participant.create'])) {
        $contactParams['api.participant_payment.create'] = array('contribution_id' => '$value.api.contribution.create.id', 'participant_id' => '$value.api.participant.create.id');
    }
    $contactParams['contact_id'] = CRM_Utils_Array::value('contact_id', $params);
    $contactParams['profile_id'] = $profileID;
    $contactParams['skip_custom'] = 1;
    $contactProfileParams = civicrm_api3_profile_apply($contactParams);
    // Contact profile fields
    $profileParams = $contactProfileParams['values'];
    // If profile having activity fields
    if ($isContactActivityProfile && !empty($activityParams)) {
        $activityParams['id'] = $params['activity_id'];
        $profileParams['api.activity.create'] = $activityParams;
    }
    return civicrm_api3('contact', 'create', $profileParams);
}
 /**
  * get all the fields that belong to the group with the name title
  *
  * @param mix      $id           the id of the UF group or ids of ufgroup
  * @param int      $register     are we interested in registration fields
  * @param int      $action       what action are we doing
  * @param int      $visibility   visibility of fields we are interested in
  * @param          $searchable
  * @param boolean  $showall
  * @param string   $restrict     should we restrict based on a specified profile type
  *
  * @return array   the fields that belong to this ufgroup(s)
  * @static
  * @access public
  */
 static function getFields($id, $register = FALSE, $action = NULL, $visibility = NULL, $searchable = NULL, $showAll = FALSE, $restrict = NULL, $skipPermission = FALSE, $ctype = NULL, $permissionType = CRM_Core_Permission::CREATE, $orderBy = 'field_name', $orderProfiles = NULL)
 {
     if (!is_array($id)) {
         $id = CRM_Utils_Type::escape($id, 'Positive');
         $profileIds = array($id);
     } else {
         $profileIds = $id;
     }
     $gids = implode(',', $profileIds);
     $params = array();
     if ($restrict) {
         $query = "SELECT g.* from civicrm_uf_group g, civicrm_uf_join j\n                WHERE g.id IN ( {$gids} )\n                AND j.uf_group_id IN ( {$gids} )\n                AND j.module      = %1\n                ";
         $params = array(1 => array($restrict, 'String'));
     } else {
         $query = "SELECT g.* from civicrm_uf_group g WHERE g.id IN ( {$gids} ) ";
     }
     if (!$showAll) {
         $query .= " AND g.is_active = 1";
     }
     // add permissioning for profiles only if not registration
     if (!$skipPermission) {
         $permissionClause = CRM_Core_Permission::ufGroupClause($permissionType, 'g.');
         $query .= " AND {$permissionClause} ";
     }
     if ($orderProfiles and count($profileIds) > 1) {
         $query .= " ORDER BY FIELD(  g.id, {$gids} )";
     }
     $group = CRM_Core_DAO::executeQuery($query, $params);
     $fields = array();
     $validGroup = FALSE;
     while ($group->fetch()) {
         $validGroup = TRUE;
         $where = " WHERE uf_group_id = {$group->id}";
         if ($searchable) {
             $where .= " AND is_searchable = 1";
         }
         if (!$showAll) {
             $where .= " AND is_active = 1";
         }
         if ($visibility) {
             $clause = array();
             if ($visibility & self::PUBLIC_VISIBILITY) {
                 $clause[] = 'visibility = "Public Pages"';
             }
             if ($visibility & self::ADMIN_VISIBILITY) {
                 $clause[] = 'visibility = "User and User Admin Only"';
             }
             if ($visibility & self::LISTINGS_VISIBILITY) {
                 $clause[] = 'visibility = "Public Pages and Listings"';
             }
             if (!empty($clause)) {
                 $where .= ' AND ( ' . implode(' OR ', $clause) . ' ) ';
             }
         }
         $query = "SELECT * FROM civicrm_uf_field {$where} ORDER BY weight";
         if ($orderBy) {
             $query .= ", " . $orderBy;
         }
         $field = CRM_Core_DAO::executeQuery($query);
         if (!$showAll) {
             $importableFields = CRM_Contact_BAO_Contact::importableFields('All');
         } else {
             $importableFields = CRM_Contact_BAO_Contact::importableFields('All', FALSE, TRUE);
         }
         $profileType = CRM_Core_BAO_UFField::getProfileType($group->id);
         $contactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($group->id);
         if ($profileType == 'Activity' || $contactActivityProfile) {
             $componentFields = CRM_Activity_BAO_Activity::getProfileFields();
         } else {
             $componentFields = CRM_Core_Component::getQueryFields();
         }
         $importableFields = array_merge($importableFields, $componentFields);
         $importableFields['group']['title'] = ts('Group(s)');
         $importableFields['group']['where'] = NULL;
         $importableFields['tag']['title'] = ts('Tag(s)');
         $importableFields['tag']['where'] = NULL;
         $locationFields = array('street_address', 'supplemental_address_1', 'supplemental_address_2', 'city', 'postal_code', 'postal_code_suffix', 'geo_code_1', 'geo_code_2', 'state_province', 'country', 'county', 'phone', 'email', 'im', 'address_name');
         //get location type
         $locationType = array();
         $locationType = CRM_Core_PseudoConstant::locationType();
         $customFields = CRM_Core_BAO_CustomField::getFieldsForImport($ctype);
         // hack to add custom data for components
         $components = array('Contribution', 'Participant', 'Membership', 'Activity');
         foreach ($components as $value) {
             $customFields = array_merge($customFields, CRM_Core_BAO_CustomField::getFieldsForImport($value));
         }
         $addressCustomFields = CRM_Core_BAO_CustomField::getFieldsForImport('Address');
         $customFields = array_merge($customFields, $addressCustomFields);
         while ($field->fetch()) {
             $name = $title = $locType = $phoneType = '';
             $name = $field->field_name;
             $title = $field->label;
             $addressCustom = FALSE;
             if (in_array($permissionType, array(CRM_Core_Permission::CREATE, CRM_Core_Permission::EDIT)) && in_array($field->field_name, array_keys($addressCustomFields))) {
                 $addressCustom = TRUE;
                 $name = "address_{$name}";
             }
             if ($field->location_type_id) {
                 $name .= "-{$field->location_type_id}";
                 $locType = " ( {$locationType[$field->location_type_id]} ) ";
             } else {
                 if (in_array($field->field_name, $locationFields) || $addressCustom) {
                     $name .= '-Primary';
                     $locType = ' ( Primary ) ';
                 }
             }
             if (isset($field->phone_type_id)) {
                 $name .= "-{$field->phone_type_id}";
                 // this hack is to prevent Phone Phone (work)
                 if ($field->phone_type_id != '1') {
                     $phoneType = "-{$field->phone_type_id}";
                 }
             }
             $fields[$name] = array('name' => $name, 'groupTitle' => $group->title, 'groupHelpPre' => $group->help_pre, 'groupHelpPost' => $group->help_post, 'title' => $title, 'where' => CRM_Utils_Array::value('where', CRM_Utils_Array::value($field->field_name, $importableFields)), 'attributes' => CRM_Core_DAO::makeAttribute(CRM_Utils_Array::value($field->field_name, $importableFields)), 'is_required' => $field->is_required, 'is_view' => $field->is_view, 'help_pre' => $field->help_pre, 'help_post' => $field->help_post, 'visibility' => $field->visibility, 'in_selector' => $field->in_selector, 'rule' => CRM_Utils_Array::value('rule', CRM_Utils_Array::value($field->field_name, $importableFields)), 'location_type_id' => $field->location_type_id, 'phone_type_id' => isset($field->phone_type_id) ? $field->phone_type_id : NULL, 'group_id' => $group->id, 'add_to_group_id' => $group->add_to_group_id, 'add_captcha' => $group->add_captcha, 'field_type' => $field->field_type, 'field_id' => $field->id);
             //adding custom field property
             if (substr($field->field_name, 0, 6) == 'custom' || substr($field->field_name, 0, 14) === 'address_custom') {
                 // if field is not present in customFields, that means the user
                 // DOES NOT HAVE permission to access that field
                 if (array_key_exists($field->field_name, $customFields)) {
                     $fields[$name]['is_search_range'] = $customFields[$field->field_name]['is_search_range'];
                     // fix for CRM-1994
                     $fields[$name]['options_per_line'] = $customFields[$field->field_name]['options_per_line'];
                     $fields[$name]['data_type'] = $customFields[$field->field_name]['data_type'];
                     $fields[$name]['html_type'] = $customFields[$field->field_name]['html_type'];
                     if (CRM_Utils_Array::value('html_type', $fields[$name]) == 'Select Date') {
                         $fields[$name]['date_format'] = $customFields[$field->field_name]['date_format'];
                         $fields[$name]['time_format'] = $customFields[$field->field_name]['time_format'];
                     }
                 } else {
                     unset($fields[$name]);
                 }
             }
         }
         $field->free();
     }
     if (empty($fields) && !$validGroup) {
         CRM_Core_Error::fatal(ts('The requested Profile (gid=%1) is disabled OR it is not configured to be used for \'Profile\' listings in its Settings OR there is no Profile with that ID OR you do not have permission to access this profile. Please contact the site administrator if you need assistance.', array(1 => implode(',', $profileIds))));
     }
     return $fields;
 }
 /**
  * class constructor
  *
  * @param int $id  the contact id
  * @param int $gid the group id
  *
  * @return void
  * @access public
  */
 function __construct($id, $gid, $restrict, $skipPermission = FALSE, $profileIds = NULL)
 {
     parent::__construct();
     $this->_id = $id;
     $this->_gid = $gid;
     $this->_restrict = $restrict;
     $this->_skipPermission = $skipPermission;
     if ($profileIds) {
         $this->_profileIds = $profileIds;
     } else {
         $this->_profileIds = array($gid);
     }
     $this->_activityId = CRM_Utils_Request::retrieve('aid', 'Positive', $this, FALSE, 0, 'GET');
     if (is_numeric($this->_activityId)) {
         $latestRevisionId = CRM_Activity_BAO_Activity::getLatestActivityId($this->_activityId);
         if ($latestRevisionId) {
             $this->_activityId = $latestRevisionId;
         }
     }
     $this->_isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($this->_gid);
 }
/**
 * Update Profile field values.
 *
 * @param array  $params       Associative array of property name/value
 *                             pairs to update profile field values
 *
 * @return Updated Contact/ Activity object|CRM_Error
 *
 * @todo add example
 * @todo add test cases
 *
 */
function civicrm_api3_profile_set($params)
{
    civicrm_api3_verify_mandatory($params, NULL, array('profile_id'));
    if (!CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $params['profile_id'], 'is_active')) {
        return civicrm_api3_create_error('Invalid value for profile_id');
    }
    $isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($params['profile_id']);
    if (CRM_Core_BAO_UFField::checkProfileType($params['profile_id']) && !$isContactActivityProfile) {
        return civicrm_api3_create_error('Can not retrieve values for profiles include fields for more than one record type.');
    }
    $contactParams = $activityParams = $missingParams = array();
    $profileFields = CRM_Core_BAO_UFGroup::getFields($params['profile_id'], FALSE, NULL, NULL, NULL, FALSE, NULL, TRUE, NULL, CRM_Core_Permission::EDIT);
    if ($isContactActivityProfile) {
        civicrm_api3_verify_mandatory($params, NULL, array('activity_id'));
        require_once 'CRM/Profile/Form.php';
        $errors = CRM_Profile_Form::validateContactActivityProfile($params['activity_id'], $params['contact_id'], $params['profile_id']);
        if (!empty($errors)) {
            return civicrm_api3_create_error(array_pop($errors));
        }
    }
    foreach ($profileFields as $fieldName => $field) {
        if (CRM_Utils_Array::value('is_required', $field)) {
            if (!CRM_Utils_Array::value($fieldName, $params) || empty($params[$fieldName])) {
                $missingParams[] = $fieldName;
            }
        }
        if (!isset($params[$fieldName])) {
            continue;
        }
        $value = $params[$fieldName];
        if ($params[$fieldName] && isset($params[$fieldName . '_id'])) {
            $value = $params[$fieldName . '_id'];
        }
        if ($isContactActivityProfile && CRM_Utils_Array::value('field_type', $field) == 'Activity') {
            $activityParams[$fieldName] = $value;
        } else {
            $contactParams[$fieldName] = $value;
        }
    }
    if (!empty($missingParams)) {
        return civicrm_api3_create_error("Missing required parameters for profile id {$params['profile_id']}: " . implode(', ', $missingParams));
    }
    $contactParams['version'] = 3;
    $contactParams['contact_id'] = CRM_Utils_Array::value('contact_id', $params);
    $contactParams['profile_id'] = $params['profile_id'];
    $contactParams['skip_custom'] = 1;
    $contactProfileParams = civicrm_api3_profile_apply($contactParams);
    if (CRM_Utils_Array::value('is_error', $contactProfileParams)) {
        return $contactProfileParams;
    }
    // Contact profile fields
    $profileParams = $contactProfileParams['values'];
    // If profile having activity fields
    if ($isContactActivityProfile && !empty($activityParams)) {
        $activityParams['id'] = $params['activity_id'];
        $profileParams['api.activity.create'] = $activityParams;
    }
    $groups = $tags = array();
    if (isset($profileParams['group'])) {
        $groups = $profileParams['group'];
        unset($profileParams['group']);
    }
    if (isset($profileParams['tag'])) {
        $tags = $profileParams['tag'];
        unset($profileParams['tag']);
    }
    $result = civicrm_api('contact', 'create', $profileParams);
    if (CRM_Utils_Array::value('is_error', $result)) {
        return $result;
    }
    $ufGroupDetails = array();
    $ufGroupParams = array('id' => $params['profile_id']);
    CRM_Core_BAO_UFGroup::retrieve($ufGroupParams, $ufGroupDetails);
    if (isset($profileFields['group'])) {
        CRM_Contact_BAO_GroupContact::create($groups, $params['contact_id'], FALSE, 'Admin');
    }
    if (isset($profileFields['tag'])) {
        require_once 'CRM/Core/BAO/EntityTag.php';
        CRM_Core_BAO_EntityTag::create($tags, 'civicrm_contact', $params['contact_id']);
    }
    if (CRM_Utils_Array::value('add_to_group_id', $ufGroupDetails)) {
        $contactIds = array($params['contact_id']);
        CRM_Contact_BAO_GroupContact::addContactsToGroup($contactIds, $ufGroupDetails['add_to_group_id']);
    }
    return $result;
}
 /**
  * pre processing work done here.
  *
  * gets session variables for table name, id of entity in table, type of entity and stores them.
  *
  * @param
  *
  * @return void
  *
  * @access public
  */
 function preProcess()
 {
     $this->_id = $this->get('id');
     $this->_gid = $this->get('gid');
     $this->_profileIds = $this->get('profileIds');
     $this->_grid = CRM_Utils_Request::retrieve('grid', 'Integer', $this);
     $this->_context = CRM_Utils_Request::retrieve('context', 'String', $this);
     $this->_duplicateButtonName = $this->getButtonName('upload', 'duplicate');
     $gids = explode(',', CRM_Utils_Request::retrieve('gid', 'String', CRM_Core_DAO::$_nullObject, FALSE, 0, 'GET'));
     if (count($gids) > 1 && !$this->_profileIds && empty($this->_profileIds)) {
         if (!empty($gids)) {
             foreach ($gids as $pfId) {
                 $this->_profileIds[] = CRM_Utils_Type::escape($pfId, 'Positive');
             }
         }
         // check if we are rendering mixed profiles
         if (CRM_Core_BAO_UFGroup::checkForMixProfiles($this->_profileIds)) {
             CRM_Core_Error::fatal(ts('You cannot combine profiles of multiple types.'));
         }
         // for now consider 1'st profile as primary profile and validate it
         // i.e check for profile type etc.
         // FIX ME: validations for other than primary
         $this->_gid = $this->_profileIds[0];
         $this->set('gid', $this->_gid);
         $this->set('profileIds', $this->_profileIds);
     }
     if (!$this->_gid) {
         $this->_gid = CRM_Utils_Request::retrieve('gid', 'Positive', $this, FALSE, 0, 'GET');
     }
     $this->_activityId = CRM_Utils_Request::retrieve('aid', 'Positive', $this, FALSE, 0, 'GET');
     if (is_numeric($this->_activityId)) {
         $latestRevisionId = CRM_Activity_BAO_Activity::getLatestActivityId($this->_activityId);
         if ($latestRevisionId) {
             $this->_activityId = $latestRevisionId;
         }
     }
     $this->_isContactActivityProfile = CRM_Core_BAO_UFField::checkContactActivityProfileType($this->_gid);
     //get values for captch and dupe update.
     if ($this->_gid) {
         $dao = new CRM_Core_DAO_UFGroup();
         $dao->id = $this->_gid;
         if ($dao->find(TRUE)) {
             $this->_isUpdateDupe = $dao->is_update_dupe;
             $this->_isAddCaptcha = $dao->add_captcha;
         }
         $dao->free();
     }
     if (empty($this->_profileIds)) {
         $gids = $this->_gid;
     } else {
         $gids = $this->_profileIds;
     }
     // if we dont have a gid use the default, else just use that specific gid
     if (($this->_mode == self::MODE_REGISTER || $this->_mode == self::MODE_CREATE) && !$this->_gid) {
         $this->_ctype = CRM_Utils_Request::retrieve('ctype', 'String', $this, FALSE, 'Individual', 'REQUEST');
         $this->_fields = CRM_Core_BAO_UFGroup::getRegistrationFields($this->_action, $this->_mode, $this->_ctype);
     } elseif ($this->_mode == self::MODE_SEARCH) {
         $this->_fields = CRM_Core_BAO_UFGroup::getListingFields($this->_action, CRM_Core_BAO_UFGroup::PUBLIC_VISIBILITY | CRM_Core_BAO_UFGroup::LISTINGS_VISIBILITY, FALSE, $gids, TRUE, NULL, $this->_skipPermission, CRM_Core_Permission::SEARCH);
     } else {
         $this->_fields = CRM_Core_BAO_UFGroup::getFields($gids, FALSE, NULL, NULL, NULL, FALSE, NULL, $this->_skipPermission, NULL, $this->_action == CRM_Core_Action::ADD ? CRM_Core_Permission::CREATE : CRM_Core_Permission::EDIT);
         // is profile double-opt in?
         if (CRM_Utils_Array::value('group', $this->_fields) && CRM_Core_BAO_UFGroup::isProfileDoubleOptin()) {
             $emailField = FALSE;
             foreach ($this->_fields as $name => $values) {
                 if (substr($name, 0, 6) == 'email-') {
                     $emailField = TRUE;
                 }
             }
             if (!$emailField) {
                 $session = CRM_Core_Session::singleton();
                 $status = ts("Email field should be included in profile if you want to use Group(s) when Profile double-opt in process is enabled.");
                 $session->setStatus($status);
             }
         }
     }
     if (!is_array($this->_fields)) {
         $session = CRM_Core_Session::singleton();
         CRM_Core_Session::setStatus(ts('This feature is not currently available.'));
         return CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm', 'reset=1'));
     }
     if ($this->_mode != self::MODE_SEARCH) {
         CRM_Core_BAO_UFGroup::setRegisterDefaults($this->_fields, $defaults);
         $this->setDefaults($defaults);
     }
 }