From 73a688e3f45787b97daf0ec9d1a58aa08af16c2a Mon Sep 17 00:00:00 2001 From: Edsel Lopez Date: Thu, 5 Mar 2020 19:30:20 +0530 Subject: [PATCH] Applied changes for v5.22.1 --- CRM/Core/BAO/UFField.php | 348 ++++++++------- CRM/Core/BAO/UFGroup.php | 722 ++++++++++++++------------------ CRM/Core/Controller.php | 72 ++-- CRM/Core/Page/AJAX/Location.php | 110 ++--- CRM/Grant/BAO/Query.php | 123 +++--- CRM/Grant/Info.php | 78 ++-- CRM/UF/Page/Group.php | 104 ++--- CRM/UF/Page/ProfileEditor.php | 59 +-- 8 files changed, 713 insertions(+), 903 deletions(-) diff --git a/CRM/Core/BAO/UFField.php b/CRM/Core/BAO/UFField.php index ecd0b48..b79e978 100755 --- a/CRM/Core/BAO/UFField.php +++ b/CRM/Core/BAO/UFField.php @@ -1,34 +1,18 @@ 'uf_group_id', - 'id' => $params['id'], - )); - } - else { - $groupId = CRM_Utils_Array::value('uf_group_id', $params); - } + public static function create($params) { + $id = CRM_Utils_Array::value('id', $params); - $field_name = CRM_Utils_Array::value('field_name', $params); + // Merge in data from existing field + if (!empty($id)) { + $UFField = new CRM_Core_BAO_UFField(); + $UFField->id = $params['id']; + if ($UFField->find(TRUE)) { + $defaults = $UFField->toArray(); + // This will be calculated based on field name + unset($defaults['field_type']); + $params += $defaults; + } + else { + throw new API_Exception("UFFIeld id {$params['id']} not found."); + } + } - if (strpos($field_name, 'formatting') !== 0 && !CRM_Core_BAO_UFField::isValidFieldName($field_name)) { + // Validate field_name + if (strpos($params['field_name'], 'formatting') !== 0 && !CRM_Core_BAO_UFField::isValidFieldName($params['field_name'])) { throw new API_Exception('The field_name is not valid'); } - if (!(CRM_Utils_Array::value('group_id', $params))) { - $params['group_id'] = $groupId; + // Supply default label if not set + if (empty($id) && !isset($params['label'])) { + $params['label'] = self::getAvailableFieldTitles()[$params['field_name']]; } - $fieldId = CRM_Utils_Array::value('id', $params); - if (!empty($fieldId)) { - $UFField = new CRM_Core_BAO_UFField(); - $UFField->id = $fieldId; - if ($UFField->find(TRUE)) { - if (!(CRM_Utils_Array::value('group_id', $params))) { - // this copied here from previous api function - not sure if required - $params['group_id'] = $UFField->uf_group_id; - } - } - else { - throw new API_Exception("there is no field for this fieldId"); - } + // Supply field_type if not set + if (empty($params['field_type']) && strpos($params['field_name'], 'formatting') !== 0) { + $params['field_type'] = CRM_Utils_Array::pathGet(self::getAvailableFieldsFlat(), [$params['field_name'], 'field_type']); + } + elseif (empty($params['field_type'])) { + $params['field_type'] = 'Formatting'; + } + + // Generate unique name for formatting fields + if ($params['field_name'] === 'formatting') { + $params['field_name'] = 'formatting_' . substr(uniqid(), -4); } - $params['uf_group_id'] = $params['group_id']; - if (CRM_Core_BAO_UFField::duplicateField($params)) { + if (self::duplicateField($params)) { throw new API_Exception("The field was not added. It already exists in this profile."); } - // @todo fix BAO to be less weird. - $field_type = CRM_Utils_Array::value('field_type', $params); - $location_type_id = CRM_Utils_Array::value('location_type_id', $params, CRM_Utils_Array::value('website_type_id', $params)); - $phone_type = CRM_Utils_Array::value('phone_type_id', $params, CRM_Utils_Array::value('phone_type', $params)); - $params['field_name'] = array($field_type, $field_name, $location_type_id, $phone_type); //@todo why is this even optional? Surely weight should just be 'managed' ?? if (CRM_Utils_Array::value('option.autoweight', $params, TRUE)) { $params['weight'] = CRM_Core_BAO_UFField::autoWeight($params); } - // set values for uf field properties and save + + // Set values for uf field properties and save $ufField = new CRM_Core_DAO_UFField(); $ufField->copyValues($params); - $ufField->field_type = $params['field_name'][0]; - $ufField->field_name = $params['field_name'][1]; - //should not set location type id for Primary - $locationTypeId = NULL; - if ($params['field_name'][1] == 'url') { - $ufField->website_type_id = CRM_Utils_Array::value(2, $params['field_name']); + if ($params['field_name'] == 'url') { + $ufField->location_type_id = 'null'; } else { - $locationTypeId = CRM_Utils_Array::value(2, $params['field_name']); - $ufField->website_type_id = NULL; + $ufField->website_type_id = 'null'; } - if ($locationTypeId) { - $ufField->location_type_id = $locationTypeId; + if (!strstr($params['field_name'], 'phone')) { + $ufField->phone_type_id = 'null'; } - else { - $ufField->location_type_id = 'null'; - } - - $ufField->phone_type_id = CRM_Utils_Array::value(3, $params['field_name'], 'NULL'); $ufField->save(); - $fieldsType = CRM_Core_BAO_UFGroup::calculateGroupType($groupId, TRUE); - CRM_Core_BAO_UFGroup::updateGroupTypes($groupId, $fieldsType); + $fieldsType = CRM_Core_BAO_UFGroup::calculateGroupType($ufField->uf_group_id, TRUE); + CRM_Core_BAO_UFGroup::updateGroupTypes($ufField->uf_group_id, $fieldsType); - civicrm_api3('profile', 'getfields', array('cache_clear' => TRUE)); + civicrm_api3('profile', 'getfields', ['cache_clear' => TRUE]); return $ufField; } - /** * Fetch object based on array of properties. * @@ -158,8 +131,8 @@ public static function retrieve(&$params, &$defaults) { * @param bool $is_active * Value we want to set the is_active field. * - * @return Object - * DAO object on success, null otherwise + * @return bool + * true if we found and updated the object, else false */ public static function setIsActive($id, $is_active) { //check if custom data profile field is disabled @@ -204,17 +177,23 @@ public static function del($id) { public static function duplicateField($params) { $ufField = new CRM_Core_DAO_UFField(); $ufField->uf_group_id = CRM_Utils_Array::value('uf_group_id', $params); - $ufField->field_type = $params['field_type']; - $ufField->field_name = $params['field_name']; + $ufField->field_type = CRM_Utils_Array::value('field_type', $params); + $ufField->field_name = CRM_Utils_Array::value('field_name', $params); $ufField->website_type_id = CRM_Utils_Array::value('website_type_id', $params); - $ufField->location_type_id = CRM_Utils_Array::value('location_type_id', $params); - $ufField->phone_type_id = CRM_Utils_Array::value('phone_type_id', $params);; + if (is_null(CRM_Utils_Array::value('location_type_id', $params, ''))) { + // primary location type have NULL value in DB + $ufField->whereAdd("location_type_id IS NULL"); + } + else { + $ufField->location_type_id = CRM_Utils_Array::value('location_type_id', $params); + } + $ufField->phone_type_id = CRM_Utils_Array::value('phone_type_id', $params); if (!empty($params['id'])) { $ufField->whereAdd("id <> " . $params['id']); } - return ($ufField->find(TRUE) ? 1 : 0); + return (bool) $ufField->find(TRUE); } /** @@ -229,9 +208,9 @@ public static function checkMultiRecordFieldExists($gId) { FROM civicrm_uf_field f, civicrm_uf_group g WHERE f.uf_group_id = g.id AND g.id = %1 AND f.field_name LIKE 'custom%'"; - $p = array(1 => array($gId, 'Integer')); + $p = [1 => [$gId, 'Integer']]; $dao = CRM_Core_DAO::executeQuery($queryString, $p); - $customFieldIds = array(); + $customFieldIds = []; $isMultiRecordFieldPresent = FALSE; while ($dao->fetch()) { if ($customId = CRM_Core_BAO_CustomField::getKeyID($dao->field_name)) { @@ -274,10 +253,10 @@ public static function autoWeight($params) { // fix for CRM-316 $oldWeight = NULL; - if (!empty($params['field_id'])) { - $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFField', $params['field_id'], 'weight', 'id'); + if (!empty($params['field_id']) || !empty($params['id'])) { + $oldWeight = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFField', !empty($params['id']) ? $params['id'] : $params['field_id'], 'weight', 'id'); } - $fieldValues = array('uf_group_id' => $params['group_id']); + $fieldValues = ['uf_group_id' => !empty($params['uf_group_id']) ? $params['uf_group_id'] : $params['group_id']]; return CRM_Utils_Weight::updateOtherWeights('CRM_Core_DAO_UFField', $oldWeight, CRM_Utils_Array::value('weight', $params, 0), $fieldValues); } @@ -354,7 +333,7 @@ public static function setUFFieldStatus($customGroupId, $is_active) { FROM civicrm_custom_field, civicrm_custom_group WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id AND civicrm_custom_group.id = %1"; - $p = array(1 => array($customGroupId, 'Integer')); + $p = [1 => [$customGroupId, 'Integer']]; $dao = CRM_Core_DAO::executeQuery($queryString, $p); while ($dao->fetch()) { @@ -413,7 +392,7 @@ public static function checkContactActivityProfileType($ufGroupId) { * @return bool */ public static function checkContactActivityProfileTypeByGroupType($ufGroupType) { - $profileTypes = array(); + $profileTypes = []; if ($ufGroupType) { $typeParts = explode(CRM_Core_DAO::VALUE_SEPARATOR, $ufGroupType); $profileTypes = explode(',', $typeParts[0]); @@ -422,7 +401,7 @@ public static function checkContactActivityProfileTypeByGroupType($ufGroupType) if (empty($profileTypes)) { return FALSE; } - $components = array('Contribution', 'Participant', 'Membership'); + $components = ['Contribution', 'Participant', 'Membership']; if (!in_array('Activity', $profileTypes)) { return FALSE; } @@ -437,7 +416,7 @@ public static function checkContactActivityProfileTypeByGroupType($ufGroupType) } } - $contactTypes = array('Individual', 'Household', 'Organization'); + $contactTypes = ['Individual', 'Household', 'Organization']; $subTypes = CRM_Contact_BAO_ContactType::subTypes(); $profileTypeComponent = array_intersect($components, $profileTypes); @@ -473,7 +452,7 @@ public static function checkValidProfileType($ufGroupId, $required, $optional = $ufGroup->id = $ufGroupId; $ufGroup->find(TRUE); - $profileTypes = array(); + $profileTypes = []; if ($ufGroup->group_type) { $typeParts = explode(CRM_Core_DAO::VALUE_SEPARATOR, $ufGroup->group_type); $profileTypes = explode(',', $typeParts[0]); @@ -516,7 +495,7 @@ public static function checkProfileType($ufGroupId) { $ufGroup->id = $ufGroupId; $ufGroup->find(TRUE); - $profileTypes = array(); + $profileTypes = []; if ($ufGroup->group_type) { $typeParts = explode(CRM_Core_DAO::VALUE_SEPARATOR, $ufGroup->group_type); $profileTypes = explode(',', $typeParts[0]); @@ -538,9 +517,9 @@ public static function checkProfileType($ufGroupId) { // suppress any subtypes if present CRM_Contact_BAO_ContactType::suppressSubTypes($profileTypes); - $contactTypes = array('Contact', 'Individual', 'Household', 'Organization'); - $components = array('Contribution', 'Participant', 'Membership', 'Activity', 'Grant'); - $fields = array(); + $contactTypes = ['Contact', 'Individual', 'Household', 'Organization']; + $components = ['Contribution', 'Participant', 'Membership', 'Activity', 'Grant']; + $fields = []; // check for mix profile condition if (count($profileTypes) > 1) { @@ -606,11 +585,11 @@ public static function getProfileType($ufGroupId, $returnMixType = TRUE, $onlyPu */ public static function calculateProfileType($ufGroupType, $returnMixType = TRUE, $onlyPure = FALSE, $skipComponentType = FALSE) { // profile types - $contactTypes = array('Contact', 'Individual', 'Household', 'Organization'); + $contactTypes = ['Contact', 'Individual', 'Household', 'Organization']; $subTypes = CRM_Contact_BAO_ContactType::subTypes(); - $components = array('Contribution', 'Participant', 'Membership', 'Activity', 'Grant'); + $components = ['Contribution', 'Participant', 'Membership', 'Activity', 'Grant']; - $profileTypes = array(); + $profileTypes = []; if ($ufGroupType) { $typeParts = explode(CRM_Core_DAO::VALUE_SEPARATOR, $ufGroupType); $profileTypes = explode(',', $typeParts[0]); @@ -641,7 +620,7 @@ public static function calculateProfileType($ufGroupType, $returnMixType = TRUE, } else { //check the there are any components include in profile - $componentCount = array(); + $componentCount = []; foreach ($components as $value) { if (in_array($value, $profileTypes)) { $componentCount[] = $value; @@ -649,14 +628,14 @@ public static function calculateProfileType($ufGroupType, $returnMixType = TRUE, } //check contact type included in profile - $contactTypeCount = array(); + $contactTypeCount = []; foreach ($contactTypes as $value) { if (in_array($value, $profileTypes)) { $contactTypeCount[] = $value; } } // subtype counter - $subTypeCount = array(); + $subTypeCount = []; foreach ($subTypes as $value) { if (in_array($value, $profileTypes)) { $subTypeCount[] = $value; @@ -717,8 +696,8 @@ public static function checkProfileGroupType($ctype) { $ufGroup = CRM_Core_DAO::executeQuery($query); - $fields = array(); - $validProfiles = array('Individual', 'Organization', 'Household', 'Contribution'); + $fields = []; + $validProfiles = ['Individual', 'Organization', 'Household', 'Contribution']; while ($ufGroup->fetch()) { $profileType = self::getProfileType($ufGroup->id); if (in_array($profileType, $validProfiles)) { @@ -804,16 +783,16 @@ public static function assignAddressField($key, &$profileAddressFields, $profile list($prefixName, $index) = CRM_Utils_System::explode('-', $key, 2); $profileFields = civicrm_api3('uf_field', 'get', array_merge($profileFilter, - array( + [ 'is_active' => 1, 'return' => 'field_name, is_required', - 'options' => array( + 'options' => [ 'limit' => 0, - ), - ) + ], + ] )); //check for valid fields ( fields that are present in billing block ) - $validBillingFields = array( + $validBillingFields = [ 'first_name', 'middle_name', 'last_name', @@ -823,16 +802,16 @@ public static function assignAddressField($key, &$profileAddressFields, $profile 'state_province', 'postal_code', 'country', - ); - $requiredBillingFields = array_diff($validBillingFields, array('middle_name', 'supplemental_address_1')); - $validProfileFields = array(); - $requiredProfileFields = array(); + ]; + $requiredBillingFields = array_diff($validBillingFields, ['middle_name', 'supplemental_address_1']); + $validProfileFields = []; + $requiredProfileFields = []; foreach ($profileFields['values'] as $field) { if (in_array($field['field_name'], $validBillingFields)) { $validProfileFields[] = $field['field_name']; } - if (CRM_Utils_Array::value('is_required', $field)) { + if (!empty($field['is_required'])) { $requiredProfileFields[] = $field['field_name']; } } @@ -859,7 +838,7 @@ public static function assignAddressField($key, &$profileAddressFields, $profile $potentiallyMissingRequiredFields = array_diff($requiredBillingFields, $requiredProfileFields); CRM_Core_Resources::singleton() - ->addSetting(array('billing' => array('billingProfileIsHideable' => empty($potentiallyMissingRequiredFields)))); + ->addSetting(['billing' => ['billingProfileIsHideable' => empty($potentiallyMissingRequiredFields)]]); } /** @@ -869,28 +848,28 @@ public static function assignAddressField($key, &$profileAddressFields, $profile * @param array $defaults : Form defaults * @return array, multidimensional; e.g. $result['FieldGroup']['field_name']['label'] */ - public static function getAvailableFields($gid = NULL, $defaults = array()) { - $fields = array( - 'Contact' => array(), + public static function getAvailableFields($gid = NULL, $defaults = []) { + $fields = [ + 'Contact' => [], 'Individual' => CRM_Contact_BAO_Contact::importableFields('Individual', FALSE, FALSE, TRUE, TRUE, TRUE), 'Household' => CRM_Contact_BAO_Contact::importableFields('Household', FALSE, FALSE, TRUE, TRUE, TRUE), 'Organization' => CRM_Contact_BAO_Contact::importableFields('Organization', FALSE, FALSE, TRUE, TRUE, TRUE), - ); + ]; // include hook injected fields $fields['Contact'] = array_merge($fields['Contact'], CRM_Contact_BAO_Query_Hook::singleton()->getFields()); // add current employer for individuals - $fields['Individual']['current_employer'] = array( + $fields['Individual']['current_employer'] = [ 'name' => 'organization_name', 'title' => ts('Current Employer'), - ); + ]; $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options', TRUE, NULL, TRUE ); - if (!$addressOptions['county']) { + if (empty($addressOptions['county'])) { unset($fields['Individual']['county'], $fields['Household']['county'], $fields['Organization']['county']); } @@ -911,11 +890,11 @@ public static function getAvailableFields($gid = NULL, $defaults = array()) { //unset extension unset($fields['Contact']['phone_ext']); //add psedo field - $fields['Contact']['phone_and_ext'] = array( + $fields['Contact']['phone_and_ext'] = [ 'name' => 'phone_and_ext', 'title' => ts('Phone and Extension'), 'hasLocationType' => 1, - ); + ]; // include Subtypes For Profile $subTypes = CRM_Contact_BAO_ContactType::subTypeInfo(); @@ -936,10 +915,10 @@ public static function getAvailableFields($gid = NULL, $defaults = array()) { unset($contribFields['is_test']); unset($contribFields['is_pay_later']); unset($contribFields['contribution_id']); - $contribFields['contribution_note'] = array( + $contribFields['contribution_note'] = [ 'name' => 'contribution_note', 'title' => ts('Contribution Note'), - ); + ]; $fields['Contribution'] = array_merge($contribFields, self::getContribBatchEntryFields()); } } @@ -982,6 +961,7 @@ public static function getAvailableFields($gid = NULL, $defaults = array()) { 'membership_type_id', 'member_is_test', 'is_override', + 'member_is_override', 'status_override_end_date', 'status_id', 'member_is_pay_later' @@ -1002,10 +982,7 @@ public static function getAvailableFields($gid = NULL, $defaults = array()) { CRM_Utils_Array::remove($caseFields, 'case_id', 'case_type', - 'case_start_date', - 'case_end_date', 'case_role', - 'case_status', 'case_deleted' ); } @@ -1021,12 +998,12 @@ public static function getAvailableFields($gid = NULL, $defaults = array()) { $fields['Activity'] = $activityFields; } - $fields['Formatting']['format_free_html_' . rand(1000, 9999)] = array( + $fields['Formatting']['format_free_html_' . rand(1000, 9999)] = [ 'name' => 'free_html', 'import' => FALSE, 'export' => FALSE, 'title' => 'Free HTML', - ); + ]; // Sort by title foreach ($fields as &$values) { @@ -1034,14 +1011,14 @@ public static function getAvailableFields($gid = NULL, $defaults = array()) { } //group selected and unwanted fields list - $ufFields = $gid ? CRM_Core_BAO_UFGroup::getFields($gid, FALSE, NULL, NULL, NULL, TRUE, NULL, TRUE) : array(); - $groupFieldList = array_merge($ufFields, array( + $ufFields = $gid ? CRM_Core_BAO_UFGroup::getFields($gid, FALSE, NULL, NULL, NULL, TRUE, NULL, TRUE) : []; + $groupFieldList = array_merge($ufFields, [ 'note', 'email_greeting_custom', 'postal_greeting_custom', 'addressee_custom', 'id', - )); + ]); //unset selected fields foreach ($groupFieldList as $key => $value) { if (is_int($key)) { @@ -1065,24 +1042,33 @@ public static function getAvailableFields($gid = NULL, $defaults = array()) { * * @param bool $force * - * @return array, multidimensional; e.g. $result['field_name']['label'] + * @return array + * e.g. $result['field_name']['label'] */ public static function getAvailableFieldsFlat($force = FALSE) { - // FIXME reset when data model changes - static $result = NULL; - if ($result === NULL || $force) { - $fieldTree = self::getAvailableFields(); - $result = array(); - foreach ($fieldTree as $field_type => $fields) { - foreach ($fields as $field_name => $field) { - if (!isset($result[$field_name])) { - $field['field_type'] = $field_type; - $result[$field_name] = $field; + if (!isset(Civi::$statics['UFFieldsFlat']) || $force) { + Civi::$statics['UFFieldsFlat'] = []; + foreach (self::getAvailableFields() as $fieldType => $fields) { + foreach ($fields as $fieldName => $field) { + if (!isset(Civi::$statics['UFFieldsFlat'][$fieldName])) { + $field['field_type'] = $fieldType; + Civi::$statics['UFFieldsFlat'][$fieldName] = $field; } } } } - return $result; + return Civi::$statics['UFFieldsFlat']; + } + + /** + * Get a list of fields which can be added to profiles in the format [name => title] + * + * @return array + */ + public static function getAvailableFieldTitles() { + $fields = self::getAvailableFieldsFlat(); + $fields['formatting'] = ['title' => ts('Formatting')]; + return CRM_Utils_Array::collect('title', $fields); } /** @@ -1101,32 +1087,32 @@ public static function isValidFieldName($fieldName) { */ public static function getContribBatchEntryFields() { if (self::$_contriBatchEntryFields === NULL) { - self::$_contriBatchEntryFields = array( - 'send_receipt' => array( + self::$_contriBatchEntryFields = [ + 'send_receipt' => [ 'name' => 'send_receipt', 'title' => ts('Send Receipt'), - ), - 'soft_credit' => array( + ], + 'soft_credit' => [ 'name' => 'soft_credit', 'title' => ts('Soft Credit'), - ), - 'soft_credit_type' => array( + ], + 'soft_credit_type' => [ 'name' => 'soft_credit_type', 'title' => ts('Soft Credit Type'), - ), - 'product_name' => array( + ], + 'product_name' => [ 'name' => 'product_name', 'title' => ts('Premiums'), - ), - 'contribution_note' => array( + ], + 'contribution_note' => [ 'name' => 'contribution_note', 'title' => ts('Contribution Note'), - ), - 'contribution_soft_credit_pcp_id' => array( + ], + 'contribution_soft_credit_pcp_id' => [ 'name' => 'contribution_soft_credit_pcp_id', 'title' => ts('Personal Campaign Page'), - ), - ); + ], + ]; } return self::$_contriBatchEntryFields; } @@ -1136,44 +1122,44 @@ public static function getContribBatchEntryFields() { */ public static function getMemberBatchEntryFields() { if (self::$_memberBatchEntryFields === NULL) { - self::$_memberBatchEntryFields = array( - 'send_receipt' => array( + self::$_memberBatchEntryFields = [ + 'send_receipt' => [ 'name' => 'send_receipt', 'title' => ts('Send Receipt'), - ), - 'soft_credit' => array( + ], + 'soft_credit' => [ 'name' => 'soft_credit', 'title' => ts('Soft Credit'), - ), - 'product_name' => array( + ], + 'product_name' => [ 'name' => 'product_name', 'title' => ts('Premiums'), - ), - 'financial_type' => array( + ], + 'financial_type' => [ 'name' => 'financial_type', 'title' => ts('Financial Type'), - ), - 'total_amount' => array( + ], + 'total_amount' => [ 'name' => 'total_amount', 'title' => ts('Total Amount'), - ), - 'receive_date' => array( + ], + 'receive_date' => [ 'name' => 'receive_date', 'title' => ts('Date Received'), - ), - 'payment_instrument' => array( + ], + 'payment_instrument' => [ 'name' => 'payment_instrument', 'title' => ts('Payment Method'), - ), - 'contribution_status_id' => array( + ], + 'contribution_status_id' => [ 'name' => 'contribution_status_id', 'title' => ts('Contribution Status'), - ), - 'trxn_id' => array( + ], + 'trxn_id' => [ 'name' => 'contribution_trxn_id', 'title' => ts('Contribution Transaction ID'), - ), - ); + ], + ]; } return self::$_memberBatchEntryFields; } diff --git a/CRM/Core/BAO/UFGroup.php b/CRM/Core/BAO/UFGroup.php index 2f49193..fa72db3 100644 --- a/CRM/Core/BAO/UFGroup.php +++ b/CRM/Core/BAO/UFGroup.php @@ -1,40 +1,25 @@ $title) { if ($ctype) { @@ -194,8 +181,11 @@ public static function getRegistrationFields($action, $mode, $ctype = NULL) { * @param null $restrict * @param bool $skipPermission * @param int $permissionType + * * @return array * the fields that are listings related + * + * @throws \Exception */ public static function getListingFields( $action, @@ -228,7 +218,7 @@ public static function getListingFields( else { $ufGroups = CRM_Core_PseudoConstant::get('CRM_Core_DAO_UFField', 'uf_group_id'); - $fields = array(); + $fields = []; foreach ($ufGroups as $id => $title) { $subset = self::getFields($id, FALSE, $action, $visibility, $searchable, @@ -277,7 +267,8 @@ public static function getListingFields( * * @return array * The fields that belong to this ufgroup(s) - * @throws \Exception + * + * @throws \CRM_Core_Exception */ public static function getFields( $id, @@ -296,21 +287,21 @@ public static function getFields( ) { if (!is_array($id)) { $id = CRM_Utils_Type::escape($id, 'Positive'); - $profileIds = array($id); + $profileIds = [$id]; } else { $profileIds = $id; } $gids = implode(',', $profileIds); - $params = array(); + $params = []; if ($restrict) { $query = "SELECT g.* from civicrm_uf_group g LEFT JOIN civicrm_uf_join j ON (j.uf_group_id = g.id) WHERE g.id IN ( {$gids} ) AND ((j.uf_group_id IN ( {$gids} ) AND j.module = %1) OR g.is_reserved = 1 ) "; - $params = array(1 => array($restrict, 'String')); + $params = [1 => [$restrict, 'String']]; } else { $query = "SELECT g.* from civicrm_uf_group g WHERE g.id IN ( {$gids} ) "; @@ -320,12 +311,12 @@ public static function getFields( $query .= " AND g.is_active = 1"; } - $checkPermission = array( - array( + $checkPermission = [ + [ 'administer CiviCRM', 'manage event profiles', - ), - ); + ], + ]; if ($eventProfile && CRM_Core_Permission::check($checkPermission)) { $skipPermission = TRUE; } @@ -336,11 +327,11 @@ public static function getFields( $query .= " AND $permissionClause "; } - if ($orderProfiles AND count($profileIds) > 1) { + if ($orderProfiles and count($profileIds) > 1) { $query .= " ORDER BY FIELD( g.id, {$gids} )"; } $group = CRM_Core_DAO::executeQuery($query, $params); - $fields = array(); + $fields = []; $validGroup = FALSE; while ($group->fetch()) { @@ -357,12 +348,11 @@ public static function getFields( $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)) + throw new CRM_Core_Exception(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.', + [1 => implode(',', $profileIds)] )); } else { @@ -412,7 +402,7 @@ public static function formatUFFields( $importableFields = self::getImportableFields($showAll, $profileType, $contactActivityProfile); list($customFields, $addressCustomFields) = self::getCustomFields($ctype); - $formattedFields = array(); + $formattedFields = []; foreach ($fieldArrs as $fieldArr) { $field = (object) $fieldArr; if (!self::filterUFField($field, $searchable, $showAll, $visibility)) { @@ -437,6 +427,7 @@ public static function formatUFFields( * @param array $importableFields * @param int $permissionType * Eg CRM_Core_Permission::CREATE. + * * @return array */ protected static function formatUFField( @@ -451,10 +442,7 @@ protected static function formatUFField( $title = $field->label; $addressCustom = FALSE; - if (in_array($permissionType, array( - CRM_Core_Permission::CREATE, - CRM_Core_Permission::EDIT, - )) && + if (in_array($permissionType, [CRM_Core_Permission::CREATE, CRM_Core_Permission::EDIT]) && in_array($field->field_name, array_keys($addressCustomFields)) ) { $addressCustom = TRUE; @@ -476,11 +464,11 @@ protected static function formatUFField( if (isset($field->phone_type_id)) { $name .= "-{$field->phone_type_id}"; } - $fieldMetaData = CRM_Utils_Array::value($name, $importableFields, (isset($importableFields[$field->field_name]) ? $importableFields[$field->field_name] : array())); + $fieldMetaData = CRM_Utils_Array::value($name, $importableFields, (isset($importableFields[$field->field_name]) ? $importableFields[$field->field_name] : [])); // No lie: this is bizarre; why do we need to mix so many UFGroup properties into UFFields? // I guess to make field self sufficient with all the required data and avoid additional calls - $formattedField = array( + $formattedField = [ 'name' => $name, 'groupTitle' => $group->title, 'groupName' => $group->name, @@ -517,7 +505,7 @@ protected static function formatUFField( 'skipDisplay' => 0, 'data_type' => CRM_Utils_Type::getDataTypeFromFieldMetadata($fieldMetaData), 'bao' => CRM_Utils_Array::value('bao', $fieldMetaData), - ); + ]; $formattedField = CRM_Utils_Date::addDateMetadataToField($fieldMetaData, $formattedField); @@ -541,14 +529,14 @@ protected static function formatUFField( } $formattedField['is_multi_summary'] = $field->is_multi_summary; - return array($name, $formattedField); + return [$name, $formattedField]; } else { $formattedField = NULL; - return array($name, $formattedField); + return [$name, $formattedField]; } } - return array($name, $formattedField); + return [$name, $formattedField]; } /** @@ -562,6 +550,7 @@ protected static function formatUFField( * @param int $visibility * @param string $orderBy * Comma-delimited list of SQL columns. + * * @return string */ protected static function createUFFieldQuery($groupId, $searchable, $showAll, $visibility, $orderBy) { @@ -576,7 +565,7 @@ protected static function createUFFieldQuery($groupId, $searchable, $showAll, $v } if ($visibility) { - $clause = array(); + $clause = []; if ($visibility & self::PUBLIC_VISIBILITY) { $clause[] = 'visibility = "Public Pages"'; } @@ -608,6 +597,7 @@ protected static function createUFFieldQuery($groupId, $searchable, $showAll, $v * @param bool $searchable * @param bool $showAll * @param int $visibility + * * @return bool * TRUE if field is displayable */ @@ -621,7 +611,7 @@ protected static function filterUFField($field, $searchable, $showAll, $visibili } if ($visibility) { - $allowedVisibilities = array(); + $allowedVisibilities = []; if ($visibility & self::PUBLIC_VISIBILITY) { $allowedVisibilities[] = 'Public Pages'; } @@ -643,8 +633,6 @@ protected static function filterUFField($field, $searchable, $showAll, $visibili /** * Get a list of filtered field metadata. * - * @deprecated use getProfileFieldMetadata - * * @param $showAll * @param $profileType * @param $contactActivityProfile @@ -657,6 +645,8 @@ protected static function filterUFField($field, $searchable, $showAll, $visibili * send this confusion to history. * * @return array + * @deprecated use getProfileFieldMetadata + * */ protected static function getImportableFields($showAll, $profileType, $contactActivityProfile, $filterMode = TRUE) { if (!$showAll) { @@ -706,7 +696,7 @@ protected static function getProfileFieldMetadata($isIncludeInactive) { * @return array */ public static function getLocationFields() { - static $locationFields = array( + static $locationFields = [ 'street_address', 'supplemental_address_1', 'supplemental_address_2', @@ -725,7 +715,7 @@ public static function getLocationFields() { 'im', 'address_name', 'phone_ext', - ); + ]; return $locationFields; } @@ -735,20 +725,20 @@ public static function getLocationFields() { * @return mixed */ protected static function getCustomFields($ctype) { - static $customFieldCache = array(); - if (!isset($customFieldCache[$ctype])) { + $cacheKey = 'uf_group_custom_fields_' . $ctype; + if (!Civi::cache('metadata')->has($cacheKey)) { $customFields = CRM_Core_BAO_CustomField::getFieldsForImport($ctype, FALSE, FALSE, FALSE, TRUE, TRUE); // hack to add custom data for components - $components = array('Contribution', 'Participant', 'Membership', 'Activity', 'Case', 'Grant'); + $components = ['Contribution', 'Participant', 'Membership', 'Activity', 'Case', 'Grant']; 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); - $customFieldCache[$ctype] = array($customFields, $addressCustomFields); + Civi::cache('metadata')->set($cacheKey, [$customFields, $addressCustomFields]); } - return $customFieldCache[$ctype]; + return Civi::cache('metadata')->get($cacheKey); } /** @@ -982,7 +972,7 @@ public static function getValues( // get the contact details (hier) $returnProperties = CRM_Contact_BAO_Contact::makeHierReturnProperties($fields); - $params = $cid ? array(array('contact_id', '=', $cid, 0, 0)) : array(); + $params = $cid ? [['contact_id', '=', $cid, 0, 0]] : []; // add conditions specified by components. eg partcipant_id etc if (!empty($componentWhere)) { @@ -993,17 +983,18 @@ public static function getValues( $details = $query->searchQuery(0, 0, NULL, FALSE, FALSE, FALSE, FALSE, FALSE, $additionalWhereClause); - if (!$details->fetch()) { - return; + while ($details->fetch()) { + if (!$details) { + 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'); + $locationTypes = CRM_Core_BAO_Address::buildOptions('location_type_id', 'validate'); + $imProviders = CRM_Core_DAO_IM::buildOptions('provider_id'); + $websiteTypes = CRM_Core_DAO_Website::buildOptions('website_type_id'); - $multipleFields = array('url'); + $multipleFields = ['url']; //start of code to set the default values foreach ($fields as $name => $field) { @@ -1031,7 +1022,7 @@ public static function getValues( // 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'))) { + if (in_array(substr($name, 0, -3), ['gender', 'prefix', 'suffix'])) { $params[$index] = $details->$name; $values[$index] = $details->$name; } @@ -1041,11 +1032,11 @@ public static function getValues( $name = $name . '_id'; $params[$index] = $details->$name; } - elseif (in_array($name, array( + elseif (in_array($name, [ 'state_province', 'country', 'county', - ))) { + ])) { $values[$index] = $details->$name; $idx = $name . '_id'; $params[$index] = $details->$idx; @@ -1056,7 +1047,7 @@ public static function getValues( } elseif ($name == 'group') { $groups = CRM_Contact_BAO_GroupContact::getContactGroup($cid, 'Added', NULL, FALSE, TRUE); - $title = $ids = array(); + $title = $ids = []; foreach ($groups as $g) { // CRM-8362: User and User Admin visibility groups should be included in display if user has @@ -1077,8 +1068,8 @@ public static function getValues( } 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(); + $allTags = CRM_Core_PseudoConstant::get('CRM_Core_DAO_EntityTag', 'tag_id', ['onlyActive' => FALSE]); + $title = []; foreach ($entityTags as $tagId) { $title[] = $allTags[$tagId]; } @@ -1097,7 +1088,7 @@ public static function getValues( elseif ($name == 'contact_sub_type') { $contactSubTypeNames = explode(CRM_Core_DAO::VALUE_SEPARATOR, $details->$name); if (!empty($contactSubTypeNames)) { - $contactSubTypeLabels = array(); + $contactSubTypeLabels = []; // get all contact subtypes $allContactSubTypes = CRM_Contact_BAO_ContactType::subTypeInfo(); // build contact subtype labels array @@ -1188,10 +1179,10 @@ public static function getValues( $image_URL = ''; $values[$index] = "{$image_URL}"; } - elseif (in_array($name, array( + elseif (in_array($name, [ 'birth_date', 'deceased_date', - ))) { + ])) { // @todo this set should be determined from metadata, not hard-coded. $values[$index] = CRM_Utils_Date::customFormat($details->$name); $params[$index] = CRM_Utils_Date::isoToMysql($details->$name); @@ -1237,22 +1228,22 @@ public static function getValues( $detailName = "{$locationTypeName}-{$fieldName}"; $detailName = str_replace(' ', '_', $detailName); - if (in_array($fieldName, array( + if (in_array($fieldName, [ 'phone', 'im', 'email', 'openid', - ))) { + ])) { if ($type) { $detailName .= "-{$type}"; } } - if (in_array($fieldName, array( + if (in_array($fieldName, [ 'state_province', 'country', 'county', - ))) { + ])) { $values[$index] = $details->$detailName; $idx = $detailName . '_id'; $params[$index] = $details->$idx; @@ -1318,13 +1309,13 @@ public static function getValues( if ($htmlType == 'Link') { $url = $params[$index]; } - elseif (in_array($htmlType, array( + elseif (in_array($htmlType, [ 'CheckBox', 'Multi-Select', 'AdvMulti-Select', 'Multi-Select State/Province', 'Multi-Select Country', - ))) { + ])) { $valSeperator = CRM_Core_DAO::VALUE_SEPARATOR; $selectedOptions = explode($valSeperator, $params[$index]); @@ -1363,7 +1354,7 @@ public static function getValues( ) { if (is_array($url) && !empty($url)) { - $links = array(); + $links = []; $eachMultiValue = explode(', ', $values[$index]); foreach ($eachMultiValue as $key => $valueLabel) { $links[] = '' . $valueLabel . ''; @@ -1444,8 +1435,8 @@ public static function del($id) { * * @return object */ - public static function add(&$params, $ids = array()) { - $fields = array( + public static function add(&$params, $ids = []) { + $fields = [ 'is_active', 'add_captcha', 'is_map', @@ -1453,7 +1444,7 @@ public static function add(&$params, $ids = array()) { 'is_edit_link', 'is_uf_link', 'is_cms_user', - ); + ]; foreach ($fields as $field) { $params[$field] = CRM_Utils_Array::value($field, $params, FALSE); } @@ -1503,18 +1494,18 @@ public static function createUFJoin(&$params, $ufGroupId) { // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input if (!is_array($groupTypes)) { - $groupTypes = array(); + $groupTypes = []; } // this fix is done to prevent warning generated by array_key_exits incase of empty array is given as input if (!is_array($ufGroupRecord)) { - $ufGroupRecord = array(); + $ufGroupRecord = []; } // check which values has to be inserted/deleted for contact $menuRebuild = FALSE; foreach ($allUFGroupType as $key => $value) { - $joinParams = array(); + $joinParams = []; $joinParams['uf_group_id'] = $ufGroupId; $joinParams['module'] = $key; if ($key == 'User Account') { @@ -1537,10 +1528,10 @@ public static function createUFJoin(&$params, $ufGroupId) { WHERE uf_group_id = %2 AND ( entity_id IS NULL OR entity_id <= 0 ) "; - $p = array( - 1 => array($params['weight'], 'Integer'), - 2 => array($ufGroupId, 'Integer'), - ); + $p = [ + 1 => [$params['weight'], 'Integer'], + 2 => [$ufGroupId, 'Integer'], + ]; CRM_Core_DAO::executeQuery($query, $p); // Do a menu rebuild, so it gets all the new menu entries for user account @@ -1565,11 +1556,11 @@ public static function createUFJoin(&$params, $ufGroupId) { */ public static function getUFJoinRecord($ufGroupId = NULL, $displayName = NULL, $status = NULL) { if ($displayName) { - $UFGroupType = array(); + $UFGroupType = []; $UFGroupType = CRM_Core_SelectValues::ufGroupTypes(); } - $ufJoin = array(); + $ufJoin = []; $dao = new CRM_Core_DAO_UFJoin(); if ($ufGroupId) { @@ -1577,7 +1568,7 @@ public static function getUFJoinRecord($ufGroupId = NULL, $displayName = NULL, $ } $dao->find(); - $ufJoin = array(); + $ufJoin = []; while ($dao->fetch()) { if (!$displayName) { @@ -1637,7 +1628,7 @@ public static function delUFJoin(&$params) { */ public static function getWeight($ufGroupId = NULL) { //calculate the weight - $p = array(); + $p = []; if (!$ufGroupId) { $queryString = "SELECT ( MAX(civicrm_uf_join.weight)+1) as new_weight FROM civicrm_uf_join @@ -1648,7 +1639,7 @@ public static function getWeight($ufGroupId = NULL) { FROM civicrm_uf_join WHERE civicrm_uf_join.uf_group_id = %1 AND ( entity_id IS NULL OR entity_id <= 0 )"; - $p[1] = array($ufGroupId, 'Integer'); + $p[1] = [$ufGroupId, 'Integer']; } $dao = CRM_Core_DAO::executeQuery($queryString, $p); @@ -1672,14 +1663,14 @@ public static function getWeight($ufGroupId = NULL) { * array of ufgroups for a module */ public static function getModuleUFGroup($moduleName = NULL, $count = 0, $skipPermission = TRUE, $op = CRM_Core_Permission::VIEW, $returnFields = NULL) { - $selectFields = array('id', 'title', 'created_id', 'is_active', 'is_reserved', 'group_type'); + $selectFields = ['id', 'title', 'created_id', 'is_active', 'is_reserved', 'group_type']; - if (CRM_Core_DAO::checkFieldExists('civicrm_uf_group', 'description')) { + if (CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_uf_group', 'description')) { // CRM-13555, since description field was added later (4.4), and to avoid any problems with upgrade $selectFields[] = 'description'; } - if (CRM_Core_DAO::checkFieldExists('civicrm_uf_group', 'frontend_title')) { + if (CRM_Core_BAO_SchemaHandler::checkIfFieldExists('civicrm_uf_group', 'frontend_title')) { $selectFields[] = 'frontend_title'; } @@ -1690,11 +1681,11 @@ public static function getModuleUFGroup($moduleName = NULL, $count = 0, $skipPer $queryString = 'SELECT civicrm_uf_group.' . implode(', civicrm_uf_group.', $selectFields) . ' FROM civicrm_uf_group LEFT JOIN civicrm_uf_join ON (civicrm_uf_group.id = uf_group_id)'; - $p = array(); + $p = []; if ($moduleName) { $queryString .= ' AND civicrm_uf_group.is_active = 1 WHERE civicrm_uf_join.module = %2'; - $p[2] = array($moduleName, 'String'); + $p[2] = [$moduleName, 'String']; } // add permissioning for profiles only if not registration @@ -1711,16 +1702,16 @@ public static function getModuleUFGroup($moduleName = NULL, $count = 0, $skipPer $queryString .= ' ORDER BY civicrm_uf_join.weight, civicrm_uf_group.title'; $dao = CRM_Core_DAO::executeQuery($queryString, $p); - $ufGroups = array(); + $ufGroups = []; while ($dao->fetch()) { //skip mix profiles in user Registration / User Account - if (($moduleName == 'User Registration' || $moduleName == 'User Account') && + if (($moduleName === 'User Registration' || $moduleName === 'User Account') && CRM_Core_BAO_UFField::checkProfileType($dao->id) ) { continue; } foreach ($selectFields as $key => $field) { - if ($field == 'id') { + if ($field === 'id') { continue; } $ufGroups[$dao->id][$field] = $dao->$field; @@ -1766,7 +1757,7 @@ public static function filterUFGroups($ufGroupId, $contactID = NULL) { } //allow special mix profiles for Contribution and Participant - $specialProfiles = array('Contribution', 'Participant', 'Membership', 'Grant'); + $specialProfiles = ['Contribution', 'Participant', 'Membership', 'Grant']; if (in_array($profileType, $specialProfiles)) { return TRUE; @@ -1807,7 +1798,7 @@ public static function buildProfile( $rowNumber = NULL, $prefix = '' ) { - $defaultValues = array(); + $defaultValues = []; $fieldName = $field['name']; $title = $field['title']; $attributes = $field['attributes']; @@ -1842,24 +1833,24 @@ public static function buildProfile( $name = $fieldName; } - $selectAttributes = array('class' => 'crm-select2', 'placeholder' => TRUE); + $selectAttributes = ['class' => 'crm-select2', 'placeholder' => TRUE]; if ($fieldName == 'image_URL' && $mode == CRM_Profile_Form::MODE_EDIT) { $deleteExtra = json_encode(ts('Are you sure you want to delete contact image.')); - $deleteURL = array( - CRM_Core_Action::DELETE => array( + $deleteURL = [ + CRM_Core_Action::DELETE => [ 'name' => ts('Delete Contact Image'), 'url' => 'civicrm/contact/image', 'qs' => 'reset=1&id=%%id%%&gid=%%gid%%&action=delete', 'extra' => 'onclick = "' . htmlspecialchars("if (confirm($deleteExtra)) this.href+='&confirmed=1'; else return false;") . '"', - ), - ); + ], + ]; $deleteURL = CRM_Core_Action::formLink($deleteURL, CRM_Core_Action::DELETE, - array( + [ 'id' => $form->get('id'), 'gid' => $form->get('gid'), - ), + ], ts('more'), FALSE, 'contact.profileimage.delete', @@ -1873,12 +1864,9 @@ public static function buildProfile( ); if (substr($fieldName, 0, 14) === 'state_province') { - $form->addChainSelect($name, array('label' => $title, 'required' => $required)); + $form->addChainSelect($name, ['label' => $title, 'required' => $required]); $config = CRM_Core_Config::singleton(); - if (!in_array($mode, array( - CRM_Profile_Form::MODE_EDIT, - CRM_Profile_Form::MODE_SEARCH, - )) && + if (!in_array($mode, [CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH]) && $config->defaultContactStateProvince ) { $defaultValues[$name] = $config->defaultContactStateProvince; @@ -1886,12 +1874,9 @@ public static function buildProfile( } } elseif (substr($fieldName, 0, 7) === 'country') { - $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Core_PseudoConstant::country(), $required, $selectAttributes); + $form->add('select', $name, $title, ['' => ts('- select -')] + CRM_Core_PseudoConstant::country(), $required, $selectAttributes); $config = CRM_Core_Config::singleton(); - if (!in_array($mode, array( - CRM_Profile_Form::MODE_EDIT, - CRM_Profile_Form::MODE_SEARCH, - )) && + if (!in_array($mode, [CRM_Profile_Form::MODE_EDIT, CRM_Profile_Form::MODE_SEARCH]) && $config->defaultContactCountry ) { $defaultValues[$name] = $config->defaultContactCountry; @@ -1900,7 +1885,7 @@ public static function buildProfile( } elseif (substr($fieldName, 0, 6) === 'county') { if ($addressOptions['county']) { - $form->addChainSelect($name, array('label' => $title, 'required' => $required)); + $form->addChainSelect($name, ['label' => $title, 'required' => $required]); } } elseif (substr($fieldName, 0, 9) === 'image_URL') { @@ -1911,20 +1896,20 @@ public static function buildProfile( $form->add('text', $name, $title, $attributes, $required); if (!$contactId) { if ($usedFor) { - if (substr($name, -1) == ']') { + if (substr($name, -1) === ']') { $providerName = substr($name, 0, -1) . '-provider_id]'; } $form->add('select', $providerName, NULL, - array( + [ '' => ts('- select -'), - ) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'), $required + ] + CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'), $required ); } else { $form->add('select', $name . '-provider_id', $title, - array( + [ '' => ts('- select -'), - ) + CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'), $required + ] + CRM_Core_PseudoConstant::get('CRM_Core_DAO_IM', 'provider_id'), $required ); } @@ -1933,24 +1918,10 @@ public static function buildProfile( } } } - elseif (($fieldName === 'birth_date') || ($fieldName === 'deceased_date')) { - $form->addDate($name, $title, $required, array('formatType' => 'birth')); - } - elseif (in_array($fieldName, array( - 'membership_start_date', - 'membership_end_date', - 'join_date', - 'application_received_date', - 'decision_date', - 'grant_money_transfer_date', - 'grant_due_date', - ))) { - $form->addDate($name, $title, $required, array('formatType' => 'activityDate')); - } elseif (CRM_Utils_Array::value('name', $field) == 'membership_type') { list($orgInfo, $types) = CRM_Member_BAO_MembershipType::getMembershipTypeInfo(); $sel = &$form->addElement('hierselect', $name, $title); - $select = array('' => ts('- select -')); + $select = ['' => ts('- select -')]; if (count($orgInfo) == 1 && $field['is_required']) { // we only have one org - so we should default to it. Not sure about defaulting to first type // as it could be missed - so adding a select @@ -1962,37 +1933,37 @@ public static function buildProfile( else { $orgInfo = $select + $orgInfo; } - $sel->setOptions(array($orgInfo, $types)); + $sel->setOptions([$orgInfo, $types]); } elseif (CRM_Utils_Array::value('name', $field) == 'membership_status') { $form->add('select', $name, $title, - array( + [ '' => ts('- select -'), - ) + CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label'), $required + ] + CRM_Member_PseudoConstant::membershipStatus(NULL, NULL, 'label'), $required ); } - elseif (in_array($fieldName, array('gender_id', 'communication_style_id'))) { - $options = array(); + elseif (in_array($fieldName, ['gender_id', 'communication_style_id'])) { + $options = []; $pseudoValues = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', $fieldName); foreach ($pseudoValues as $key => $var) { $options[$key] = $form->createElement('radio', NULL, ts($title), $var, $key); } $group = $form->addGroup($options, $name, $title); if ($required) { - $form->addRule($name, ts('%1 is a required field.', array(1 => $title)), 'required'); + $form->addRule($name, ts('%1 is a required field.', [1 => $title]), 'required'); } else { $group->setAttribute('allowClear', TRUE); } } elseif ($fieldName === 'prefix_id' || $fieldName === 'suffix_id') { - $form->addSelect($name, array( + $form->addSelect($name, [ 'label' => $title, 'entity' => 'contact', 'field' => $fieldName, 'class' => 'six', 'placeholder' => '', - ), $required); + ], $required); } elseif ($fieldName === 'contact_sub_type') { $gId = $form->get('gid') ? $form->get('gid') : CRM_Utils_Array::value('group_id', $field); @@ -2015,47 +1986,36 @@ public static function buildProfile( $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType); } - $subtypes = $profileType ? CRM_Contact_BAO_ContactType::subTypePairs($profileType) : array(); + $subtypes = $profileType ? CRM_Contact_BAO_ContactType::subTypePairs($profileType) : []; if ($setSubtype) { - $subtypeList = array(); + $subtypeList = []; $subtypeList[$setSubtype] = $subtypes[$setSubtype]; } else { $subtypeList = $subtypes; } - $form->add('select', $name, $title, $subtypeList, $required, array('class' => 'crm-select2', 'multiple' => TRUE)); + $form->add('select', $name, $title, $subtypeList, $required, ['class' => 'crm-select2', 'multiple' => TRUE]); } elseif (in_array($fieldName, CRM_Contact_BAO_Contact::$_greetingTypes)) { - //add email greeting, postal greeting, addressee, CRM-4575 - $gId = $form->get('gid') ? $form->get('gid') : CRM_Utils_Array::value('group_id', $field); + // Get contact type for greeting selector + $gId = $form->get('gid') ?: CRM_Utils_Array::value('group_id', $field); $profileType = CRM_Core_BAO_UFField::getProfileType($gId, TRUE, FALSE, TRUE); - if (empty($profileType) || in_array($profileType, array( - 'Contact', - 'Contribution', - 'Participant', - 'Membership', - 'Grant', - )) - ) { - $profileType = 'Individual'; + if (!$profileType || in_array($profileType, ['Contact', 'Contribution', 'Participant', 'Membership', 'Grant'])) { + $profileType = ($profileType == 'Contact' && $form->get('id')) ? CRM_Contact_BAO_Contact::getContactType($form->get('id')) : 'Individual'; } if (CRM_Contact_BAO_ContactType::isaSubType($profileType)) { $profileType = CRM_Contact_BAO_ContactType::getBasicType($profileType); } - $greeting = array( + $greeting = [ 'contact_type' => $profileType, 'greeting_type' => $fieldName, - ); - $form->add('select', $name, $title, - array( - '' => ts('- select -'), - ) + CRM_Core_PseudoConstant::greeting($greeting), $required - ); + ]; + $form->add('select', $name, $title, ['' => ts('- select -')] + CRM_Core_PseudoConstant::greeting($greeting), $required); // add custom greeting element - $form->add('text', $fieldName . '_custom', ts('Custom %1', array(1 => ucwords(str_replace('_', ' ', $fieldName)))), + $form->add('text', $fieldName . '_custom', ts('Custom %1', [1 => ucwords(str_replace('_', ' ', $fieldName))]), NULL, FALSE ); } @@ -2073,7 +2033,7 @@ public static function buildProfile( $form->add('select', $name, $title, CRM_Core_SelectValues::pmf()); } elseif ($fieldName === 'preferred_language') { - $form->add('select', $name, $title, array('' => ts('- select -')) + CRM_Contact_BAO_Contact::buildOptions('preferred_language')); + $form->add('select', $name, $title, ['' => ts('- select -')] + CRM_Contact_BAO_Contact::buildOptions('preferred_language')); } elseif ($fieldName == 'external_identifier') { $form->add('text', $name, $title, $attributes, $required); @@ -2084,7 +2044,7 @@ public static function buildProfile( $form->addRule($name, ts('External ID already exists in Database.'), 'objectExists', - array('CRM_Contact_DAO_Contact', $contID, 'external_identifier') + ['CRM_Contact_DAO_Contact', $contID, 'external_identifier'] ); } elseif ($fieldName === 'group') { @@ -2126,59 +2086,49 @@ public static function buildProfile( $form->addElement('checkbox', $name, $title); } elseif ($fieldName == 'soft_credit') { - $form->addEntityRef("soft_credit_contact_id[$rowNumber]", ts('Soft Credit To'), array('create' => TRUE)); + $form->addEntityRef("soft_credit_contact_id[$rowNumber]", ts('Soft Credit To'), ['create' => TRUE]); $form->addMoney("soft_credit_amount[{$rowNumber}]", ts('Amount'), FALSE, NULL, FALSE); } - elseif ($fieldName == 'product_name') { + elseif ($fieldName === 'product_name') { list($products, $options) = CRM_Contribute_BAO_Premium::getPremiumProductInfo(); $sel = &$form->addElement('hierselect', $name, $title); - $products = array( - '0' => ts('- select -'), - ) + $products; - $sel->setOptions(array($products, $options)); + $products = ['0' => ts('- select -')] + $products; + $sel->setOptions([$products, $options]); } - elseif ($fieldName == 'payment_instrument') { + elseif ($fieldName === 'payment_instrument') { $form->add('select', $name, $title, - array('' => ts('- select -')) + CRM_Contribute_PseudoConstant::paymentInstrument(), $required); + ['' => ts('- select -')] + CRM_Contribute_PseudoConstant::paymentInstrument(), $required); } - elseif ($fieldName == 'financial_type') { + elseif ($fieldName === 'financial_type') { $form->add('select', $name, $title, - array( + [ '' => ts('- select -'), - ) + CRM_Contribute_PseudoConstant::financialType(), $required + ] + CRM_Contribute_PseudoConstant::financialType(), $required ); } - elseif ($fieldName == 'contribution_status_id') { - $contributionStatuses = CRM_Contribute_PseudoConstant::contributionStatus(); - $statusName = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name'); - foreach (array( - 'In Progress', - 'Overdue', - 'Refunded', - ) as $suppress) { - unset($contributionStatuses[CRM_Utils_Array::key($suppress, $statusName)]); - } + elseif ($fieldName === 'contribution_status_id') { + $contributionStatuses = CRM_Contribute_BAO_Contribution_Utils::getContributionStatuses(); $form->add('select', $name, $title, - array( + [ '' => ts('- select -'), - ) + $contributionStatuses, $required + ] + $contributionStatuses, $required ); } - elseif ($fieldName == 'soft_credit_type') { + elseif ($fieldName === 'soft_credit_type') { $name = "soft_credit_type[$rowNumber]"; $form->add('select', $name, $title, - array( + [ '' => ts('- select -'), - ) + CRM_Core_OptionGroup::values("soft_credit_type") + ] + CRM_Core_OptionGroup::values("soft_credit_type") ); //CRM-15350: choose SCT field default value as 'Gift' for membership use //else (for contribution), use configured SCT default value $SCTDefaultValue = CRM_Core_OptionGroup::getDefaultValue("soft_credit_type"); if ($field['field_type'] == 'Membership') { - $SCTDefaultValue = CRM_Core_OptionGroup::getValue('soft_credit_type', 'Gift', 'name'); + $SCTDefaultValue = CRM_Core_PseudoConstant::getKey('CRM_Contribute_BAO_ContributionSoft', 'soft_credit_type_id', 'gift'); } - $form->addElement('hidden', 'sct_default_id', $SCTDefaultValue, array('id' => 'sct_default_id')); + $form->addElement('hidden', 'sct_default_id', $SCTDefaultValue, ['id' => 'sct_default_id']); } elseif ($fieldName == 'contribution_soft_credit_pcp_id') { CRM_Contribute_Form_SoftCredit::addPCPFields($form, "[$rowNumber]"); @@ -2188,23 +2138,23 @@ public static function buildProfile( } elseif ($fieldName == 'contribution_page_id') { $form->add('select', $name, $title, - array( + [ '' => ts('- select -'), - ) + CRM_Contribute_PseudoConstant::contributionPage(), $required, 'class="big"' + ] + CRM_Contribute_PseudoConstant::contributionPage(), $required, 'class="big"' ); } elseif ($fieldName == 'activity_status_id') { $form->add('select', $name, $title, - array( + [ '' => ts('- select -'), - ) + CRM_Core_PseudoConstant::activityStatus(), $required + ] + CRM_Core_PseudoConstant::activityStatus(), $required ); } elseif ($fieldName == 'activity_engagement_level') { $form->add('select', $name, $title, - array( + [ '' => ts('- select -'), - ) + CRM_Campaign_PseudoConstant::engagementLevel(), $required + ] + CRM_Campaign_PseudoConstant::engagementLevel(), $required ); } elseif ($fieldName == 'participant_status') { @@ -2213,9 +2163,9 @@ public static function buildProfile( $cond = 'visibility_id = 1'; } $form->add('select', $name, $title, - array( + [ '' => ts('- select -'), - ) + CRM_Event_PseudoConstant::participantStatus(NULL, $cond, 'label'), $required + ] + CRM_Event_PseudoConstant::participantStatus(NULL, $cond, 'label'), $required ); } elseif ($fieldName == 'participant_role') { @@ -2224,24 +2174,15 @@ public static function buildProfile( } else { $form->add('select', $name, $title, - array( + [ '' => ts('- select -'), - ) + CRM_Event_PseudoConstant::participantRole(), $required + ] + CRM_Event_PseudoConstant::participantRole(), $required ); } } elseif ($fieldName == 'world_region') { $form->add('select', $name, $title, CRM_Core_PseudoConstant::worldRegion(), $required, $selectAttributes); } - elseif ($fieldName == 'grant_type_id') { - $form->add('select', $name, $title, CRM_Core_PseudoConstant::get('CRM_Grant_DAO_Grant', 'grant_type_id'), $required, $selectAttributes); - } - elseif ($fieldName == 'grant_status_id') { - $form->add('select', $name, $title, CRM_Core_PseudoConstant::get('CRM_Grant_DAO_Grant', 'grant_status_id'), $required, $selectAttributes); - } - elseif ($fieldName == 'grant_report_received') { - $form->add('advcheckbox', $name, $title, $attributes, $required); - } elseif ($fieldName == 'signature_html') { $form->add('wysiwyg', $name, $title, CRM_Core_DAO::getAttribute('CRM_Core_DAO_Email', $fieldName)); } @@ -2254,14 +2195,14 @@ public static function buildProfile( $form->_componentCampaigns )); $form->add('select', $name, $title, - array( + [ '' => ts('- select -'), - ) + $campaigns, $required, 'class="crm-select2 big"' + ] + $campaigns, $required, 'class="crm-select2 big"' ); } } elseif ($fieldName == 'activity_details') { - $form->add('wysiwyg', $fieldName, $title, array('rows' => 4, 'cols' => 60), $required); + $form->add('wysiwyg', $fieldName, $title, ['rows' => 4, 'cols' => 60], $required); } elseif ($fieldName == 'activity_duration') { $form->add('text', $name, $title, $attributes, $required); @@ -2269,9 +2210,9 @@ public static function buildProfile( } elseif ($fieldName == 'case_status') { $form->add('select', $name, $title, - array( + [ '' => ts('- select -'), - ) + CRM_Case_BAO_Case::buildOptions('case_status_id', 'create'), + ] + CRM_Case_BAO_Case::buildOptions('case_status_id', 'create'), $required ); } @@ -2311,17 +2252,17 @@ public static function buildProfile( } //add the rules - if (in_array($fieldName, array( + if (in_array($fieldName, [ 'non_deductible_amount', 'total_amount', 'fee_amount', 'net_amount', - ))) { + ])) { $form->addRule($name, ts('Please enter a valid amount.'), 'money'); } if ($rule) { if (!($rule == 'email' && $mode == CRM_Profile_Form::MODE_SEARCH)) { - $form->addRule($name, ts('Please enter a valid %1', array(1 => $title)), $rule); + $form->addRule($name, ts('Please enter a valid %1', [1 => $title]), $rule); } } } @@ -2347,9 +2288,9 @@ public static function setProfileDefaults( ) { if (!$componentId) { //get the contact details - list($contactDetails, $options) = CRM_Contact_BAO_Contact::getHierContactDetails($contactId, $fields); + $contactDetails = CRM_Contact_BAO_Contact::getHierContactDetails($contactId, $fields); $details = CRM_Utils_Array::value($contactId, $contactDetails); - $multipleFields = array('website' => 'url'); + $multipleFields = ['website' => 'url']; //start of code to set the default values foreach ($fields as $name => $field) { @@ -2398,67 +2339,14 @@ public static function setProfileDefaults( $defaults[$fldName] = $details['worldregion_id']; } elseif ($customFieldId = CRM_Core_BAO_CustomField::getKeyID($name)) { - // @todo retrieving the custom fields here seems obsolete - $field holds more data for the fields. - $customFields = CRM_Core_BAO_CustomField::getFields(CRM_Utils_Array::value('contact_type', $details)); - - // hack to add custom data for components - $components = array('Contribution', 'Participant', 'Membership', 'Activity', 'Grant'); - foreach ($components as $value) { - $customFields = CRM_Utils_Array::crmArrayMerge($customFields, - CRM_Core_BAO_CustomField::getFieldsForImport($value) - ); - } - - switch ($customFields[$customFieldId]['html_type']) { - case 'Multi-Select State/Province': - case 'Multi-Select Country': - case 'AdvMulti-Select': - case 'Multi-Select': - $v = explode(CRM_Core_DAO::VALUE_SEPARATOR, $details[$name]); - foreach ($v as $item) { - if ($item) { - $defaults[$fldName][$item] = $item; - } - } - break; - - case 'CheckBox': - $v = explode(CRM_Core_DAO::VALUE_SEPARATOR, $details[$name]); - foreach ($v as $item) { - if ($item) { - $defaults[$fldName][$item] = 1; - // seems like we need this for QF style checkboxes in profile where its multiindexed - // CRM-2969 - $defaults["{$fldName}[{$item}]"] = 1; - } - } - break; - - case 'Autocomplete-Select': - if ($customFields[$customFieldId]['data_type'] == 'ContactReference') { - if (is_numeric($details[$name])) { - $defaults[$fldName . '_id'] = $details[$name]; - $defaults[$fldName] = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $details[$name], 'sort_name'); - } - } - else { - $label = CRM_Core_BAO_CustomOption::getOptionLabel($customFieldId, $details[$name]); - $defaults[$fldName . '_id'] = $details[$name]; - $defaults[$fldName] = $label; - } - break; - - default: - $defaults[$fldName] = $details[$name]; - break; - } + $defaults[$fldName] = self::reformatProfileDefaults($field, $details[$name]); } else { $defaults[$fldName] = $details[$name]; } } else { - $blocks = array('email', 'phone', 'im', 'openid'); + $blocks = ['email', 'phone', 'im', 'openid']; list($fieldName, $locTypeId, $phoneTypeId) = CRM_Utils_System::explode('-', $name, 3); if (!in_array($fieldName, $multipleFields)) { if (is_array($details)) { @@ -2533,10 +2421,17 @@ public static function setProfileDefaults( elseif (substr($fieldName, 0, 14) === 'address_custom' && CRM_Utils_Array::value(substr($fieldName, 8), $value) ) { - $defaults[$fldName] = $value[substr($fieldName, 8)]; + $defaults[$fldName] = self::reformatProfileDefaults($field, $value[substr($fieldName, 8)]); } } } + else { + if (substr($fieldName, 0, 14) === 'address_custom' && + CRM_Utils_Array::value(substr($fieldName, 8), $value) + ) { + $defaults[$fldName] = self::reformatProfileDefaults($field, $value[substr($fieldName, 8)]); + } + } } } } @@ -2597,7 +2492,7 @@ public static function setProfileDefaults( * associative array of profiles */ public static function getProfiles($types, $onlyPure = FALSE) { - $profiles = array(); + $profiles = []; $ufGroups = CRM_Core_PseudoConstant::get('CRM_Core_DAO_UFField', 'uf_group_id'); CRM_Utils_Hook::aclGroup(CRM_Core_Permission::ADMIN, NULL, 'civicrm_uf_group', $ufGroups, $ufGroups); @@ -2631,7 +2526,7 @@ public static function getValidProfiles($required, $optional = NULL) { return NULL; } - $profiles = array(); + $profiles = []; $ufGroups = CRM_Core_PseudoConstant::get('CRM_Core_DAO_UFField', 'uf_group_id'); CRM_Utils_Hook::aclGroup(CRM_Core_Permission::ADMIN, NULL, 'civicrm_uf_group', $ufGroups, $ufGroups); @@ -2673,7 +2568,7 @@ public static function checkValidProfile($ufId, $required = NULL) { CRM_Core_Permission::CREATE, NULL ); - $validProfile = array(); + $validProfile = []; if (!empty($profileFields)) { $fields = array_keys($profileFields); foreach ($fields as $val) { @@ -2727,16 +2622,16 @@ public static function setRegisterDefaults(&$fields, &$defaults) { public static function copy($id) { $maxId = CRM_Core_DAO::singleValueQuery("SELECT max(id) FROM civicrm_uf_group"); - $title = ts('[Copy id %1]', array(1 => $maxId + 1)); - $fieldsFix = array( - 'suffix' => array( + $title = ts('[Copy id %1]', [1 => $maxId + 1]); + $fieldsFix = [ + 'suffix' => [ 'title' => ' ' . $title, 'name' => '__Copy_id_' . ($maxId + 1) . '_', - ), - ); + ], + ]; - $copy = &CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFGroup', - array('id' => $id), + $copy = CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFGroup', + ['id' => $id], NULL, $fieldsFix ); @@ -2747,16 +2642,16 @@ public static function copy($id) { $copy->name = CRM_Utils_String::munge($copy->name, '_', 56) . "_{$copy->id}"; $copy->save(); - $copyUFJoin = &CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin', - array('uf_group_id' => $id), - array('uf_group_id' => $copy->id), + $copyUFJoin = CRM_Core_DAO::copyGeneric('CRM_Core_DAO_UFJoin', + ['uf_group_id' => $id], + ['uf_group_id' => $copy->id], NULL, 'entity_table' ); - $copyUFField = &CRM_Core_DAO::copyGeneric('CRM_Core_BAO_UFField', - array('uf_group_id' => $id), - array('uf_group_id' => $copy->id) + $copyUFField = CRM_Core_DAO::copyGeneric('CRM_Core_BAO_UFField', + ['uf_group_id' => $id], + ['uf_group_id' => $copy->id] ); $maxWeight = CRM_Utils_Weight::getMax('CRM_Core_DAO_UFJoin', NULL, 'weight'); @@ -2768,14 +2663,14 @@ public static function copy($id) { WHERE uf_group_id = %2 AND ( entity_id IS NULL OR entity_id <= 0 ) "; - $p = array( - 1 => array($maxWeight + 1, 'Integer'), - 2 => array($copy->id, 'Integer'), - ); + $p = [ + 1 => [$maxWeight + 1, 'Integer'], + 2 => [$copy->id, 'Integer'], + ]; CRM_Core_DAO::executeQuery($query, $p); if ($copy->is_reserved) { $query = "UPDATE civicrm_uf_group SET is_reserved = 0 WHERE id = %1"; - $params = array(1 => array($copy->id, 'Integer')); + $params = [1 => [$copy->id, 'Integer']]; CRM_Core_DAO::executeQuery($query, $params); } CRM_Utils_Hook::copy('UFGroup', $copy); @@ -2816,24 +2711,24 @@ public static function commonSendMail($contactID, &$values) { if (!$domainEmailAddress || $domainEmailAddress == 'info@EXAMPLE.ORG') { $fixUrl = CRM_Utils_System::url('civicrm/admin/domain', 'action=update&reset=1'); - CRM_Core_Error::fatal(ts('The site administrator needs to enter a valid \'FROM Email Address\' in Administer CiviCRM » Communications » FROM Email Addresses. The email address used may need to be a valid mail account with your email service provider.', array(1 => $fixUrl))); + CRM_Core_Error::fatal(ts('The site administrator needs to enter a valid \'FROM Email Address\' in Administer CiviCRM » Communications » FROM Email Addresses. The email address used may need to be a valid mail account with your email service provider.', [1 => $fixUrl])); } foreach ($emailList as $emailTo) { // FIXME: take the below out of the foreach loop CRM_Core_BAO_MessageTemplate::sendTemplate( - array( + [ 'groupName' => 'msg_tpl_workflow_uf', 'valueName' => 'uf_notify', 'contactId' => $contactID, - 'tplParams' => array( + 'tplParams' => [ 'displayName' => $displayName, 'currentDate' => date('r'), 'contactLink' => $contactLink, - ), + ], 'from' => "$domainEmailName <$domainEmailAddress>", 'toEmail' => $emailTo, - ) + ] ); } } @@ -2855,7 +2750,7 @@ public static function commonSendMail($contactID, &$values) { public function checkFieldsEmptyValues($gid, $cid, $params, $skipCheck = FALSE) { if ($gid) { if (CRM_Core_BAO_UFGroup::filterUFGroups($gid, $cid) || $skipCheck) { - $values = array(); + $values = []; $fields = CRM_Core_BAO_UFGroup::getFields($gid, FALSE, CRM_Core_Action::VIEW); CRM_Core_BAO_UFGroup::getValues($cid, $fields, $values, FALSE, $params, TRUE); @@ -2864,11 +2759,11 @@ public function checkFieldsEmptyValues($gid, $cid, $params, $skipCheck = FALSE) if (!empty($values) && !empty($email) ) { - $val = array( + $val = [ 'id' => $gid, 'values' => $values, 'email' => $email, - ); + ]; return $val; } } @@ -2884,7 +2779,7 @@ public function checkFieldsEmptyValues($gid, $cid, $params, $skipCheck = FALSE) * @param array $values * @param CRM_Core_Smarty $template */ - static public function profileDisplay($gid, $values, $template) { + public static function profileDisplay($gid, $values, $template) { $groupTitle = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $gid, 'title'); $template->assign('grouptitle', $groupTitle); if (count($values)) { @@ -2912,8 +2807,8 @@ public static function formatFields($params, $contactId = NULL) { $primaryLocationType = $defaultLocationType->id; } - $data = array(); - $locationType = array(); + $data = []; + $locationType = []; $count = 1; $primaryLocation = 0; foreach ($params as $key => $value) { @@ -2999,13 +2894,13 @@ public static function formatFields($params, $contactId = NULL) { $value = $date; } - $data['custom'][$customFieldID] = array( + $data['custom'][$customFieldID] = [ 'id' => $id, 'value' => $value, 'extends' => $customFields[$customFieldID]['extends'], 'type' => $customFields[$customFieldID]['data_type'], 'custom_field_id' => $customFieldID, - ); + ]; } } elseif ($key == 'edit') { @@ -3055,7 +2950,7 @@ public static function calculateGroupType($gId, $includeTypeValues = FALSE, $ign * list of calculated group type */ public static function _calculateGroupType($ufFields, $includeTypeValues = FALSE, $ignoreFieldId = NULL) { - $groupType = $groupTypeValues = $customFieldIds = array(); + $groupType = $groupTypeValues = $customFieldIds = []; if (!empty($ufFields)) { foreach ($ufFields as $fieldName => $fieldValue) { //ignore field from group type when provided. @@ -3084,7 +2979,7 @@ public static function _calculateGroupType($ufFields, $includeTypeValues = FALSE $groupTypeName = "{$customGroups->extends}Type"; if ($customGroups->extends == 'Participant' && $customGroups->extends_entity_column_id) { - $groupTypeName = CRM_Core_OptionGroup::getValue('custom_data_type', $customGroups->extends_entity_column_id, 'value', 'String', 'name'); + $groupTypeName = CRM_Core_PseudoConstant::getName('CRM_Core_DAO_CustomGroup', 'extends_entity_column_id', $customGroups->extends_entity_column_id); } foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, $customGroups->extends_entity_column_value) as $val) { @@ -3123,7 +3018,7 @@ public static function _calculateGroupType($ufFields, $includeTypeValues = FALSE * * @return bool */ - public static function updateGroupTypes($gId, $groupTypes = array()) { + public static function updateGroupTypes($gId, $groupTypes = []) { if (!is_array($groupTypes) || !$gId) { return FALSE; } @@ -3133,17 +3028,17 @@ public static function updateGroupTypes($gId, $groupTypes = array()) { return CRM_Core_DAO::setFieldValue('CRM_Core_DAO_UFGroup', $gId, 'group_type', 'null'); } - $componentGroupTypes = array('Contribution', 'Participant', 'Membership', 'Activity', 'Case', 'Grant'); - $validGroupTypes = array_merge(array( + $componentGroupTypes = ['Contribution', 'Participant', 'Membership', 'Activity', 'Case', 'Grant']; + $validGroupTypes = array_merge([ 'Contact', 'Individual', 'Organization', 'Household', - ), $componentGroupTypes, CRM_Contact_BAO_ContactType::subTypes()); + ], $componentGroupTypes, CRM_Contact_BAO_ContactType::subTypes()); - $gTypes = $gTypeValues = array(); + $gTypes = $gTypeValues = []; - $participantExtends = array('ParticipantRole', 'ParticipantEventName', 'ParticipantEventType'); + $participantExtends = ['ParticipantRole', 'ParticipantEventName', 'ParticipantEventType']; // Get valid group type and group subtypes foreach ($groupTypes as $groupType => $value) { if (in_array($groupType, $validGroupTypes) && !in_array($groupType, $gTypes)) { @@ -3229,7 +3124,7 @@ public static function encodeGroupType($coreTypes, $subTypes, $delim = CRM_Core_ */ public static function setComponentDefaults(&$fields, $componentId, $component, &$defaults, $isStandalone = FALSE) { if (!$componentId || - !in_array($component, array('Contribute', 'Membership', 'Event', 'Activity', 'Case', 'Grant')) + !in_array($component, ['Contribute', 'Membership', 'Event', 'Activity', 'Case', 'Grant']) ) { return; } @@ -3239,31 +3134,31 @@ public static function setComponentDefaults(&$fields, $componentId, $component, case 'Membership': $componentBAO = 'CRM_Member_BAO_Membership'; $componentBAOName = 'Membership'; - $componentSubType = array('membership_type_id'); + $componentSubType = ['membership_type_id']; break; case 'Contribute': $componentBAO = 'CRM_Contribute_BAO_Contribution'; $componentBAOName = 'Contribution'; - $componentSubType = array('financial_type_id'); + $componentSubType = ['financial_type_id']; break; case 'Event': $componentBAO = 'CRM_Event_BAO_Participant'; $componentBAOName = 'Participant'; - $componentSubType = array('role_id', 'event_id', 'event_type_id'); + $componentSubType = ['role_id', 'event_id', 'event_type_id']; break; case 'Activity': $componentBAO = 'CRM_Activity_BAO_Activity'; $componentBAOName = 'Activity'; - $componentSubType = array('activity_type_id'); + $componentSubType = ['activity_type_id']; break; case 'Case': $componentBAO = 'CRM_Case_BAO_Case'; $componentBAOName = 'Case'; - $componentSubType = array('case_type_id'); + $componentSubType = ['case_type_id']; break; case 'Grant': @@ -3273,16 +3168,16 @@ public static function setComponentDefaults(&$fields, $componentId, $component, break; } - $values = array(); - $params = array('id' => $componentId); + $values = []; + $params = ['id' => $componentId]; //get the component values. CRM_Core_DAO::commonRetrieve($componentBAO, $params, $values); if ($componentBAOName == 'Participant') { - $values += array('event_type_id' => CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $values['event_id'], 'event_type_id')); + $values += ['event_type_id' => CRM_Core_DAO::getFieldValue('CRM_Event_DAO_Event', $values['event_id'], 'event_type_id')]; } - $formattedGroupTree = array(); + $formattedGroupTree = []; foreach ($fields as $name => $field) { $fldName = $isStandalone ? $name : "field[$componentId][$name]"; @@ -3293,12 +3188,12 @@ public static function setComponentDefaults(&$fields, $componentId, $component, $noteDetails = CRM_Core_BAO_Note::getNote($componentId, 'civicrm_participant'); $defaults[$fldName] = array_pop($noteDetails); } - elseif (in_array($name, array( + elseif (in_array($name, [ 'financial_type', 'payment_instrument', 'participant_status', 'participant_role', - ))) { + ])) { $defaults[$fldName] = $values["{$name}_id"]; } elseif ($name == 'membership_type') { @@ -3313,10 +3208,10 @@ public static function setComponentDefaults(&$fields, $componentId, $component, elseif ($name == 'case_status') { $defaults[$fldName] = $values['case_status_id']; } - elseif (CRM_Core_BAO_CustomField::getKeyID($name, TRUE) !== array(NULL, NULL)) { + elseif (CRM_Core_BAO_CustomField::getKeyID($name, TRUE) !== [NULL, NULL]) { if (empty($formattedGroupTree)) { //get the groupTree as per subTypes. - $groupTree = array(); + $groupTree = []; foreach ($componentSubType as $subType) { $subTree = CRM_Core_BAO_CustomGroup::getTree($componentBAOName, NULL, $componentId, 0, $values[$subType] @@ -3371,48 +3266,6 @@ public static function setComponentDefaults(&$fields, $componentId, $component, } } - /** - * @param array|string $profiles - name of profile(s) to create links for - * @param array $appendProfiles - * Name of profile(s) to append to each link. - * - * @return array - */ - public static function getCreateLinks($profiles = '', $appendProfiles = array()) { - // Default to contact profiles - if (!$profiles) { - $profiles = array('new_individual', 'new_organization', 'new_household'); - } - $profiles = (array) $profiles; - $toGet = array_merge($profiles, (array) $appendProfiles); - $retrieved = civicrm_api3('uf_group', 'get', array( - 'name' => array('IN' => $toGet), - 'is_active' => 1, - )); - $links = $append = array(); - if (!empty($retrieved['values'])) { - foreach ($retrieved['values'] as $id => $profile) { - if (in_array($profile['name'], $profiles)) { - $links[] = array( - 'label' => $profile['title'], - 'url' => CRM_Utils_System::url('civicrm/profile/create', "reset=1&context=dialog&gid=$id", - NULL, NULL, FALSE, FALSE, TRUE), - 'type' => ucfirst(str_replace('new_', '', $profile['name'])), - ); - } - else { - $append[] = $id; - } - } - foreach ($append as $id) { - foreach ($links as &$link) { - $link['url'] .= ",$id"; - } - } - } - return $links; - } - /** * Retrieve groups of profiles. * @@ -3423,7 +3276,7 @@ public static function getCreateLinks($profiles = '', $appendProfiles = array()) * returns array */ public static function profileGroups($profileID) { - $groupTypes = array(); + $groupTypes = []; $profileTypes = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileID, 'group_type'); if ($profileTypes) { $groupTypeParts = explode(CRM_Core_DAO::VALUE_SEPARATOR, $profileTypes); @@ -3446,7 +3299,7 @@ public static function profileGroups($profileID) { */ public static function getDoubleOptInGroupIds(&$params, $contactId = NULL) { $config = CRM_Core_Config::singleton(); - $subscribeGroupIds = array(); + $subscribeGroupIds = []; // process further only if profileDoubleOptIn enabled and if groups exist if (!array_key_exists('group', $params) || @@ -3471,7 +3324,7 @@ public static function getDoubleOptInGroupIds(&$params, $contactId = NULL) { } //do check for already subscriptions. - $contactGroups = array(); + $contactGroups = []; if ($contactId) { $query = " SELECT group_id @@ -3479,7 +3332,7 @@ public static function getDoubleOptInGroupIds(&$params, $contactId = NULL) { WHERE status = 'Added' AND contact_id = %1"; - $dao = CRM_Core_DAO::executeQuery($query, array(1 => array($contactId, 'Integer'))); + $dao = CRM_Core_DAO::executeQuery($query, [1 => [$contactId, 'Integer']]); while ($dao->fetch()) { $contactGroups[$dao->group_id] = $dao->group_id; } @@ -3521,12 +3374,12 @@ public static function getDoubleOptInGroupIds(&$params, $contactId = NULL) { public static function checkForMixProfiles($profileIds) { $mixProfile = FALSE; - $contactTypes = array('Individual', 'Household', 'Organization'); + $contactTypes = ['Individual', 'Household', 'Organization']; $subTypes = CRM_Contact_BAO_ContactType::subTypes(); - $components = array('Contribution', 'Participant', 'Membership', 'Activity', 'Grant'); + $components = ['Contribution', 'Participant', 'Membership', 'Activity', 'Grant']; - $typeCount = array('ctype' => array(), 'subtype' => array()); + $typeCount = ['ctype' => [], 'subtype' => []]; foreach ($profileIds as $gid) { $profileType = CRM_Core_BAO_UFField::getProfileType($gid); // ignore profile of type Contact @@ -3596,17 +3449,17 @@ public static function showOverlayProfile() { * group type values */ public static function groupTypeValues($profileId, $groupType = NULL) { - $groupTypeValue = array(); + $groupTypeValue = []; $groupTypes = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_UFGroup', $profileId, 'group_type'); $groupTypeParts = explode(CRM_Core_DAO::VALUE_SEPARATOR, $groupTypes); if (empty($groupTypeParts[1])) { return $groupTypeValue; } - $participantExtends = array('ParticipantRole', 'ParticipantEventName', 'ParticipantEventType'); + $participantExtends = ['ParticipantRole', 'ParticipantEventName', 'ParticipantEventType']; foreach (explode(',', $groupTypeParts[1]) as $groupTypeValues) { - $values = array(); + $values = []; $valueParts = explode(':', $groupTypeValues); if ($groupType && ($valueParts[0] != "{$groupType}Type" || @@ -3669,7 +3522,7 @@ public static function getBatchProfiles() { FROM civicrm_uf_group WHERE name IN ('contribution_batch_entry', 'membership_batch_entry')"; $dao = CRM_Core_DAO::executeQuery($query); - $profileIds = array(); + $profileIds = []; while ($dao->fetch()) { $profileIds[$dao->id] = $dao->id; } @@ -3677,15 +3530,15 @@ public static function getBatchProfiles() { } /** - * @todo what do I do? * @param $source * @param $destination * @param bool $returnMultiSummaryFields * * @return array|null + * @todo what do I do? */ public static function shiftMultiRecordFields(&$source, &$destination, $returnMultiSummaryFields = FALSE) { - $multiSummaryFields = $returnMultiSummaryFields ? array() : NULL; + $multiSummaryFields = $returnMultiSummaryFields ? [] : NULL; foreach ($source as $field => $properties) { if (!CRM_Core_BAO_CustomField::getKeyID($field)) { continue; @@ -3734,4 +3587,63 @@ public static function reformatProfileFields(&$fields) { } } + /** + * Get the frontend_title for the profile, falling back on 'title' if none. + * + * @param int $profileID + * + * @return string + * + * @throws \CiviCRM_API3_Exception + */ + public static function getFrontEndTitle(int $profileID) { + $profile = civicrm_api3('UFGroup', 'getsingle', ['id' => $profileID, 'return' => ['title', 'frontend_title']]); + return $profile['frontend_title'] ?? $profile['title']; + } + + /** + * This function is used to format the profile default values. + * + * @param array $field + * Associated array of profile fields to render. + * @param string $value + * Value to render + * + * @return $defaults + * String or array, depending on the html type + */ + public static function reformatProfileDefaults($field, $value) { + $defaults = []; + + switch ($field['html_type']) { + case 'Multi-Select State/Province': + case 'Multi-Select Country': + case 'Multi-Select': + $v = explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($value)); + foreach ($v as $item) { + if ($item) { + $defaults[$item] = $item; + } + } + break; + + case 'CheckBox': + $v = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value); + foreach ($v as $item) { + if ($item) { + $defaults[$item] = 1; + // seems like we need this for QF style checkboxes in profile where its multiindexed + // CRM-2969 + $defaults["[{$item}]"] = 1; + } + } + break; + + default: + $defaults = $value; + break; + } + return $defaults; + } + } diff --git a/CRM/Core/Controller.php b/CRM/Core/Controller.php index 96f7d54..32129ef 100644 --- a/CRM/Core/Controller.php +++ b/CRM/Core/Controller.php @@ -1,27 +1,11 @@ _key)) { - CRM_Core_Session::registerAndRetrieveSessionObjects(array( + CRM_Core_Session::registerAndRetrieveSessionObjects([ "_{$name}_container", - array('CiviCRM', $this->_scope), - )); + ['CiviCRM', $this->_scope], + ]); } parent::__construct($name, $modal); @@ -239,7 +225,7 @@ public function __construct( $this->_print = CRM_Core_Smarty::PRINT_NOFORM; } // Respond with JSON if in AJAX context (also support legacy value '6') - elseif (in_array($snippet, array(CRM_Core_Smarty::PRINT_JSON, 6))) { + elseif (in_array($snippet, [CRM_Core_Smarty::PRINT_JSON, 6])) { $this->_print = CRM_Core_Smarty::PRINT_JSON; $this->_QFResponseType = 'json'; } @@ -275,12 +261,10 @@ public function __construct( } public function fini() { - CRM_Core_BAO_Cache::storeSessionToCache(array( - "_{$this->_name}_container", - array('CiviCRM', $this->_scope), - ), - TRUE - ); + CRM_Core_BAO_Cache::storeSessionToCache([ + "_{$this->_name}_container", + ['CiviCRM', $this->_scope], + ], TRUE); } /** @@ -382,7 +366,7 @@ public function validate() { * @param array $uploadNames for the various upload buttons (note u can have more than 1 upload) */ public function addActions($uploadDirectory = NULL, $uploadNames = NULL) { - $names = array( + $names = [ 'display' => 'CRM_Core_QuickForm_Action_Display', 'next' => 'CRM_Core_QuickForm_Action_Next', 'back' => 'CRM_Core_QuickForm_Action_Back', @@ -393,7 +377,7 @@ public function addActions($uploadDirectory = NULL, $uploadNames = NULL) { 'done' => 'CRM_Core_QuickForm_Action_Done', 'jump' => 'CRM_Core_QuickForm_Action_Jump', 'submit' => 'CRM_Core_QuickForm_Action_Submit', - ); + ]; foreach ($names as $name => $classPath) { $action = new $classPath($this->_stateMachine); @@ -535,12 +519,12 @@ public function get($name) { * @return array */ public function wizardHeader($currentPageName) { - $wizard = array(); - $wizard['steps'] = array(); + $wizard = []; + $wizard['steps'] = []; $count = 0; foreach ($this->_pages as $name => $page) { $count++; - $wizard['steps'][] = array( + $wizard['steps'][] = [ 'name' => $name, 'title' => $page->getTitle(), //'link' => $page->getLink ( ), @@ -549,7 +533,7 @@ public function wizardHeader($currentPageName) { 'valid' => TRUE, 'stepNumber' => $count, 'collapsed' => FALSE, - ); + ]; if ($name == $currentPageName) { $wizard['currentStepNumber'] = $count; @@ -570,7 +554,7 @@ public function wizardHeader($currentPageName) { * @param array $wizard */ public function addWizardStyle(&$wizard) { - $wizard['style'] = array( + $wizard['style'] = [ 'barClass' => '', 'stepPrefixCurrent' => '»', 'stepPrefixPast' => '✔', @@ -579,7 +563,7 @@ public function addWizardStyle(&$wizard) { 'subStepPrefixPast' => '  ', 'subStepPrefixFuture' => '  ', 'showTitle' => 1, - ); + ]; } /** diff --git a/CRM/Core/Page/AJAX/Location.php b/CRM/Core/Page/AJAX/Location.php index b15ecd1..a976280 100644 --- a/CRM/Core/Page/AJAX/Location.php +++ b/CRM/Core/Page/AJAX/Location.php @@ -1,34 +1,18 @@ get('userID')); + ->get('userID')); if (empty($user) || (CRM_Utils_Request::retrieve('cs', 'String', $form, FALSE) && !CRM_Contact_BAO_Contact_Permission::validateChecksumContact($user, CRM_Core_DAO::$_nullObject, FALSE)) ) { CRM_Utils_System::civiExit(); @@ -63,12 +47,11 @@ public static function getPermissionedLocation() { CRM_Utils_System::civiExit(); } - $values = array(); - $entityBlock = array('contact_id' => $cid); + $values = []; + $entityBlock = ['contact_id' => $cid]; $location = CRM_Core_BAO_Location::getValues($entityBlock); - $config = CRM_Core_Config::singleton(); - $addressSequence = array_flip($config->addressSequence()); + $addressSequence = array_flip(CRM_Utils_Address::sequence(\Civi::settings()->get('address_format'))); $profileFields = CRM_Core_BAO_UFGroup::getFields($ufId, FALSE, CRM_Core_Action::VIEW, NULL, NULL, FALSE, NULL, FALSE, NULL, CRM_Core_Permission::CREATE, NULL @@ -79,30 +62,30 @@ public static function getPermissionedLocation() { if (is_array($values) && !empty($values)) { $locType = $values[1]['location_type_id']; if ($fld == 'email') { - $elements["onbehalf_{$fld}-{$locType}"] = array( + $elements["onbehalf_{$fld}-{$locType}"] = [ 'type' => 'Text', 'value' => $location[$fld][1][$fld], - ); + ]; unset($profileFields["{$fld}-{$locType}"]); } elseif ($fld == 'phone') { $phoneTypeId = $values[1]['phone_type_id']; - $elements["onbehalf_{$fld}-{$locType}-{$phoneTypeId}"] = array( + $elements["onbehalf_{$fld}-{$locType}-{$phoneTypeId}"] = [ 'type' => 'Text', 'value' => $location[$fld][1][$fld], - ); + ]; unset($profileFields["{$fld}-{$locType}-{$phoneTypeId}"]); } elseif ($fld == 'im') { $providerId = $values[1]['provider_id']; - $elements["onbehalf_{$fld}-{$locType}"] = array( + $elements["onbehalf_{$fld}-{$locType}"] = [ 'type' => 'Text', 'value' => $location[$fld][1][$fld], - ); - $elements["onbehalf_{$fld}-{$locType}provider_id"] = array( + ]; + $elements["onbehalf_{$fld}-{$locType}provider_id"] = [ 'type' => 'Select', 'value' => $location[$fld][1]['provider_id'], - ); + ]; unset($profileFields["{$fld}-{$locType}-{$providerId}"]); } } @@ -111,20 +94,20 @@ public static function getPermissionedLocation() { if (!empty($website)) { foreach ($website as $key => $val) { $websiteTypeId = $values[1]['website_type_id']; - $elements["onbehalf_url-1"] = array( + $elements["onbehalf_url-1"] = [ 'type' => 'Text', 'value' => $website[1]['url'], - ); - $elements["onbehalf_url-1-website_type_id"] = array( + ]; + $elements["onbehalf_url-1-website_type_id"] = [ 'type' => 'Select', 'value' => $website[1]['website_type_id'], - ); + ]; unset($profileFields["url-1"]); } } $locTypeId = isset($location['address'][1]) ? $location['address'][1]['location_type_id'] : NULL; - $addressFields = array( + $addressFields = [ 'street_address', 'supplemental_address_1', 'supplemental_address_2', @@ -134,27 +117,27 @@ public static function getPermissionedLocation() { 'county', 'state_province', 'country', - ); + ]; foreach ($addressFields as $field) { if (array_key_exists($field, $addressSequence)) { $addField = $field; $type = 'Text'; - if (in_array($field, array('state_province', 'country', 'county'))) { + if (in_array($field, ['state_province', 'country', 'county'])) { $addField = "{$field}_id"; $type = 'Select'; } - $elements["onbehalf_{$field}-{$locTypeId}"] = array( + $elements["onbehalf_{$field}-{$locTypeId}"] = [ 'type' => $type, 'value' => isset($location['address'][1]) ? CRM_Utils_Array::value($addField, $location['address'][1]) : NULL, - ); + ]; unset($profileFields["{$field}-{$locTypeId}"]); } } //set custom field defaults - $defaults = array(); + $defaults = []; CRM_Core_BAO_UFGroup::setProfileDefaults($cid, $profileFields, $defaults, TRUE, NULL, NULL, TRUE); if (!empty($defaults)) { @@ -171,7 +154,7 @@ public static function getPermissionedLocation() { $elements["onbehalf_{$key}"]['value'][$k] = $v; } } - elseif (strstr($htmlType, 'Multi-Select') && $htmlType != 'AdvMulti-Select') { + elseif (strstr($htmlType, 'Multi-Select')) { $elements["onbehalf_{$key}"]['type'] = 'Multi-Select'; $elements["onbehalf_{$key}"]['value'] = array_values($defaults[$key]); } @@ -217,32 +200,31 @@ public static function getLocBlock() { // i wish i could retrieve loc block info based on loc_block_id, // Anyway, lets retrieve an event which has loc_block_id set to 'lbid'. if ($_REQUEST['lbid']) { - $params = array('1' => array($_REQUEST['lbid'], 'Integer')); + $params = ['1' => [$_REQUEST['lbid'], 'Integer']]; $eventId = CRM_Core_DAO::singleValueQuery('SELECT id FROM civicrm_event WHERE loc_block_id=%1 LIMIT 1', $params); } // now lets use the event-id obtained above, to retrieve loc block information. if ($eventId) { - $params = array('entity_id' => $eventId, 'entity_table' => 'civicrm_event'); + $params = ['entity_id' => $eventId, 'entity_table' => 'civicrm_event']; // second parameter is of no use, but since required, lets use the same variable. $location = CRM_Core_BAO_Location::getValues($params, $params); } - $result = array(); + $result = []; $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME, 'address_options', TRUE, NULL, TRUE ); // lets output only required fields. foreach ($addressOptions as $element => $isSet) { - if ($isSet && (!in_array($element, array( - 'im', - 'openid', - ))) - ) { - if (in_array($element, array( + if ($isSet && (!in_array($element, [ + 'im', + 'openid', + ]))) { + if (in_array($element, [ 'country', 'state_province', 'county', - ))) { + ])) { $element .= '_id'; } elseif ($element == 'address_name') { @@ -251,29 +233,29 @@ public static function getLocBlock() { $fld = "address[1][{$element}]"; $value = CRM_Utils_Array::value($element, $location['address'][1]); $value = $value ? $value : ""; - $result[str_replace(array( + $result[str_replace([ '][', '[', "]", - ), array('_', '_', ''), $fld)] = $value; + ], ['_', '_', ''], $fld)] = $value; } } - foreach (array( - 'email', - 'phone_type_id', - 'phone', - ) as $element) { + foreach ([ + 'email', + 'phone_type_id', + 'phone', + ] as $element) { $block = ($element == 'phone_type_id') ? 'phone' : $element; for ($i = 1; $i < 3; $i++) { $fld = "{$block}[{$i}][{$element}]"; $value = CRM_Utils_Array::value($element, $location[$block][$i]); $value = $value ? $value : ""; - $result[str_replace(array( + $result[str_replace([ '][', '[', "]", - ), array('_', '_', ''), $fld)] = $value; + ], ['_', '_', ''], $fld)] = $value; } } diff --git a/CRM/Grant/BAO/Query.php b/CRM/Grant/BAO/Query.php index e7ff050..5d3d94b 100644 --- a/CRM/Grant/BAO/Query.php +++ b/CRM/Grant/BAO/Query.php @@ -1,43 +1,28 @@ _where[$grouping][] = "civicrm_grant.application_received_date IS NULL"; $query->_qill[$grouping][] = ts("Grant Application Received Date is NULL"); $query->_tables['civicrm_grant'] = $query->_whereTables['civicrm_grant'] = 1; @@ -207,7 +190,7 @@ public static function whereClauseSingle(&$values, &$query) { $query->_tables['civicrm_grant'] = $query->_whereTables['civicrm_grant'] = 1; list($qillop, $qillVal) = CRM_Contact_BAO_Query::buildQillForFieldValue('CRM_Grant_DAO_Grant', $name, $value, $op); - $query->_qill[$grouping][] = ts("%1 %2 %3", array(1 => $label, 2 => $qillop, 3 => $qillVal)); + $query->_qill[$grouping][] = ts("%1 %2 %3", [1 => $label, 2 => $qillop, 3 => $qillVal]); $query->_tables['civicrm_grant'] = $query->_whereTables['civicrm_grant'] = 1; return; @@ -215,15 +198,15 @@ public static function whereClauseSingle(&$values, &$query) { case 'grant_report_received': if ($value == 1) { - $yesNo = 'Yes'; + $yesNo = ts('Yes'); $query->_where[$grouping][] = "civicrm_grant.grant_report_received $op $value"; } elseif ($value == 0) { - $yesNo = 'No'; + $yesNo = ts('No'); $query->_where[$grouping][] = "civicrm_grant.grant_report_received IS NULL"; } - $query->_qill[$grouping][] = "Grant Report Received = $yesNo "; + $query->_qill[$grouping][] = ts('Grant Report Received = %1', [1 => $yesNo]); $query->_tables['civicrm_grant'] = $query->_whereTables['civicrm_grant'] = 1; return; @@ -295,7 +278,7 @@ public static function defaultReturnProperties( ) { $properties = NULL; if ($mode & CRM_Contact_BAO_Query::MODE_GRANT) { - $properties = array( + $properties = [ 'contact_type' => 1, 'contact_sub_type' => 1, 'sort_name' => 1, @@ -307,76 +290,72 @@ public static function defaultReturnProperties( 'grant_report_received' => 1, 'grant_money_transfer_date' => 1, 'grant_note' => 1, - ); + ]; } return $properties; } + /** + * Get the metadata for fields to be included on the grant search form. + * + * @throws \CiviCRM_API3_Exception + */ + public static function getSearchFieldMetadata() { + $fields = [ + 'grant_report_received', + 'grant_application_received_date', + 'grant_decision_date', + 'grant_money_transfer_date', + 'grant_due_date', + ]; + $metadata = civicrm_api3('Grant', 'getfields', [])['values']; + return array_intersect_key($metadata, array_flip($fields)); + } + + /** + * Transitional function for specifying which fields the tpl can iterate through. + */ + public static function getTemplateHandlableSearchFields() { + return array_diff_key(self::getSearchFieldMetadata(), ['grant_report_received' => 1]); + } + /** * Add all the elements shared between grant search and advanaced search. * * - * @param CRM_Core_Form $form + * @param \CRM_Grant_Form_Search $form * * @return void */ public static function buildSearchForm(&$form) { $grantType = CRM_Core_OptionGroup::values('grant_type'); + $form->addSearchFieldMetadata(['Grant' => self::getSearchFieldMetadata()]); + $form->addFormFieldsFromMetadata(); + $form->assign('grantSearchFields', self::getTemplateHandlableSearchFields()); $form->add('select', 'grant_type_id', ts('Grant Type'), $grantType, FALSE, - array('id' => 'grant_type_id', 'multiple' => 'multiple', 'class' => 'crm-select2') + ['id' => 'grant_type_id', 'multiple' => 'multiple', 'class' => 'crm-select2'] ); $grantStatus = CRM_Core_OptionGroup::values('grant_status'); $form->add('select', 'grant_status_id', ts('Grant Status'), $grantStatus, FALSE, - array('id' => 'grant_status_id', 'multiple' => 'multiple', 'class' => 'crm-select2') + ['id' => 'grant_status_id', 'multiple' => 'multiple', 'class' => 'crm-select2'] ); - - $form->addDate('grant_application_received_date_low', ts('App. Received Date - From'), FALSE, array('formatType' => 'searchDate')); - $form->addDate('grant_application_received_date_high', ts('To'), FALSE, array('formatType' => 'searchDate')); - - $form->addElement('checkbox', 'grant_application_received_notset', ts('Date is not set'), NULL); - - $form->addDate('grant_money_transfer_date_low', ts('Money Sent Date - From'), FALSE, array('formatType' => 'searchDate')); - $form->addDate('grant_money_transfer_date_high', ts('To'), FALSE, array('formatType' => 'searchDate')); - + $form->addElement('checkbox', 'grant_application_received_date_notset', ts('Date is not set'), NULL); $form->addElement('checkbox', 'grant_money_transfer_date_notset', ts('Date is not set'), NULL); - - $form->addDate('grant_due_date_low', ts('Report Due Date - From'), FALSE, array('formatType' => 'searchDate')); - $form->addDate('grant_due_date_high', ts('To'), FALSE, array('formatType' => 'searchDate')); - $form->addElement('checkbox', 'grant_due_date_notset', ts('Date is not set'), NULL); - - $form->addDate('grant_decision_date_low', ts('Grant Decision Date - From'), FALSE, array('formatType' => 'searchDate')); - $form->addDate('grant_decision_date_high', ts('To'), FALSE, array('formatType' => 'searchDate')); - $form->addElement('checkbox', 'grant_decision_date_notset', ts('Date is not set'), NULL); - $form->addYesNo('grant_report_received', ts('Grant report received?'), TRUE); - - $form->add('text', 'grant_amount_low', ts('Minimum Amount'), array('size' => 8, 'maxlength' => 8)); - $form->addRule('grant_amount_low', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('9.99', ' '))), 'money'); + $form->add('text', 'grant_amount_low', ts('Minimum Amount'), ['size' => 8, 'maxlength' => 8]); + $form->addRule('grant_amount_low', ts('Please enter a valid money value (e.g. %1).', [1 => CRM_Utils_Money::format('9.99', ' ')]), 'money'); - $form->add('text', 'grant_amount_high', ts('Maximum Amount'), array('size' => 8, 'maxlength' => 8)); - $form->addRule('grant_amount_high', ts('Please enter a valid money value (e.g. %1).', array(1 => CRM_Utils_Money::format('99.99', ' '))), 'money'); + $form->add('text', 'grant_amount_high', ts('Maximum Amount'), ['size' => 8, 'maxlength' => 8]); + $form->addRule('grant_amount_high', ts('Please enter a valid money value (e.g. %1).', [1 => CRM_Utils_Money::format('99.99', ' ')]), 'money'); - self::addCustomFormFields($form, array('Grant')); + self::addCustomFormFields($form, ['Grant']); $form->assign('validGrant', TRUE); } - /** - * @param $row - * @param int $id - */ - public static function searchAction(&$row, $id) { - } - - /** - * @param $tables - */ - public static function tableNames(&$tables) { - } - } diff --git a/CRM/Grant/Info.php b/CRM/Grant/Info.php index d782481..9297b98 100644 --- a/CRM/Grant/Info.php +++ b/CRM/Grant/Info.php @@ -1,27 +1,11 @@ 'CiviGrant', 'translatedName' => ts('CiviGrant'), 'title' => 'CiviCRM Grant Management Engine', 'path' => 'CRM_Grant_', 'search' => 1, 'showActivitiesInCore' => 1, - ); + ]; } - /** * @inheritDoc * @param bool $getAllUnconditionally @@ -67,23 +51,23 @@ public function getInfo() { * @return array */ public function getPermissions($getAllUnconditionally = FALSE, $descriptions = FALSE) { - $permissions = array( - 'access CiviGrant' => array( + $permissions = [ + 'access CiviGrant' => [ ts('access CiviGrant'), ts('View all grants'), - ), - 'edit grants' => array( + ], + 'edit grants' => [ ts('edit grants'), ts('Create and update grants'), - ), - 'submit online grant application' => array( + ], + 'submit online grant application' => [ ts('submit online grant application'), - ), - 'delete in CiviGrant' => array( + ], + 'delete in CiviGrant' => [ ts('delete in CiviGrant'), ts('Delete grants'), - ), - ); + ], + ]; if (!$descriptions) { foreach ($permissions as $name => $attr) { @@ -121,11 +105,19 @@ public function getUserDashboardObject() { * @return array */ public function registerTab() { - return array( + return [ 'title' => ts('Grants'), 'url' => 'grant', - 'weight' => 50, - ); + 'weight' => 60, + ]; + } + + /** + * @inheritDoc + * @return string + */ + public function getIcon() { + return 'crm-i fa-money'; } /** @@ -133,10 +125,10 @@ public function registerTab() { * @return array */ public function registerAdvancedSearchPane() { - return array( + return [ 'title' => ts('Grants'), 'weight' => 50, - ); + ]; } /** @@ -155,14 +147,14 @@ public function creatNewShortcut(&$shortCuts) { if (CRM_Core_Permission::check('access CiviGrant') && CRM_Core_Permission::check('edit grants') ) { - $shortCuts = array_merge($shortCuts, array( - array( + $shortCuts = array_merge($shortCuts, [ + [ 'path' => 'civicrm/grant/add', 'query' => "reset=1&action=add&context=standalone", 'ref' => 'new-grant', 'title' => ts('Grant'), - ), - )); + ], + ]); } } diff --git a/CRM/UF/Page/Group.php b/CRM/UF/Page/Group.php index 4495a65..683331b 100644 --- a/CRM/UF/Page/Group.php +++ b/CRM/UF/Page/Group.php @@ -1,34 +1,18 @@ array( + self::$_actionLinks = [ + CRM_Core_Action::BROWSE => [ 'name' => ts('Fields'), 'url' => 'civicrm/admin/uf/group/field', 'qs' => 'reset=1&action=browse&gid=%%id%%', 'title' => ts('View and Edit Fields'), - ), - CRM_Core_Action::UPDATE => array( + ], + CRM_Core_Action::UPDATE => [ 'name' => ts('Settings'), 'url' => 'civicrm/admin/uf/group/update', 'qs' => 'action=update&id=%%id%%&context=group', 'title' => ts('Edit CiviCRM Profile Group'), - ), - CRM_Core_Action::PREVIEW => array( + ], + CRM_Core_Action::PREVIEW => [ 'name' => ts('Preview'), 'url' => 'civicrm/admin/uf/group', 'qs' => 'action=preview&id=%%id%%&field=0&context=group', 'title' => ts('Edit CiviCRM Profile Group'), - ), - CRM_Core_Action::ADD => array( + ], + CRM_Core_Action::ADD => [ 'name' => ts('Use - Create Mode'), 'url' => 'civicrm/profile/create', 'qs' => 'gid=%%id%%&reset=1', 'title' => ts('Use - Create Mode'), 'fe' => TRUE, - ), - CRM_Core_Action::ADVANCED => array( + ], + CRM_Core_Action::ADVANCED => [ 'name' => ts('Use - Edit Mode'), 'url' => 'civicrm/profile/edit', 'qs' => 'gid=%%id%%&reset=1', 'title' => ts('Use - Edit Mode'), 'fe' => TRUE, - ), - CRM_Core_Action::BASIC => array( + ], + CRM_Core_Action::BASIC => [ 'name' => ts('Use - Listings Mode'), 'url' => 'civicrm/profile', 'qs' => 'gid=%%id%%&reset=1', 'title' => ts('Use - Listings Mode'), 'fe' => TRUE, - ), - CRM_Core_Action::DISABLE => array( + ], + CRM_Core_Action::DISABLE => [ 'name' => ts('Disable'), 'ref' => 'crm-enable-disable', 'title' => ts('Disable CiviCRM Profile Group'), - ), - CRM_Core_Action::ENABLE => array( + ], + CRM_Core_Action::ENABLE => [ 'name' => ts('Enable'), 'ref' => 'crm-enable-disable', 'title' => ts('Enable CiviCRM Profile Group'), - ), - CRM_Core_Action::DELETE => array( + ], + CRM_Core_Action::DELETE => [ 'name' => ts('Delete'), 'url' => 'civicrm/admin/uf/group', 'qs' => 'action=delete&id=%%id%%', 'title' => ts('Delete CiviCRM Profile Group'), - ), - CRM_Core_Action::PROFILE => array( - 'name' => ts('HTML Form Snippet'), - 'url' => 'civicrm/admin/uf/group', - 'qs' => 'action=profile&gid=%%id%%', - 'title' => ts('HTML Form Snippet for this Profile'), - ), - CRM_Core_Action::COPY => array( + ], + CRM_Core_Action::COPY => [ 'name' => ts('Copy'), 'url' => 'civicrm/admin/uf/group', 'qs' => 'action=copy&gid=%%id%%', 'title' => ts('Make a Copy of CiviCRM Profile Group'), 'extra' => 'onclick = "return confirm(\'' . $copyExtra . '\');"', - ), - ); + ], + ]; $allowRemoteSubmit = Civi::settings()->get('remote_profile_submissions'); if ($allowRemoteSubmit) { - self::$_actionLinks[CRM_Core_Action::PROFILE] = array( + self::$_actionLinks[CRM_Core_Action::PROFILE] = [ 'name' => ts('HTML Form Snippet'), 'url' => 'civicrm/admin/uf/group', 'qs' => 'action=profile&gid=%%id%%', 'title' => ts('HTML Form Snippet for this Profile'), - ); + ]; } } return self::$_actionLinks; @@ -151,10 +129,6 @@ public static function &actionLinks() { * This method is called after the page is created. It checks for the * type of action and executes that action. * Finally it calls the parent's run method. - * - * @param - * - * @return void */ public function run() { // get the requested action @@ -166,7 +140,7 @@ public function run() { // assign vars to templates $this->assign('action', $action); - $this->assign('selectedChild', CRM_Utils_Request::retrieve('selectedChild', 'String', $this)); + $this->assign('selectedChild', CRM_Utils_Request::retrieve('selectedChild', 'Alphanumeric', $this)); $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE, 0 ); @@ -188,7 +162,7 @@ public function run() { } elseif ($action & CRM_Core_Action::PROFILE) { $this->profile(); - CRM_Utils_System::setTitle(ts('%1 - HTML Form Snippet', array(1 => $this->_title))); + CRM_Utils_System::setTitle(ts('%1 - HTML Form Snippet', [1 => $this->_title])); } elseif ($action & CRM_Core_Action::PREVIEW) { $this->preview($id, $action); @@ -319,7 +293,7 @@ public function edit($id, $action) { * @return void */ public function browse($action = NULL) { - $ufGroup = array(); + $ufGroup = []; $allUFGroups = CRM_Core_BAO_UFGroup::getModuleUFGroup(); if (empty($allUFGroups)) { return; @@ -329,7 +303,7 @@ public function browse($action = NULL) { CRM_Utils_Hook::aclGroup(CRM_Core_Permission::ADMIN, NULL, 'civicrm_uf_group', $ufGroups, $allUFGroups); foreach ($allUFGroups as $id => $value) { - $ufGroup[$id] = array(); + $ufGroup[$id] = []; $ufGroup[$id]['id'] = $id; $ufGroup[$id]['title'] = $value['title']; $ufGroup[$id]['frontend_title'] = $value['frontend_title']; @@ -377,7 +351,7 @@ public function browse($action = NULL) { $ufGroup[$id]['group_type'] = self::formatGroupTypes($groupTypes); $ufGroup[$id]['action'] = CRM_Core_Action::formLink(self::actionLinks(), $action, - array('id' => $id), + ['id' => $id], ts('more'), FALSE, 'ufGroup.row.actions', @@ -412,7 +386,7 @@ public function preview($id, $action) { * @param $action */ public function setContext($id, $action) { - $context = CRM_Utils_Request::retrieve('context', 'String', $this); + $context = CRM_Utils_Request::retrieve('context', 'Alphanumeric', $this); //we need to differentiate context for update and preview profile. if (!$context && !($action & (CRM_Core_Action::UPDATE | CRM_Core_Action::PREVIEW))) { @@ -436,7 +410,7 @@ public function setContext($id, $action) { * @return array */ public static function extractGroupTypes($groupType) { - $returnGroupTypes = array(); + $returnGroupTypes = []; if (!$groupType) { return $returnGroupTypes; } @@ -448,7 +422,7 @@ public static function extractGroupTypes($groupType) { if (!empty($groupTypeParts[1])) { foreach (explode(',', $groupTypeParts[1]) as $typeValue) { - $groupTypeValues = $valueLabels = array(); + $groupTypeValues = $valueLabels = []; $valueParts = explode(':', $typeValue); $typeName = NULL; switch ($valueParts[0]) { @@ -500,7 +474,7 @@ public static function extractGroupTypes($groupType) { } if (!is_array($returnGroupTypes[$typeName])) { - $returnGroupTypes[$typeName] = array(); + $returnGroupTypes[$typeName] = []; } $returnGroupTypes[$typeName][$valueParts[0]] = $groupTypeValues; } @@ -518,7 +492,7 @@ public static function extractGroupTypes($groupType) { public static function formatGroupTypes($groupTypes) { $groupTypesString = ''; if (!empty($groupTypes)) { - $groupTypesStrings = array(); + $groupTypesStrings = []; foreach ($groupTypes as $groupType => $typeValues) { if (is_array($typeValues)) { if ($groupType == 'Participant') { diff --git a/CRM/UF/Page/ProfileEditor.php b/CRM/UF/Page/ProfileEditor.php index 0102392..de37871 100644 --- a/CRM/UF/Page/ProfileEditor.php +++ b/CRM/UF/Page/ProfileEditor.php @@ -7,6 +7,7 @@ * widgets */ class CRM_UF_Page_ProfileEditor extends CRM_Core_Page { + /** * Run page. * @@ -28,11 +29,11 @@ public static function registerProfileScripts() { CRM_Core_Resources::singleton() ->addSettingsFactory(function () { - $ufGroups = civicrm_api3('UFGroup', 'get', array( + $ufGroups = civicrm_api3('UFGroup', 'get', [ 'sequential' => 1, 'is_active' => 1, - 'options' => array('limit' => 0), - )); + 'options' => ['limit' => 0], + ]); //CRM-16915 - insert 'module' param for the profile used by CiviEvent. if (CRM_Core_Permission::check('manage event profiles') && !CRM_Core_Permission::check('administer CiviCRM')) { foreach ($ufGroups['values'] as $key => $value) { @@ -42,16 +43,16 @@ public static function registerProfileScripts() { } } } - return array( - 'PseudoConstant' => array( + return [ + 'PseudoConstant' => [ 'locationType' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_Address', 'location_type_id'), 'websiteType' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_Website', 'website_type_id'), 'phoneType' => CRM_Core_PseudoConstant::get('CRM_Core_DAO_Phone', 'phone_type_id'), - ), + ], 'initialProfileList' => $ufGroups, 'contactSubTypes' => CRM_Contact_BAO_ContactType::subTypes(), 'profilePreviewKey' => CRM_Core_Key::get('CRM_UF_Form_Inline_Preview', TRUE), - ); + ]; }) ->addScriptFile('civicrm', 'packages/backbone/json2.js', 100, 'html-header', FALSE) ->addScriptFile('civicrm', 'packages/backbone/backbone.js', 120, 'html-header') @@ -75,9 +76,9 @@ public static function registerProfileScripts() { ->addScriptFile('civicrm', 'js/jquery/jquery.crmProfileSelector.js', 250) ->addScriptFile('civicrm', 'js/crm.designerapp.js', 250); - CRM_Core_Region::instance('page-header')->add(array( + CRM_Core_Region::instance('page-header')->add([ 'template' => 'CRM/UF/Page/ProfileTemplates.tpl', - )); + ]); } /** @@ -89,9 +90,9 @@ public static function registerProfileScripts() { public static function registerSchemas($entityTypes) { // TODO in cases where registerSchemas is called multiple times for same entity, be more efficient CRM_Core_Resources::singleton()->addSettingsFactory(function () use ($entityTypes) { - return array( + return [ 'civiSchema' => CRM_UF_Page_ProfileEditor::getSchema($entityTypes), - ); + ]; }); } @@ -120,7 +121,7 @@ public static function getSchema($entityTypes) { $entityTypes = array_unique($entityTypes); $availableFields = NULL; - $civiSchema = array(); + $civiSchema = []; foreach ($entityTypes as $entityType) { if (!$availableFields) { $availableFields = CRM_Core_BAO_UFField::getAvailableFieldsFlat(); @@ -204,22 +205,22 @@ public static function getSchema($entityTypes) { } // Adding the oddball "formatting" field here because there's no other place to put it - foreach (array('Individual', 'Organization', 'Household') as $type) { + foreach (['Individual', 'Organization', 'Household'] as $type) { if (isset($civiSchema[$type . 'Model'])) { - $civiSchema[$type . 'Model']['schema'] += array( - 'formatting' => array( + $civiSchema[$type . 'Model']['schema'] += [ + 'formatting' => [ 'type' => 'Markup', 'title' => ts('Free HTML'), 'civiFieldType' => 'Formatting', 'section' => 'formatting', - ), - ); - $civiSchema[$type . 'Model']['sections'] += array( - 'formatting' => array( + ], + ]; + $civiSchema[$type . 'Model']['sections'] += [ + 'formatting' => [ 'title' => ts('Formatting'), 'is_addable' => FALSE, - ), - ); + ], + ]; } } @@ -271,28 +272,28 @@ public static function convertCiviModelToBackboneModel($extends, $title, $availa } } // FIXME: type set to "Text" - $result['schema'][$fieldName] = array( + $result['schema'][$fieldName] = [ 'type' => 'Text', 'title' => $field['title'], 'civiFieldType' => $field['field_type'], - ); + ]; if (in_array($fieldName, $locationFields)) { $result['schema'][$fieldName]['civiIsLocation'] = TRUE; } if ($fieldName == 'url') { $result['schema'][$fieldName]['civiIsWebsite'] = TRUE; } - if (in_array($fieldName, array('phone', 'phone_and_ext'))) { + if (in_array($fieldName, ['phone', 'phone_and_ext'])) { // FIXME what about phone_ext? $result['schema'][$fieldName]['civiIsPhone'] = TRUE; } } // build section list - $result['sections']['default'] = array( + $result['sections']['default'] = [ 'title' => $title, 'is_addable' => FALSE, - ); + ]; $customGroup = CRM_Core_BAO_CustomGroup::getAllCustomGroupsByBaseEntity($extends); $customGroup->orderBy('weight'); @@ -300,14 +301,14 @@ public static function convertCiviModelToBackboneModel($extends, $title, $availa $customGroup->find(); while ($customGroup->fetch()) { $sectionName = 'cg_' . $customGroup->id; - $section = array( - 'title' => ts('%1: %2', array(1 => $title, 2 => $customGroup->title)), + $section = [ + 'title' => ts('%1: %2', [1 => $title, 2 => $customGroup->title]), 'is_addable' => $customGroup->is_reserved ? FALSE : TRUE, 'custom_group_id' => $customGroup->id, 'extends_entity_column_id' => $customGroup->extends_entity_column_id, 'extends_entity_column_value' => CRM_Utils_Array::explodePadded($customGroup->extends_entity_column_value), 'is_reserved' => $customGroup->is_reserved ? TRUE : FALSE, - ); + ]; $result['sections'][$sectionName] = $section; }